👤
TIN HỌC 10 TIN HỌC 11 TIN HỌC 12 TRỢ LÝ TÀI NĂNG HỌC TẬP ONLINE ÔN THI TỐT NGHIỆP
DANH MỤC ×

KẾT NỐI HỆ THỐNG (GAME THI ĐẤU)

// File: ket_noi_he_thong.js import { initializeApp } from "https://www.gstatic.com/firebasejs/10.0.0/firebase-app.js"; import { getDatabase, ref, set, update, onValue, get } from "https://www.gstatic.com/firebasejs/10.0.0/firebase-database.js"; // Tạo một "Công cụ vạn năng" gắn vào hệ thống trình duyệt window.CongCuThiDau = { db: null, studentId: "", isJoined: false, hasStarted: false, // 1. Hàm cắm điện: Kết nối Game với Firebase khoiTao: function(config, hamBatDauGame, hamLamMoiGame) { const app = initializeApp(config); this.db = getDatabase(app); // Liên tục nghe ngóng máy chủ onValue(ref(this.db, 'room/status'), (snapshot) => { const status = snapshot.val(); // Xử lý khi Thầy bấm Làm mới if (status === null && this.isJoined) { if (hamLamMoiGame) hamLamMoiGame(); else window.location.reload(); // Mặc định là ép F5 tải lại trang } // Xử lý khi Thầy bấm Bắt đầu if (status === 'playing' && this.isJoined && !this.hasStarted) { this.hasStarted = true; if (hamBatDauGame) hamBatDauGame(); } }); }, // 2. Hàm ghi danh: Cho học sinh nhập tên vaoPhong: function(tenHocSinh, hamHienManHinhCho, hamVaoThangGame) { if (!tenHocSinh || tenHocSinh.trim() === "") return alert("Em phải nhập tên!"); this.studentId = tenHocSinh.replace(/\s+/g, '_') + "_" + Math.floor(Math.random() * 1000); set(ref(this.db, 'room/players/' + this.studentId), { name: tenHocSinh, score: 0 }); this.isJoined = true; // Kiểm tra xem Thầy đã bấm Bắt đầu chưa get(ref(this.db, 'room/status')).then((snapshot) => { if (snapshot.val() === 'playing') { this.hasStarted = true; if (hamVaoThangGame) hamVaoThangGame(); // Trễ giờ -> vô luôn } else { if (hamHienManHinhCho) hamHienManHinhCho(); // Sớm giờ -> chờ lệnh } }); }, // 3. Hàm báo cáo: Gửi điểm về máy chủ (Dùng bất cứ lúc nào học sinh làm đúng) guiDiem: function(diemMoi) { if (!this.isJoined) return; update(ref(this.db, 'room/players/' + this.studentId), { score: diemMoi }); } };