-
Notifications
You must be signed in to change notification settings - Fork 0
/
socketServer.js
147 lines (121 loc) · 4.04 KB
/
socketServer.js
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
import _ from 'lodash';
import * as db from './db';
import Timer from './timer';
let IO;
// TODO: This is necessary because different rooms need to access the same timer
// Longer-term solution involves an adapter?
// For now, enabled session affinity (https://devcenter.heroku.com/articles/node-websockets#option-2-socket-io-start-the-app)
// Also see: https://devcenter.heroku.com/articles/websockets#application-architecture
const timers = {};
const connections = {};
function connectSocket(socket) {
// Each socket is associated with just one game id
const socketGameId = socket.handshake.query.gameId;
if (!socketGameId) {
return;
}
socket.join(socketGameId);
// If player is found, update player's game status to connected
updateConnection(true);
/**
* 1. Store updated game in db
* 2. Update other clients
*/
socket.on('move', ({ data, boardNum, nextColor, isCapture }) => {
// If checkmate, end timer. TODO: Restart timer
const timer = timers[socketGameId];
if (timer) {
if (data.winner) {
timer.endTimer();
} else {
timer.updateTurn(boardNum, nextColor);
}
} else {
console.error('Timer not found');
}
socket.to(socketGameId).emit('pushMove', {
data, boardNum, isCapture
});
db.addPosition(socketGameId, data.newPosition);
db.addMove(socketGameId, boardNum, data.move);
db.updateGame(socketGameId, { winner: data.winner });
});
/*
* Join game as a player
*/
socket.on('join', (data) => {
// If all users have joined, start game
db.getGame(socketGameId).then((result) => {
const { boardNum, color, username, isConnected } = data;
if (!connections[socketGameId]) {
connections[socketGameId] = [{}, {}];
}
connections[socketGameId][boardNum][color] = isConnected;
const allConnected = _.every(connections[socketGameId], board => board.w && board.b);
if (allConnected && !timers[socketGameId]) {
// Start game timer
const timer = new Timer();
timers[socketGameId] = timer;
timer.startTimer(emitTime, endGame);
}
});
IO.to(socketGameId).emit('pushJoin', data);
db.updatePlayer(socketGameId, data);
});
/*
* Store username associated with a game in the user's session
*/
socket.on('setUsername', (data) => {
const { username } = data;
// Save username for a given game in session
socket.request.session[socketGameId] = { username };
socket.request.session.save();
});
/*
* Update player's game status to disconnected
*/
socket.on('disconnect', () => {
console.debug('disconnect', socketGameId);
if (!socketGameId) {
return;
}
updateConnection(false);
});
/******************** HELPERS *********************/
function updateConnection(isConnected) {
const { username } = socket.request.session[socketGameId] || {};
db.getGame(socketGameId).then((result) => {
const initialConnections = connections[socketGameId] || [{}, {}];
// Update connections for all user's players
connections[socketGameId] = _.reduce(result.currentGames, (memo, game, boardNum) => {
['w', 'b'].forEach(color => {
if (game[`${color}Player`] === username) {
memo[boardNum][color] = isConnected;
}
});
return memo;
}, initialConnections);
IO.to(socketGameId).emit('updateGame', {
connections: connections[socketGameId]
});
});
}
function emitTime(timers) {
// TODO: Write timers to db in case server crashes
// Cache in memory, with db as fallback
// db.updateGame(socketGameId, timers);
IO.to(socketGameId).emit('updateGame', { timers });
}
function endGame({ boardNum, color }) {
const gameData = { winner: { boardNum, color } };
db.updateGame(socketGameId, gameData);
IO.to(socketGameId).emit('updateGame', gameData);
}
}
export default {
attach: function attach(io) {
io.on('connection', connectSocket);
IO = io;
},
connections // TODO: Move to own module
};