-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiplayer.js
More file actions
61 lines (56 loc) · 1.52 KB
/
Copy pathmultiplayer.js
File metadata and controls
61 lines (56 loc) · 1.52 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
/**
* Multiplayer state synchronisation module.
* Pushes game state to Supabase and subscribes to changes from other players.
*/
var Multiplayer = (function () {
var channel = null;
async function saveGameState(roomId, state, userId) {
var result = await supabase
.from('game_state')
.upsert({
room_id: roomId,
state: state,
updated_by: userId,
updated_at: new Date().toISOString(),
version: (state._version || 0) + 1
});
if (result.error) throw result.error;
}
async function loadGameState(roomId) {
var result = await supabase
.from('game_state')
.select('*')
.eq('room_id', roomId)
.maybeSingle();
if (result.error) return null;
return result.data ? result.data.state : null;
}
function subscribeToGameState(roomId, onStateChange) {
channel = supabase
.channel('game-' + roomId)
.on('postgres_changes', {
event: '*',
schema: 'public',
table: 'game_state',
filter: 'room_id=eq.' + roomId
}, function (payload) {
if (payload.new && payload.new.state) {
onStateChange(payload.new.state, payload.new.updated_by);
}
})
.subscribe();
return channel;
}
function unsubscribe() {
if (channel) {
supabase.removeChannel(channel);
channel = null;
}
}
return {
saveGameState: saveGameState,
loadGameState: loadGameState,
subscribeToGameState: subscribeToGameState,
unsubscribe: unsubscribe
};
})();