-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchess.js
252 lines (230 loc) · 10.1 KB
/
chess.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
const https = require('https');
const http = require('http');
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const WebSocket = require('ws');
var uniqid = require('uniqid');
const { type } = require('os');
const randomAnimalName = require('random-animal-name')
const randomAvatarGenerator = require("random-avatar-generator")
const avaGenerator = new randomAvatarGenerator.AvatarGenerator()
// config file
const config = require('./config.json');
certFileLocation = config.certFileLocation;
keyFileLocation = config.keyFileLocation;
let port = process.env.PORT;
if (port == null || port == "") {
port = config.port || 8000;
}
// Serve static files from the "public" directory
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
let server;
if (fs.existsSync(config.keyFileLocation) && fs.existsSync(config.certFileLocation)) {
const options = {
key: fs.readFileSync(config.keyFileLocation),
cert: fs.readFileSync(config.certFileLocation)
};
server = https.createServer(options, app);
} else {
server = http.createServer(app);
}
server.listen(port, "0.0.0.0", () => {
console.log(`Server running at http://127.0.0.1:${port}/`);
});
const wss = new WebSocket.Server({ server });
var rooms = {}
wss.on('connection', function connection(ws, request, client) {
console.log('new con',request.cookie)
ws.on('message', function incoming(message) {
var messageJson = getJsonString(message);
console.log(messageJson)
switch(messageJson.requestType){
case "playerMove":
case "botMove":
rooms[ws.user.roomId].gameState.turnOrder.lastGameBoardFen = messageJson.fen
rooms[ws.user.roomId].gameState.turnOrder.centipawns = messageJson.centipawns
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN && client.user.userid !== ws.user.userid && client.user.roomId == ws.user.roomId) {
var payload = {
requestType: messageJson.requestType,
moveObj: messageJson,
}
var data = JSON.stringify(payload);
client.send(data);
}
});
break;
case "initRoom":
if(messageJson.roomId == null)
ws.user.roomId = uniqid()
else
ws.user.roomId = messageJson.roomId
if(rooms[ws.user.roomId] == undefined) {
rooms[ws.user.roomId] = {
users: {},
gameState: {
turnOrder: {
order: [ws.user.userid, "robot"],
serverTimestamp: Date.now(),
turnNum: 0,
turnOrderIndex: 0,
lastGameBoardFen: undefined,
centipawns: 0
}
}
}
}
//user rejoins w/ id ->
// clear timeout
// send playerReconnect
// --- in future, should have a secret id sent when making session for auth
var isReconnect = false;
var theirUsers = []
if(messageJson.myUsers != null){
for(var i in messageJson.myUsers){
var user = messageJson.myUsers[i]
var userIsInRoom = rooms[ws.user.roomId].users[user.userid] != undefined
if(!userIsInRoom) continue;
theirUsers.push(user)
var userHasDisconnected = rooms[ws.user.roomId].users[user.userid].disconnect != null
console.log(userIsInRoom, userHasDisconnected)
if(userIsInRoom && userHasDisconnected){
clearTimeout(rooms[ws.user.roomId].users[user.userid].disconnect.timeout)
delete rooms[ws.user.roomId].users[user.userid].disconnect
ws.user.userid = user.userid
ws.user.username = user.username
isReconnect = true
}
}
}
ws.user['avatarUrl'] = avaGenerator.generateRandomAvatar(ws.user.username)
rooms[ws.user.roomId].users[ws.user.userid] = ws.user
var userArr = []
var clients = Array.from(wss.clients)
for(i in clients){
var client = clients[i]
if (client.readyState === WebSocket.OPEN && client.user.roomId == ws.user.roomId){
userArr.push(client.user)
if(client.user.userid !== ws.user.userid) {
//notify everyone else of my existance
var payload = {
requestType: "newClient",
isReconnect: isReconnect,
newClient: ws.user
}
var data = JSON.stringify(payload);
client.send(data);
}
}
}
var payload = {
requestType: "init",
myId: ws.user.userid,
myUsername: ws.user.username,
turnOrder: rooms[ws.user.roomId].gameState.turnOrder,
allUsers: userArr,
roomId: ws.user.roomId,
theirUsers: theirUsers,
centipawns: rooms[ws.user.roomId].gameState.turnOrder.centipawns
}
ws.send(JSON.stringify(payload));
break;
case "turnOrderUpdate":
turnOrderUpdate(messageJson.requestType, messageJson.turnOrder, ws, wss)
break;
case "resetBoard":
rooms[ws.user.roomId].gameState.turnOrder.lastGameBoardFen = undefined
rooms[ws.user.roomId].gameState.turnOrder.turnNum = 0
rooms[ws.user.roomId].gameState.turnOrder.turnOrderIndex = 0
//turnNum
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN && client.user.roomId == ws.user.roomId) {
var payload = {
requestType: messageJson.requestType,
moveObj: messageJson,
}
var data = JSON.stringify(payload);
client.send(data);
}
});
break;
}
})
function turnOrderUpdate(requestType, turnOrder, ws, wss){
rooms[ws.user.roomId].gameState.turnOrder = turnOrder
rooms[ws.user.roomId].gameState.turnOrder.serverTimestamp = Date.now()
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN && client.user.roomId == ws.user.roomId) {
var payload = {
requestType: requestType,
turnOrder: rooms[ws.user.roomId].gameState.turnOrder
}
var data = JSON.stringify(payload);
client.send(data);
}
});
}
ws.on('close', function incoming() {
console.log('con closed', ws.user.userid)
//send playerDisconnectWarning ->
// ws.user.disconnected = settimeout
// send timestamp, userid
ws.user.disconnect = {
disconnectTime: Date.now(),
timeout: setTimeout(function () {
//timeout hits
// remove user from turnorder
// delete user from room
// send playerDisconnect
// userid
var newOrder = []
for(var i = 0; i < rooms[ws.user.roomId].gameState.turnOrder.order.length; i++){
if(rooms[ws.user.roomId].gameState.turnOrder.order[i] !== ws.user.userid){
newOrder.push(rooms[ws.user.roomId].gameState.turnOrder.order[i])
}
}
rooms[ws.user.roomId].gameState.turnOrder.order = newOrder
rooms[ws.user.roomId].gameState.turnOrder.serverTimestamp = Date.now()
delete rooms[ws.user.roomId].users[ws.user.userid]
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN && client.user.roomId == ws.user.roomId) {
var payload = {
requestType: "playerDisconnect",
userid: ws.user.userid,
turnOrder: rooms[ws.user.roomId].gameState.turnOrder
}
var data = JSON.stringify(payload);
client.send(data);
}
});
}.bind(this), 10000)
}
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN && client.user.userid !== ws.user.userid && client.user.roomId == ws.user.roomId) {
var payload = {
requestType: "playerDisconnectWarning",
userid: ws.user.userid,
disconnectTime: ws.user.disconnect.disconnectTime
}
var data = JSON.stringify(payload);
client.send(data);
}
});
});
ws.user = {
userid: uniqid(),
username: randomAnimalName()
}
});
function getJsonString(str) {
try {
return JSON.parse(str);
} catch (e) {
return false;
}
}