-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
218 lines (200 loc) · 6.54 KB
/
index.ts
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
const express = require('express');
import * as Express from 'express';
const cors = require('cors');
const crypto = require('crypto');
const {
port,
host,
allowedPort,
allowedHost,
isDevelopment,
key_file,
cert_file,
} = require('./config');
import { Socket } from 'socket.io';
import * as gameSettings from './gameSettings';
import * as gameLogic from './gameLogic';
console.log('This is running as development:', isDevelopment);
let moveCounter = 0;
// keep a list of the running games on this server
const running_games: Map<string, gameLogic.GameObject> = new Map();
const allowedCors = {
origin: `http${isDevelopment ? '' : 's'}://${allowedHost}${
isDevelopment ? ':' + allowedPort : ''
}`,
methods: ['GET', 'POST'],
};
console.log(`allowing cors from: ${allowedCors.origin}`);
const app = express();
app.use(cors(allowedCors));
let server: any;
// use https if there are cert and key files in the environment variables
if (key_file && cert_file) {
const fs = require('fs');
const https = require('https');
const privateKey = fs.readFileSync(key_file);
const certificate = fs.readFileSync(cert_file);
const credentials = { key: privateKey, cert: certificate };
server = https.createServer(credentials, app);
} else {
const http = require('http');
server = http.createServer(app);
}
const { Server } = require('socket.io');
let io: Socket;
io = new Server(server, {
cors: allowedCors,
});
app.get('/', (req: Express.Request, res: Express.Response) => {
res.send('Hello World!');
});
app.get(
'/create/chinese-checkers',
(req: Express.Request, res: Express.Response) => {
const gameID = crypto.randomBytes(32).toString('hex');
const numTargetPlayers = 2;
const targetPlayers = gameSettings.AllPlayers.slice(0, numTargetPlayers);
console.log('got random id for game: ', gameID);
const newGame: gameLogic.GameObject = {
gameID: gameID,
gameType: 'chinese-checkers',
host: `${host}:${port}`,
players: [],
numTargetPlayers: numTargetPlayers,
targetPlayers: targetPlayers,
rows: gameSettings.StartingRows[numTargetPlayers],
turn: gameSettings.AllPlayers[0].id,
availableSeats: Array(numTargetPlayers).fill(true),
};
running_games.set(newGame.gameID, newGame);
res.send(Array.from(running_games.values()));
}
);
app.get(
'/list-games/chinese-checkers',
(req: Express.Request, res: Express.Response) => {
// console.log('getting running games: ', Array.from(running_games.values()));
console.log(
`number of games: ${Array.from(running_games.values()).length}`
);
res.send(Array.from(running_games.values()));
}
);
io.on('connection', (socket) => {
console.log('a user connected!');
let user: { gameID: string; player: gameLogic.Player | null } = {
gameID: '',
player: null,
};
socket.on('disconnect', () => {
console.log('user disconnected');
const currentGame = running_games.get(user.gameID);
if (currentGame) {
const newPlayers = currentGame.players.filter(
(value: gameLogic.Player) => {
return user.player && value.id !== user.player.id;
}
);
if (newPlayers.length === 0) {
running_games.delete(user.gameID);
} else {
console.log('removing player from game');
console.log('player id: ', user.player!.id);
currentGame.availableSeats[user.player!.id - 1] = true;
console.log('new available seats: ', currentGame.availableSeats);
console.log('new players: ', newPlayers);
running_games.set(user.gameID, {
gameID: currentGame.gameID,
gameType: currentGame.gameType,
host: currentGame.host,
players: newPlayers,
rows: currentGame.rows,
targetPlayers: currentGame.targetPlayers,
numTargetPlayers: currentGame.numTargetPlayers,
turn: currentGame.turn,
availableSeats: currentGame.availableSeats,
});
}
}
socket.broadcast.emit('playerLeft', running_games.get(user.gameID));
socket.removeAllListeners();
});
socket.on('join', (gameID: string) => {
// console.log('joining game: ', gameID);
const game = running_games.get(gameID);
if (game) {
for (let i = 0; i < game.numTargetPlayers; i++) {
if (game.availableSeats[i]) {
game.availableSeats[i] = false;
const player = gameSettings.AllPlayers[i];
const secret = crypto.randomBytes(32).toString('hex'); // player secret, so other people can't move on this player's behalf
game.players.push(player);
user.gameID = game.gameID;
user.player = player;
const response = {
player: player,
secret: secret,
game: game,
};
// console.log('found game, sending response', response);
socket.emit('join', response);
socket.join(gameID);
io.to(gameID).emit('newPlayer', game);
break;
}
}
} else {
console.log("couldn't find game: ", gameID);
socket.emit(null);
}
});
socket.on(
'move',
(res: { gameID: string; move: gameLogic.MoveObject; turn: number }) => {
// console.log('user tried to play move', res.move);
// TODO verify moves on server
// if (gameLogic.validMove()) {
// }
console.log('doing move!', moveCounter);
moveCounter++;
if (
running_games.has(res.gameID) &&
running_games.get(res.gameID)?.turn === res.turn
) {
const currentGame = running_games.get(res.gameID);
if (currentGame) {
const newBoard = gameLogic.updateRows(
currentGame.rows,
res.move.source,
res.move.dest,
res.move.player
);
running_games.set(res.gameID, {
gameID: currentGame.gameID,
gameType: currentGame.gameType,
host: currentGame.host,
players: currentGame.players,
rows: newBoard,
targetPlayers: currentGame.targetPlayers,
numTargetPlayers: currentGame.numTargetPlayers,
turn: gameLogic.changeTurn(
currentGame.targetPlayers,
currentGame.turn
),
availableSeats: currentGame.availableSeats,
});
io.to(res.gameID).emit('move', {
gameID: res.gameID,
move: res.move,
});
}
}
}
);
});
server.listen(port, host, () => {
console.log(
`listening at: http${key_file && cert_file ? 's' : ''}://${host}:${port}`
);
});
export {};