1 const params
= require("./parameters.js");
2 const WebSocket
= require("ws");
3 const wss
= new WebSocket
.Server({
4 port: params
.socket_port
,
5 path: params
.socket_path
8 let challenges
= {}; //variantName --> socketId, name
9 let games
= {}; //gameId --> gameInfo (vname, fen, players, options, time)
10 let moveHash
= {}; //gameId --> set of hashes seen so far
11 let sockets
= {}; //socketId --> socket
12 const variants
= require("./variants.js");
13 const Crypto
= require("crypto");
14 const randstrSize
= 8;
16 function send(sid
, code
, data
) {
17 const socket
= sockets
[sid
];
18 // If a player deletes local infos and then tries to resume a game,
19 // sockets[oppSid] will probably not exist anymore:
21 socket
.send(JSON
.stringify(Object
.assign({code: code
}, data
)));
24 function initializeGame(vname
, players
, options
) {
26 Crypto
.randomBytes(randstrSize
).toString("hex").slice(0, randstrSize
);
36 // Provide seed in case of, so that both players initialize with same FEN
37 function launchGame(gid
) {
39 const gameInfo
= Object
.assign(
40 {seed: Math
.floor(Math
.random() * 1984), gid: gid
},
43 // players array is supposed to be full:
44 for (const p
of games
[gid
].players
) {
47 Object
.assign({randvar: p
.randvar
}, gameInfo
));
51 function getRandomVariant() {
52 // Pick a variant at random in the list
53 const index
= Math
.floor(Math
.random() * variants
.length
);
54 return variants
[index
].name
;
57 wss
.on("connection", (socket
, req
) => {
58 const sid
= req
.url
.split("=")[1]; //...?sid=...
59 sockets
[sid
] = socket
;
60 socket
.isAlive
= true;
61 socket
.on("pong", () => socket
.isAlive
= true);
63 socket
.on("message", (msg
) => {
64 const obj
= JSON
.parse(msg
);
66 // Send challenge (may trigger game creation)
68 let oppIndex
= undefined, //variant name
69 choice
= undefined; //variant finally played
70 const vname
= obj
.vname
, //variant requested
71 randvar
= (obj
.vname
== "_random");
72 if (vname
== "_random") {
73 // Pick any current challenge if possible
74 const currentChalls
= Object
.keys(challenges
);
75 if (currentChalls
.length
>= 1) {
77 currentChalls
[Math
.floor(Math
.random() * currentChalls
.length
)];
81 else if (challenges
[vname
]) {
82 // Anyone wanting to play the same variant ?
86 else if (challenges
["_random"]) {
87 // Anyone accepting any variant (including vname) ?
92 if (choice
== "_random")
93 choice
= getRandomVariant();
96 {sid: sid
, name: obj
.name
, randvar: randvar
},
97 Object
.assign({}, challenges
[oppIndex
])
99 delete challenges
[oppIndex
];
100 if (Math
.random() < 0.5)
101 players
= players
.reverse();
102 // Empty options = default
103 launchGame( initializeGame(choice
, players
, {}) );
106 // Place challenge and wait. 'randvar' indicate if we play anything
107 challenges
[vname
] = {sid: sid
, name: obj
.name
, randvar: randvar
};
110 // Set FEN after game was created (received twice)
112 games
[obj
.gid
].fen
= obj
.fen
;
114 // Send back game informations
119 send(sid
, "gameinfo", games
[obj
.gid
]);
123 delete challenges
[obj
.vname
];
128 send(sid
, "closerematch");
130 const myIndex
= (games
[obj
.gid
].players
[0].sid
== sid
? 0 : 1);
131 if (!games
[obj
.gid
].rematch
)
132 games
[obj
.gid
].rematch
= [0, 0];
133 games
[obj
.gid
].rematch
[myIndex
] = !obj
.random
? 1 : 2;
134 if (games
[obj
.gid
].rematch
[1-myIndex
]) {
135 // Launch new game, colors reversed
136 let vname
= games
[obj
.gid
].vname
;
137 const allrand
= games
[obj
.gid
].rematch
.every(r
=> r
== 2);
139 vname
= getRandomVariant();
140 games
[obj
.gid
].players
.forEach(p
=>
141 p
.randvar
= allrand
? true : false);
142 const gid
= initializeGame(vname
,
143 games
[obj
.gid
].players
.reverse(),
144 games
[obj
.gid
].options
);
149 // Rematch cancellation
151 if (games
[obj
.gid
]) {
152 const myIndex
= (games
[obj
.gid
].players
[0].sid
== sid
? 0 : 1);
153 send(games
[obj
.gid
].players
[1-myIndex
].sid
, "closerematch");
156 // Create game vs. friend
159 {sid: obj
.player
.sid
, name: obj
.player
.name
},
163 obj
.player
.color
== 'b' ||
164 (obj
.player
.color
== '' && Math
.random() < 0.5)
166 players
= players
.reverse();
168 // Incomplete players array: do not start game yet
169 const gid
= initializeGame(obj
.vname
, players
, obj
.options
);
170 send(sid
, "gamecreated", {gid: gid
});
171 // If nobody joins within 3 minutes, delete game
174 if (games
[gid
] && games
[gid
].players
.some(p
=> !p
))
181 // Join game vs. friend
184 send(sid
, "jointoolate");
186 const emptySlot
= games
[obj
.gid
].players
.findIndex(p
=> !p
);
188 send(sid
, "jointoolate");
190 // Join a game (started by some other player)
191 games
[obj
.gid
].players
[emptySlot
] = {sid: sid
, name: obj
.name
};
196 // Relay a move + update games object
198 // NOTE: still potential racing issues, but... fingers crossed
199 const hash
= Crypto
.createHash("md5")
200 .update(JSON
.stringify(obj
.fen
))
204 moveHash
[hash
] = true;
205 games
[obj
.gid
].fen
= obj
.fen
;
206 games
[obj
.gid
].time
= Date
.now(); //update timestamp in case of
207 const playingWhite
= (games
[obj
.gid
].players
[0].sid
== sid
);
208 const oppSid
= games
[obj
.gid
].players
[playingWhite
? 1 : 0].sid
;
209 send(oppSid
, "newmove", {moves: obj
.moves
});
211 // Relay "game ends" message
214 const playingWhite
= (games
[obj
.gid
].players
[0].sid
== sid
);
215 const oppSid
= games
[obj
.gid
].players
[playingWhite
? 1 : 0].sid
;
216 send(oppSid
, "gameover", { gid: obj
.gid
});
218 // 2 minutes timeout for rematch:
219 setTimeout(() => delete games
[obj
.gid
], 2 * 60000);
223 socket
.on("close", () => {
225 for (const [key
, value
] of Object
.entries(challenges
)) {
226 if (value
.sid
== sid
) {
227 delete challenges
[key
];
228 break; //only one challenge per player
231 for (let g
of Object
.values(games
)) {
232 const myIndex
= g
.players
.findIndex(p
=> p
&& p
.sid
== sid
);
234 if (g
.rematch
&& g
.rematch
[myIndex
] > 0) g
.rematch
[myIndex
] = 0;
235 break; //only one game per player
241 const heartbeat
= setInterval(() => {
242 wss
.clients
.forEach((ws
) => {
243 if (ws
.isAlive
=== false)
244 return ws
.terminate();
250 // Every 24 hours, scan games and remove if last move older than 24h
251 const dayInMillisecs
= 24 * 60 * 60 * 1000;
252 const killOldGames
= setInterval(() => {
253 const now
= Date
.now();
254 Object
.keys(games
).forEach(gid
=> {
255 if (now
- games
[gid
].time
>= dayInMillisecs
)
260 // TODO: useful code here?
261 wss
.on("close", () => {
262 clearInterval(heartbeat
);
263 clearInterval(killOldGames
);