5661136105a2d50628a72695b48a93ed7532eb78
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
);
35 // Provide seed in case of, so that both players initialize with same FEN
36 function launchGame(gid
) {
37 const gameInfo
= Object
.assign(
38 {seed: Math
.floor(Math
.random() * 1984), gid: gid
},
41 // players array is supposed to be full:
42 for (const p
of games
[gid
].players
) {
45 Object
.assign({randvar: p
.randvar
}, gameInfo
));
49 function getRandomVariant() {
50 // Pick a variant at random in the list
51 const index
= Math
.floor(Math
.random() * variants
.length
);
52 return variants
[index
].name
;
55 wss
.on("connection", (socket
, req
) => {
56 const sid
= req
.url
.split("=")[1]; //...?sid=...
57 sockets
[sid
] = socket
;
58 socket
.isAlive
= true;
59 socket
.on("pong", () => socket
.isAlive
= true);
61 socket
.on("message", (msg
) => {
62 const obj
= JSON
.parse(msg
);
64 // Send challenge (may trigger game creation)
66 let opponent
= undefined,
68 const vname
= obj
.vname
,
69 randvar
= (obj
.vname
== "_random");
70 if (vname
== "_random") {
71 // Pick any current challenge if possible
72 const currentChalls
= Object
.keys(challenges
);
73 if (currentChalls
.length
>= 1) {
75 currentChalls
[Math
.floor(Math
.random() * currentChalls
.length
)];
76 opponent
= challenges
[choice
];
79 else if (challenges
[vname
]) {
80 opponent
= challenges
[vname
];
84 delete challenges
[choice
];
85 if (choice
== "_random")
86 choice
= getRandomVariant();
89 {sid: sid
, name: obj
.name
, randvar: randvar
},
92 if (Math
.random() < 0.5)
93 players
= players
.reverse();
94 // Empty options = default
95 launchGame( initializeGame(choice
, players
, {}) );
98 // Place challenge and wait. 'randvar' indicate if we play anything
99 challenges
[vname
] = {sid: sid
, name: obj
.name
, randvar: randvar
};
102 // Set FEN after game was created (received twice)
104 games
[obj
.gid
].fen
= obj
.fen
;
106 // Send back game informations
111 send(sid
, "gameinfo", games
[obj
.gid
]);
115 delete challenges
[obj
.vname
];
120 send(sid
, "closerematch");
122 const myIndex
= (games
[obj
.gid
].players
[0].sid
== sid
? 0 : 1);
123 if (!games
[obj
.gid
].rematch
)
124 games
[obj
.gid
].rematch
= [0, 0];
125 games
[obj
.gid
].rematch
[myIndex
] = !obj
.random
? 1 : 2;
126 if (games
[obj
.gid
].rematch
[1-myIndex
]) {
127 // Launch new game, colors reversed
128 let vname
= games
[obj
.gid
].vname
;
129 const allrand
= games
[obj
.gid
].rematch
.every(r
=> r
== 2);
131 vname
= getRandomVariant();
132 games
[obj
.gid
].players
.forEach(p
=>
133 p
.randvar
= allrand
? true : false);
134 const gid
= initializeGame(vname
,
135 games
[obj
.gid
].players
.reverse(),
136 games
[obj
.gid
].options
);
141 // Rematch cancellation
143 if (games
[obj
.gid
]) {
144 const myIndex
= (games
[obj
.gid
].players
[0].sid
== sid
? 0 : 1);
145 send(games
[obj
.gid
].players
[1-myIndex
].sid
, "closerematch");
148 // Create game vs. friend
151 {sid: obj
.player
.sid
, name: obj
.player
.name
},
155 obj
.player
.color
== 'b' ||
156 (obj
.player
.color
== '' && Math
.random() < 0.5)
158 players
= players
.reverse();
160 // Incomplete players array: do not start game yet
161 const gid
= initializeGame(obj
.vname
, players
, obj
.options
);
162 send(sid
, "gamecreated", {gid: gid
});
163 // If nobody joins within 3 minutes, delete game
166 if (games
[gid
] && games
[gid
].players
.some(p
=> !p
))
173 // Join game vs. friend
176 send(sid
, "jointoolate");
178 const emptySlot
= games
[obj
.gid
].players
.findIndex(p
=> !p
);
180 send(sid
, "jointoolate");
182 // Join a game (started by some other player)
183 games
[obj
.gid
].players
[emptySlot
] = {sid: sid
, name: obj
.name
};
188 // Relay a move + update games object
190 games
[obj
.gid
].fen
= obj
.fen
;
191 games
[obj
.gid
].time
= Date
.now(); //update timestamp in case of
192 const playingWhite
= (games
[obj
.gid
].players
[0].sid
== sid
);
193 const oppSid
= games
[obj
.gid
].players
[playingWhite
? 1 : 0].sid
;
194 send(oppSid
, "newmove", {moves: obj
.moves
});
196 // Relay "game ends" message
199 const playingWhite
= (games
[obj
.gid
].players
[0].sid
== sid
);
200 const oppSid
= games
[obj
.gid
].players
[playingWhite
? 1 : 0].sid
;
201 send(oppSid
, "gameover", { gid: obj
.gid
});
203 // 2 minutes timeout for rematch:
204 setTimeout(() => delete games
[obj
.gid
], 2 * 60000);
208 socket
.on("close", () => {
210 for (const [key
, value
] of Object
.entries(challenges
)) {
211 if (value
.sid
== sid
) {
212 delete challenges
[key
];
213 break; //only one challenge per player
216 for (let g
of Object
.values(games
)) {
217 const myIndex
= g
.players
.findIndex(p
=> p
&& p
.sid
== sid
);
219 if (g
.rematch
&& g
.rematch
[myIndex
] > 0) g
.rematch
[myIndex
] = 0;
220 break; //only one game per player
226 const heartbeat
= setInterval(() => {
227 wss
.clients
.forEach((ws
) => {
228 if (ws
.isAlive
=== false)
229 return ws
.terminate();
235 // Every 24 hours, scan games and remove if last move older than 24h
236 const dayInMillisecs
= 24 * 60 * 60 * 1000;
237 const killOldGames
= setInterval(() => {
238 const now
= Date
.now();
239 Object
.keys(games
).forEach(gid
=> {
240 if (now
- games
[gid
].time
>= dayInMillisecs
)
245 // TODO: useful code here?
246 wss
.on("close", () => {
247 clearInterval(heartbeat
);
248 clearInterval(killOldGames
);