0382e375e5b7173c830f72ea1dc4376339777acb
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 oppIndex
= undefined, //variant name
67 choice
= undefined; //variant finally played
68 const vname
= obj
.vname
, //variant requested
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
)];
79 else if (challenges
[vname
]) {
80 // Anyone wanting to play the same variant ?
84 else if (challenges
["_random"]) {
85 // Anyone accepting any variant (including vname) ?
90 if (choice
== "_random")
91 choice
= getRandomVariant();
94 {sid: sid
, name: obj
.name
, randvar: randvar
},
95 Object
.assign({}, challenges
[oppIndex
])
97 delete challenges
[oppIndex
];
98 if (Math
.random() < 0.5)
99 players
= players
.reverse();
100 // Empty options = default
101 launchGame( initializeGame(choice
, players
, {}) );
104 // Place challenge and wait. 'randvar' indicate if we play anything
105 challenges
[vname
] = {sid: sid
, name: obj
.name
, randvar: randvar
};
108 // Set FEN after game was created (received twice)
110 games
[obj
.gid
].fen
= obj
.fen
;
112 // Send back game informations
117 send(sid
, "gameinfo", games
[obj
.gid
]);
121 delete challenges
[obj
.vname
];
126 send(sid
, "closerematch");
128 const myIndex
= (games
[obj
.gid
].players
[0].sid
== sid
? 0 : 1);
129 if (!games
[obj
.gid
].rematch
)
130 games
[obj
.gid
].rematch
= [0, 0];
131 games
[obj
.gid
].rematch
[myIndex
] = !obj
.random
? 1 : 2;
132 if (games
[obj
.gid
].rematch
[1-myIndex
]) {
133 // Launch new game, colors reversed
134 let vname
= games
[obj
.gid
].vname
;
135 const allrand
= games
[obj
.gid
].rematch
.every(r
=> r
== 2);
137 vname
= getRandomVariant();
138 games
[obj
.gid
].players
.forEach(p
=>
139 p
.randvar
= allrand
? true : false);
140 const gid
= initializeGame(vname
,
141 games
[obj
.gid
].players
.reverse(),
142 games
[obj
.gid
].options
);
147 // Rematch cancellation
149 if (games
[obj
.gid
]) {
150 const myIndex
= (games
[obj
.gid
].players
[0].sid
== sid
? 0 : 1);
151 send(games
[obj
.gid
].players
[1-myIndex
].sid
, "closerematch");
154 // Create game vs. friend
157 {sid: obj
.player
.sid
, name: obj
.player
.name
},
161 obj
.player
.color
== 'b' ||
162 (obj
.player
.color
== '' && Math
.random() < 0.5)
164 players
= players
.reverse();
166 // Incomplete players array: do not start game yet
167 const gid
= initializeGame(obj
.vname
, players
, obj
.options
);
168 send(sid
, "gamecreated", {gid: gid
});
169 // If nobody joins within 3 minutes, delete game
172 if (games
[gid
] && games
[gid
].players
.some(p
=> !p
))
179 // Join game vs. friend
182 send(sid
, "jointoolate");
184 const emptySlot
= games
[obj
.gid
].players
.findIndex(p
=> !p
);
186 send(sid
, "jointoolate");
188 // Join a game (started by some other player)
189 games
[obj
.gid
].players
[emptySlot
] = {sid: sid
, name: obj
.name
};
194 // Relay a move + update games object
196 games
[obj
.gid
].fen
= obj
.fen
;
197 games
[obj
.gid
].time
= Date
.now(); //update timestamp in case of
198 const playingWhite
= (games
[obj
.gid
].players
[0].sid
== sid
);
199 const oppSid
= games
[obj
.gid
].players
[playingWhite
? 1 : 0].sid
;
200 send(oppSid
, "newmove", {moves: obj
.moves
});
202 // Relay "game ends" message
205 const playingWhite
= (games
[obj
.gid
].players
[0].sid
== sid
);
206 const oppSid
= games
[obj
.gid
].players
[playingWhite
? 1 : 0].sid
;
207 send(oppSid
, "gameover", { gid: obj
.gid
});
209 // 2 minutes timeout for rematch:
210 setTimeout(() => delete games
[obj
.gid
], 2 * 60000);
214 socket
.on("close", () => {
216 for (const [key
, value
] of Object
.entries(challenges
)) {
217 if (value
.sid
== sid
) {
218 delete challenges
[key
];
219 break; //only one challenge per player
222 for (let g
of Object
.values(games
)) {
223 const myIndex
= g
.players
.findIndex(p
=> p
&& p
.sid
== sid
);
225 if (g
.rematch
&& g
.rematch
[myIndex
] > 0) g
.rematch
[myIndex
] = 0;
226 break; //only one game per player
232 const heartbeat
= setInterval(() => {
233 wss
.clients
.forEach((ws
) => {
234 if (ws
.isAlive
=== false)
235 return ws
.terminate();
241 // Every 24 hours, scan games and remove if last move older than 24h
242 const dayInMillisecs
= 24 * 60 * 60 * 1000;
243 const killOldGames
= setInterval(() => {
244 const now
= Date
.now();
245 Object
.keys(games
).forEach(gid
=> {
246 if (now
- games
[gid
].time
>= dayInMillisecs
)
251 // TODO: useful code here?
252 wss
.on("close", () => {
253 clearInterval(heartbeat
);
254 clearInterval(killOldGames
);