-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase-sync.js
More file actions
350 lines (314 loc) · 16.6 KB
/
Copy pathfirebase-sync.js
File metadata and controls
350 lines (314 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// RealtimeUpdates class — Firebase read/write for grid objects, room membership,
// tutorial page progression, and final_game listeners.
// Game-flow methods (start/stop/phase) are mixed in from firebase-game-flow.js.
//
// Depends on: window.grid, window.userId, window.showWaitModal,
// window.hideWaitModal, window.onConnectionSetup,
// window.onPhaseChanged, window.onDijkstraOwnerChanged,
// window.onPhaseStartTimeChanged, window.onClaimedBotsChanged,
// window.resetBotOptions, window.setupSelectedBot
// MOVEMENT_VALUES from grid.js (<script>)
import {
ref, set, push, onValue, update, get,
onChildAdded, onChildRemoved, remove,
} from "https://www.gstatic.com/firebasejs/9.22.0/firebase-database.js";
import { db } from "./firebase-init.js";
import { generateName } from "./name.js";
import { mixinGameFlow } from "./firebase-game-flow.js";
const PAGE_ORDER = [
"tutorial1", "game1",
"tutorial2", "game2",
"tutorial3", "game3",
"tutorial4", "game4",
"tutorial5", "final_game",
];
const is_game_page = (page) => page.startsWith("game") || page === "final_game";
const getNextPage = (page) => {
const idx = PAGE_ORDER.indexOf(page);
if (idx === -1) console.error(`Page ${page} not in PAGE_ORDER`);
const next_page = PAGE_ORDER[idx + 1];
return { is_game: is_game_page(next_page), next_page };
};
const GAME_TO_THEME = { game1: "None", game2: "School", game3: "City", game4: "Pacman" };
const DEFAULT_ROOM_INFO = {
min_users_to_move: 2,
users: {},
seen_tutorial: false,
tutorial1: { users_done: {}, min_users_to_move: 2 },
tutorial2: { users_done: {}, min_users_to_move: 2 },
tutorial3: { users_done: {}, min_users_to_move: 2 },
tutorial4: { users_done: {}, min_users_to_move: 2 },
tutorial5: { users_done: {}, min_users_to_move: 2 },
game1: { users_done: {}, min_users_to_move: 2, started: {}, grid: { bots: {}, obstacles: {}, coins: {} } },
game2: { users_done: {}, min_users_to_move: 2, started: {}, grid: { bots: {}, obstacles: {}, coins: {} } },
game3: { users_done: {}, min_users_to_move: 2, started: {}, grid: { bots: {}, obstacles: {}, coins: {} } },
game4: { users_done: {}, min_users_to_move: 2, started: {}, grid: { bots: {}, obstacles: {}, coins: {} } },
final_game: {
min_users_to_move: 2, started: {}, claimed_bots: {},
phase: 1, dijkstra_owner: null, phase_start_time: null,
grid: { bots: {}, obstacles: {}, coins: {}, options: { theme: "", mode: "" } },
},
};
export class RealtimeUpdates {
constructor() {
this.roomRef = null;
this.usersRef = null;
this.numUsersRef = null;
this.startedGameRef = null;
this.claimedBotsRef = null;
this.phaseRef = null;
this.dijkstraOwnerRef = null;
this.phaseStartTimeRef = null;
this.local_phase = 1;
this.pages_ref = {};
this.users_done_ref = {};
this.bot_refs = { game1: {}, game2: {}, game3: {}, game4: {}, final_game: {} };
this.obstacle_refs = { game1: {}, game2: {}, game3: {}, game4: {}, final_game: {} };
this.coin_refs = { game1: {}, game2: {}, game3: {}, game4: { require_graph: {} }, final_game: {} };
this.room_info = DEFAULT_ROOM_INFO;
}
/*──── Room ────────────────────────────────────────────────────────────────*/
create_room(data) {
const room_key = generateName();
console.log("[ROOM] Creating room:", room_key);
set(ref(db, `rooms/${room_key}`), this.room_info)
.then(() => console.log("[ROOM] Room written:", room_key))
.catch(err => console.error("[ROOM] Failed:", err));
const el = document.getElementById("roomIdBold");
if (el) el.innerHTML = `<strong style='color:black;'>Your room ID is: ${room_key}</strong>`;
this.join_room_page({ roomId: room_key, html_page: "rooms", curr_page: "rooms" });
}
async join_room_page(data) {
const { roomId, curr_page, html_page } = data;
this.curr_page = curr_page;
this.current_room = roomId;
this.html_page = html_page;
console.log(`[JOIN] room: ${roomId}, page: ${curr_page}, userId: ${window.userId}`);
this.roomRef = ref(db, `rooms/${this.current_room}`);
this.usersRef = ref(db, `rooms/${this.current_room}/users`);
let prev;
try {
prev = await get(this.roomRef);
console.log("[JOIN] room exists:", prev.exists());
} catch (err) {
console.error("[JOIN] Firebase room read FAILED:", err);
return;
}
this.room_info = Object.assign({}, prev.val(), this.room_info);
if (!prev.exists()) console.warn(`[JOIN] Room "${this.current_room}" does not exist.`);
onValue(this.usersRef, (snapshot) => {
const new_users = snapshot.val() || {};
const count = Object.keys(new_users).length;
const min = this.room_info.min_users_to_move;
console.log(`[USERS] count: ${count}, min: ${min}, page: ${this.curr_page}`);
this.room_info.users = new_users;
if (this.curr_page === "rooms" && count === min) {
const t = window.selectedTheme || this.selected_theme || "None";
window.location.href = `tutorial1.html?room=${this.current_room}&theme=${t}`;
}
});
// Skip-tutorials signal
if (curr_page.startsWith("tutorial")) {
const skipRef = ref(db, `rooms/${this.current_room}/skip_tutorials`);
onValue(skipRef, (snapshot) => {
if (snapshot.val() === true && this.curr_page.startsWith("tutorial")) {
const theme = this.selected_theme || "None";
window.location.href = `virtualMode.html?room=${this.current_room}&option=${theme}&mode=virtual`;
}
});
}
for (const page of PAGE_ORDER) {
if (page === "final_game") continue;
const usersDoneRef = ref(db, `rooms/${this.current_room}/${page}/users_done`);
this.users_done_ref[page] = usersDoneRef;
onValue(usersDoneRef, (snapshot) => {
const new_users = snapshot.val() || {};
const doneCount = Object.keys(new_users).length;
const doneMin = this.room_info[page]?.min_users_to_move;
console.log(`[DONE] page: ${page}, curr: ${this.curr_page}, count: ${doneCount}, min: ${doneMin}`);
this.room_info[page].users_done = new_users;
if (this.curr_page === page && doneCount === doneMin) {
this.move_to_next_page(page);
}
});
}
if (is_game_page(curr_page) && html_page !== "index") {
this.startedGameRef = ref(db, `rooms/${this.current_room}/${curr_page}/started`);
onValue(this.startedGameRef, (snapshot) => {
const curr_started = snapshot.val() || {};
this.room_info[curr_page].started = curr_started;
const num_started = Object.keys(curr_started).length;
const min_users = this.room_info[curr_page].min_users_to_move || 2;
console.log(`[STARTED] page=${curr_page} num=${num_started} min=${min_users} data=`, JSON.stringify(curr_started));
const body = document.getElementById("body");
if (num_started === min_users) {
console.log(`[STARTED] → calling start_game_for_everyone`);
this.start_game_for_everyone();
} else {
for (const user_key in curr_started) {
if (user_key !== window.userId) {
if (curr_started[user_key]) body.setAttribute("show-other-user-ready", "");
else body.removeAttribute("show-other-user-ready");
}
}
if (curr_started[window.userId] && window.showWaitModal) window.showWaitModal();
if (num_started === 0) this.stop_moving_bot();
}
});
this.requireGraphRef = ref(db, `rooms/${this.current_room}/${curr_page}/require_graph`);
this.botsRef = ref(db, `rooms/${this.current_room}/${curr_page}/grid/bots`);
this.obstaclesRef = ref(db, `rooms/${this.current_room}/${curr_page}/grid/obstacles`);
this.coinsRef = ref(db, `rooms/${this.current_room}/${curr_page}/grid/coins`);
onChildAdded(this.botsRef, (snapshot) => {
const bot = snapshot.val();
const key = bot.userId;
const bot_ref = ref(db, `rooms/${this.current_room}/${curr_page}/grid/bots/${key}`);
this.bot_refs[curr_page][key] = bot_ref;
onValue(bot_ref, (snap) => {
const b = snap.val();
if (!b) return;
if (!this.room_info[curr_page].grid) this.room_info[curr_page].grid = { bots: {}, obstacles: {}, coins: {} };
if (!this.room_info[curr_page].grid.bots) this.room_info[curr_page].grid.bots = {};
this.room_info[curr_page].grid.bots[key] = b;
window.grid.replace_bot(b.id, b, { is_new: false, fromSocket: true });
this.reset_default_require_graph();
});
if (key === window.userId) {
window.currentBotId = bot.id;
if (window.setupSelectedBot) window.setupSelectedBot(bot);
if (curr_page === "final_game" && window.resetBotOptions) window.resetBotOptions(bot);
}
});
onChildRemoved(this.botsRef, (snapshot) => {
const bot = snapshot.val();
delete this.room_info[this.curr_page].grid.bots[bot.id];
delete this.bot_refs[this.curr_page][bot.id];
window.grid.remove_bot(bot.id, { fromSocket: true });
this.reset_default_require_graph();
});
onChildAdded(this.coinsRef, (snapshot) => {
const coin = snapshot.val();
const key = coin.id;
window.grid.replace_coin(coin.id, coin, { is_new: true, fromSocket: true });
const coin_ref = ref(db, `rooms/${this.current_room}/${curr_page}/grid/coins/${key}`);
this.coin_refs[curr_page][key] = coin_ref;
onValue(coin_ref, (snap) => {
const c = snap.val();
if (!c) return;
if (!this.room_info[curr_page].grid) this.room_info[curr_page].grid = { bots: {}, obstacles: {}, coins: {} };
if (!this.room_info[curr_page].grid.coins) this.room_info[curr_page].grid.coins = {};
this.room_info[curr_page].grid.coins[key] = c;
window.grid.replace_coin(c.id, c, { is_new: false, fromSocket: true });
this.reset_default_require_graph();
});
this.reset_default_require_graph();
});
onChildRemoved(this.coinsRef, (snapshot) => {
const coin = snapshot.val();
delete this.room_info[this.curr_page].grid.coins[coin.id];
delete this.coin_refs[this.curr_page][coin.id];
window.grid.remove_coin(coin.id, { fromSocket: true });
this.reset_default_require_graph();
});
onChildAdded(this.obstaclesRef, (snapshot) => {
const obstacle = snapshot.val();
const key = obstacle.id;
window.grid.replace_obstacle(obstacle.id, obstacle, { is_new: true, fromSocket: true });
const obs_ref = ref(db, `rooms/${this.current_room}/${curr_page}/grid/obstacles/${key}`);
this.obstacle_refs[curr_page][key] = obs_ref;
onValue(obs_ref, (snap) => {
const o = snap.val();
if (!o) return;
if (!this.room_info[curr_page].grid) this.room_info[curr_page].grid = { bots: {}, obstacles: {}, coins: {} };
if (!this.room_info[curr_page].grid.obstacles) this.room_info[curr_page].grid.obstacles = {};
this.room_info[curr_page].grid.obstacles[key] = o;
window.grid.replace_obstacle(o.id, o, { is_new: false, fromSocket: true });
this.reset_default_require_graph();
});
this.reset_default_require_graph();
});
onChildRemoved(this.obstaclesRef, (snapshot) => {
const obstacle = snapshot.val();
delete this.room_info[this.curr_page].grid.obstacles[obstacle.id];
delete this.obstacle_refs[this.curr_page][obstacle.id];
window.grid.remove_obstacle(obstacle.id, { fromSocket: true });
this.reset_default_require_graph();
});
}
// Final-game: claimed bots + phase listeners
if (curr_page === "final_game" && html_page !== "index") {
this.claimedBotsRef = ref(db, `rooms/${this.current_room}/final_game/claimed_bots`);
onValue(this.claimedBotsRef, (snap) => {
if (window.onClaimedBotsChanged) window.onClaimedBotsChanged(snap.val() || {});
});
this.phaseRef = ref(db, `rooms/${this.current_room}/final_game/phase`);
this.dijkstraOwnerRef = ref(db, `rooms/${this.current_room}/final_game/dijkstra_owner`);
this.phaseStartTimeRef = ref(db, `rooms/${this.current_room}/final_game/phase_start_time`);
onValue(this.phaseRef, (snap) => { console.log(`[PHASE_REF] raw value=`, snap.val()); this.local_phase = snap.val() || 1; if (window.onPhaseChanged) window.onPhaseChanged(this.local_phase); });
onValue(this.dijkstraOwnerRef, (snap) => { if (window.onDijkstraOwnerChanged) window.onDijkstraOwnerChanged(snap.val()); });
onValue(this.phaseStartTimeRef,(snap) => { console.log(`[PHASE_START_TIME_REF] raw value=`, snap.val()); if (window.onPhaseStartTimeChanged) window.onPhaseStartTimeChanged(snap.val()); });
}
console.log(`[JOIN] Writing user — userId: ${window.userId}`);
update(this.usersRef, { [window.userId]: true })
.then(() => console.log("[JOIN] User write succeeded"))
.catch(err => console.error("[JOIN] User write FAILED:", err));
}
/*──── CRUD helpers ────────────────────────────────────────────────────────*/
reset_default_require_graph() {
for (let bot_id in window.grid.bots) {
bot_id = Number(bot_id);
const require_graph = window.grid.bots[bot_id][0].movement_type === MOVEMENT_VALUES.DIJKSTRA.value;
this.change_require_graph({ bot_id, require_graph });
}
}
add_bot(data) { const { bot } = data; update(this.botsRef, { [window.userId]: { ...bot, userId: window.userId } }); }
add_obstacle(data) { const { obstacle } = data; update(this.obstaclesRef, { [obstacle.id]: obstacle }); }
add_coin(data) { const { coin } = data; update(this.coinsRef, { [coin.id]: coin }); }
replace_bot(data) { const { bot } = data; update(this.bot_refs[this.curr_page][bot.userId], bot); }
replace_obstacle(data) { const { obstacle_id, obstacle } = data; update(this.obstacle_refs[this.curr_page][obstacle_id], obstacle); }
replace_coin(data) { const { coin_id, coin } = data; update(this.coin_refs[this.curr_page][coin_id], coin); }
remove_bot(data) { const { bot } = data; remove(this.bot_refs[this.curr_page][bot.userId]); }
remove_obstacle(data) { const { obstacle } = data; remove(this.obstacle_refs[this.curr_page][obstacle.id]); }
remove_coin(data) { const { coin } = data; remove(this.coin_refs[this.curr_page][coin.id]); }
change_require_graph(data) {
const { bot_id, require_graph } = data;
const owner = window.grid.bots[bot_id][0].userId;
const result = require_graph ? true : null;
update(this.requireGraphRef, { [owner]: result });
}
finish_page(data) {
const { page } = data;
console.log(`[FINISH] page: ${page}, userId: ${window.userId}`);
update(this.users_done_ref[page], { [window.userId]: true })
.then(() => console.log(`[FINISH] users_done written for ${page}`))
.catch(err => console.error(`[FINISH] FAILED for ${page}:`, err));
}
skip_to_game() {
set(ref(db, `rooms/${this.current_room}/skip_tutorials`), true)
.then(() => console.log("[SKIP] skip_tutorials set"))
.catch(err => console.error("[SKIP] Failed:", err));
}
/*──── Navigation ──────────────────────────────────────────────────────────*/
get_bot_id() {
const all_users = Object.keys(this.room_info.users).sort();
const idx = all_users.indexOf(window.userId);
if (idx === -1) { console.error(`User ${window.userId} not in users list`); return 1; }
return idx + 1;
}
move_to_next_page(curr_page) {
const { next_page, is_game } = getNextPage(curr_page);
const playerTheme = this.selected_theme || "None";
if (next_page === "final_game") {
window.location.href = `virtualMode.html?room=${this.current_room}&option=${playerTheme}&mode=virtual`;
return;
}
if (is_game) {
const gameTheme = GAME_TO_THEME[next_page];
window.location.href = `virtualMode.html?option=${gameTheme}&mode=virtual&room=${this.current_room}&tutorial=${next_page}&theme=${playerTheme}&bot_id=${this.get_bot_id()}`;
} else {
window.location.href = `${next_page}.html?room=${this.current_room}&theme=${playerTheme}`;
}
}
}
// Mix game-flow methods (start/stop/phase) into the class
mixinGameFlow(RealtimeUpdates);