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 sockets
= {}; //socketId --> socket
11 const variants
= require("./variants.js");
12 const Crypto
= require("crypto");
13 const randstrSize
= 8;
15 function send(sid
, code
, data
) {
16 const socket
= sockets
[sid
];
17 // If a player deletes local infos and then tries to resume a game,
18 // sockets[oppSid] will probably not exist anymore:
20 socket
.send(JSON
.stringify(Object
.assign({code: code
}, data
)));
23 function initializeGame(vname
, players
, options
) {
25 Crypto
.randomBytes(randstrSize
).toString("hex").slice(0, randstrSize
);
31 moveHash: {} //set of moves hashes seen so far
36 // Provide seed in case of, so that both players initialize with same FEN
37 function launchGame(gid
) {
38 const gameInfo
= Object
.assign(
39 {seed: Math
.floor(Math
.random() * 19840), gid: gid
},
42 // players array is supposed to be full:
43 for (const p
of games
[gid
].players
)
44 send(p
.sid
, "gamestart", gameInfo
);
47 function getRandomVariant() {
48 // Pick a variant at random in the list
49 const index
= Math
.floor(Math
.random() * variants
.length
);
50 return variants
[index
].name
;
53 wss
.on("connection", (socket
, req
) => {
54 const sid
= req
.url
.split("=")[1]; //...?sid=...
55 sockets
[sid
] = socket
;
56 socket
.isAlive
= true;
57 socket
.on("pong", () => socket
.isAlive
= true);
59 socket
.on("message", (msg
) => {
60 const obj
= JSON
.parse(msg
);
62 // Send challenge (may trigger game creation)
64 let oppIndex
= undefined, //variant name
65 choice
= undefined; //variant finally played
66 const vname
= obj
.vname
, //variant requested
67 randvar
= (obj
.vname
== "_random");
68 if (vname
== "_random") {
69 // Pick any current challenge if possible
70 const currentChalls
= Object
.keys(challenges
);
71 if (currentChalls
.length
>= 1) {
73 currentChalls
[Math
.floor(Math
.random() * currentChalls
.length
)];
77 else if (challenges
[vname
]) {
78 // Anyone wanting to play the same variant ?
82 else if (challenges
["_random"]) {
83 // Anyone accepting any variant (including vname) ?
88 if (choice
== "_random")
89 choice
= getRandomVariant();
92 {sid: sid
, name: obj
.name
, randvar: randvar
},
93 Object
.assign({}, challenges
[oppIndex
])
95 delete challenges
[oppIndex
];
96 if (Math
.random() < 0.5)
97 players
= players
.reverse();
98 // Empty options = default
99 launchGame( initializeGame(choice
, players
, {}) );
102 // Place challenge and wait. 'randvar' indicate if we play anything
103 challenges
[vname
] = {sid: sid
, name: obj
.name
, randvar: randvar
};
106 // Set FEN after game was created (received twice)
108 games
[obj
.gid
].fen
= obj
.fen
;
110 // Send back game informations
115 send(sid
, "gameinfo", games
[obj
.gid
]);
119 delete challenges
[obj
.vname
];
124 send(sid
, "closerematch");
126 const myIndex
= (games
[obj
.gid
].players
[0].sid
== sid
? 0 : 1);
127 if (!games
[obj
.gid
].rematch
)
128 games
[obj
.gid
].rematch
= [0, 0];
129 games
[obj
.gid
].rematch
[myIndex
] = !obj
.random
? 1 : 2;
130 if (games
[obj
.gid
].rematch
[1-myIndex
]) {
131 // Launch new game, colors reversed
132 let vname
= games
[obj
.gid
].vname
;
133 const allrand
= games
[obj
.gid
].rematch
.every(r
=> r
== 2);
135 vname
= getRandomVariant();
136 games
[obj
.gid
].players
.forEach(p
=> p
.randvar
= allrand
);
137 const gid
= initializeGame(vname
,
138 games
[obj
.gid
].players
.reverse(),
139 games
[obj
.gid
].options
);
144 // Rematch cancellation
146 if (games
[obj
.gid
]) {
147 const myIndex
= (games
[obj
.gid
].players
[0].sid
== sid
? 0 : 1);
148 send(games
[obj
.gid
].players
[1-myIndex
].sid
, "closerematch");
151 // Create game vs. friend
154 {sid: obj
.player
.sid
, name: obj
.player
.name
},
158 obj
.player
.color
== 'b' ||
159 (obj
.player
.color
== '' && Math
.random() < 0.5)
161 players
= players
.reverse();
163 // Incomplete players array: do not start game yet
164 const gid
= initializeGame(obj
.vname
, players
, obj
.options
);
165 send(sid
, "gamecreated", {gid: gid
});
166 // If nobody joins within 3 minutes, delete game
169 if (games
[gid
] && games
[gid
].players
.some(p
=> !p
))
176 // Join game vs. friend
179 send(sid
, "jointoolate");
181 const emptySlot
= games
[obj
.gid
].players
.findIndex(p
=> !p
);
183 send(sid
, "jointoolate");
185 // Join a game (started by some other player)
186 games
[obj
.gid
].players
[emptySlot
] = {sid: sid
, name: obj
.name
};
191 // Relay a move + update games object
193 // NOTE: still potential racing issues, but... fingers crossed
194 const hash
= Crypto
.createHash("md5")
195 .update(JSON
.stringify(obj
.fen
))
197 if (games
[obj
.gid
].moveHash
[hash
])
199 games
[obj
.gid
].moveHash
[hash
] = true;
200 games
[obj
.gid
].fen
= obj
.fen
;
201 games
[obj
.gid
].time
= Date
.now(); //update useful if verrry slow game
202 const playingWhite
= (games
[obj
.gid
].players
[0].sid
== sid
);
203 const oppSid
= games
[obj
.gid
].players
[playingWhite
? 1 : 0].sid
;
204 send(oppSid
, "newmove", {moves: obj
.moves
});
206 // Relay "game ends" message
209 const playingWhite
= (games
[obj
.gid
].players
[0].sid
== sid
);
210 const oppSid
= games
[obj
.gid
].players
[playingWhite
? 1 : 0].sid
;
211 send(oppSid
, "gameover", { gid: obj
.gid
});
213 // 2 minutes timeout for rematch:
214 setTimeout(() => delete games
[obj
.gid
], 2 * 60000);
218 socket
.on("close", () => {
220 for (const [key
, value
] of Object
.entries(challenges
)) {
221 if (value
.sid
== sid
) {
222 delete challenges
[key
];
223 break; //only one challenge per player
226 for (let g
of Object
.values(games
)) {
227 const myIndex
= g
.players
.findIndex(p
=> p
&& p
.sid
== sid
);
229 if (g
.rematch
&& g
.rematch
[myIndex
] > 0) g
.rematch
[myIndex
] = 0;
230 break; //only one game per player
236 const heartbeat
= setInterval(() => {
237 wss
.clients
.forEach((ws
) => {
238 if (ws
.isAlive
=== false)
239 return ws
.terminate();
245 // Every 24 hours, scan games and remove if last move older than 24h
246 const dayInMillisecs
= 24 * 60 * 60 * 1000;
247 const killOldGames
= setInterval(() => {
248 const now
= Date
.now();
249 Object
.keys(games
).forEach(gid
=> {
250 if (now
- games
[gid
].time
>= dayInMillisecs
)
255 // TODO: useful code here?
256 wss
.on("close", () => {
257 clearInterval(heartbeat
);
258 clearInterval(killOldGames
);