-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
280 lines (213 loc) · 7.21 KB
/
server.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
//import modules and ata
var express = require('express');
var exphbs = require('express-handlebars');
var ws = require('ws');
//setup express
var app = express();
var port = 3000;
//setup websocket server
const webSocketServer = new ws.Server({ noServer: true });
//setup active gamestate
var gameState = {
type: "gameState",
activePiece: 1, //1 or 2 -- determines tick or tack
currentPlayer: 1, //starts at 1 -- used for player queue
totalPlayers: 0,
board: [
0, 0, 0, 0, 0, 0, 0, 0, 0
]
}
//will hold the soocket objects for connected websocket clients
var currentPlayers = [];
//setup templating engine
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
//stores received json in req.body
app.use(express.json());
//serves static files in /public
app.use(express.static('public'));
//serve the main page
app.get('/', function (req, res) {
res.status(200).render('mainPage', {
title: "Three n' a row!"
});
});
//404 page
app.get('*', function (req, res) {
res.status(404).render('404', {
url: req.url,
title: '404 - Page not found'
});
});
//handle websocket request
webSocketServer.on('connection', socket => {
//update list of players, assign new player their #
currentPlayers.push(socket); //add to array
console.log("== New Player Joined. Current Players: ", currentPlayers.length);
//when a new user connects, send them gamestate
//socket.send(JSON.stringify(gameState));
updatePlayerNumbers();
updateClients();
//this is where websocket requests are actually handled
socket.on('message', message => {
//print message, convert to JSON object
console.log("== Client Message Recived: ", message)
var objRecevied = JSON.parse(message)
//checks the type key in JSON object
switch(objRecevied.type) {
case "gameState":
//if we get a new gamestate, overwrite and sync clients
gameState = objRecevied;
updateGameState();
updateClients();
break;
}
})
socket.on('close', message => {
//updates array of players
console.log("= Player Disconnecting: ", currentPlayers.length);
//filters our dead socket
var newCurrentPlayers = currentPlayers.filter(function (ele) {
if(ele.readyState == 1) {
return ele;
}
})
currentPlayers = newCurrentPlayers;
console.log("= Player Disconnected. There is now ", currentPlayers.length, " players.");
//update clients
updatePlayerNumbers();
//force reset if no one left
if(currentPlayers.length == 0) {
gameState = {
type: "gameState",
activePiece: 1, //1 or 2 -- determines tick or tack
currentPlayer: 1, //starts at 1 -- used for player queue
totalPlayers: 0,
board: [
0, 0, 0, 0, 0, 0, 0, 0, 0
]
}
}
})
});
//sends updated gamestate to ALL clients
function updateClients() {
//loops thru all connected clients
webSocketServer.clients.forEach(function each(client) {
if (client.readyState === ws.OPEN) {
//send JSON of gameState object
client.send(JSON.stringify(gameState));
}
});
}
/*****************************
* This function does the actual game logic. This
* includes advancing the player in the queue, advancing
* the piece to be played, and checking for wins
******************************/
function updateGameState() {
//advance gamestate to next player in queue
gameState.currentPlayer++;
if(gameState.currentPlayer >= (currentPlayers.length + 1)) {
gameState.currentPlayer = 1;
}
//check if this player is still connected
//checkValidPlayer();
//advance to next piece (tick or tack)
if(gameState.activePiece == 2) {
gameState.activePiece = 1;
} else {
gameState.activePiece = 2;
}
//update total number of players
gameState.totalPlayers = currentPlayers.length;
//if win or tie, reset board
if(checkWin() == true || checkTie() == true) {
console.log("== A Win or a Tie was Recorded! Resetting...");
if(checkWin() == true) {
sendWinTie(1);
} else {
sendWinTie(2);
}
gameState.board = [
0, 0, 0, 0, 0, 0, 0, 0, 0,
]
}
}
//sends a gameOver object to clients, 1 for win 2 for tie
function sendWinTie(winOrLoss) {
webSocketServer.clients.forEach(function each(client) {
//only open clients
if (client.readyState === ws.OPEN) {
//the JSON object to send to new client
var gameOver = {
type: "gameOver",
state: winOrLoss,
};
//send JSON of gameOver object
client.send(JSON.stringify(gameOver));
}
});
}
//loops thru all connected players and assigns them their number in the queue
function updatePlayerNumbers() {
var playerNumber = 1;
webSocketServer.clients.forEach(function each(client) {
//only open clients
if (client.readyState === ws.OPEN) {
//the JSON object to send to new client
var newPlayer = {
type: "assignPlayer",
playerInt: playerNumber,
};
//send JSON of gameState object
client.send(JSON.stringify(newPlayer));
playerNumber++;
}
});
}
//checks for a win
function checkWin() {
// Is there a more elegant way to do this? Definitely
// Do I know how to do it? Yup!
// Do I have the mental energy to implement the more elegant solution at this point in the term?
// Nope.
if ((gameState.board[0] == gameState.board [1]) && (gameState.board[1] == gameState.board[2]) && (gameState.board[1] != 0)) //check row 1 MUDA
return true; // ORA
else if ((gameState.board[3] == gameState.board[4]) && (gameState.board[4] == gameState.board[5]) && (gameState.board[4] != 0)) // check row 2 MUDA
return true; // ORA
else if ((gameState.board[6] == gameState.board[7]) && (gameState.board[7] == gameState.board[8]) && (gameState.board[7] != 0)) // check row 3 MUDA
return true; // ORA
else if ((gameState.board[0] == gameState.board[3]) && (gameState.board[3] == gameState.board[6]) && (gameState.board[3] != 0)) // check column 1 MUDA
return true; // ORA
else if ((gameState.board[1] == gameState.board[4]) && (gameState.board[4] == gameState.board[7]) && (gameState.board[4] != 0)) // Check column 2 MUDA
return true; // ORA
else if ((gameState.board[2] == gameState.board[5]) && (gameState.board[5] == gameState.board[8]) && (gameState.board[5] != 0)) // Check column 3 MUDA
return true; // ORA
else if ((gameState.board[0] == gameState.board[4]) && (gameState.board[4] == gameState.board[8]) && (gameState.board[4] != 0)) // Check diagonal 1 MUDA
return true; // ORA
else if ((gameState.board[2] == gameState.board[4]) && (gameState.board[4] == gameState.board[6]) && (gameState.board[4] != 0)) // Check diagonal 2 MUDA
return true; // ORA
else {
return false; // WRRRRRRRRRRRRRRRRRRRRRRRRRRRRY
}
}
//checks for a tie
function checkTie() {
for (i = 0; i <= 9; i++) // Cycles through the board array
{
if (gameState.board[i] == 0) // If we find a blank spot
return false; // There's no tie
}
return true; // We've cycled through the board, there are no empty spaces, game is a tie.
}
//start the server
const server = app.listen(port, function () {
console.log("== Server is listening on port", port);
});
//upgrade the server (allows both http & ws on same server)
server.on('upgrade', (request, socket, head) => {
webSocketServer.handleUpgrade(request, socket, head, socket => {
webSocketServer.emit('connection', socket, request);
});
});