-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
579 lines (495 loc) · 16.3 KB
/
game.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
const express = require('express');
const path = require('path');
const nodemailer = require('nodemailer');
const randomstring = require('randomstring');
const PORT = process.env.PORT || 5000
const assert = require('assert');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
const bcrypt = require('bcrypt');
const { Pool } = require('pg');
var pool = new Pool({
connectionString: process.env.DATABASE_URL
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('pages/login');
});
app.get("/forgotPwd", function (req, res) {
res.render("pages/forgotPwd");
});
app.post('/home', (req,res) => {
res.render('pages/home');
});
app.post('/signUp', (req,res) => {
res.render('pages/signUp');
});
var gameFlag = false;
var blockPlayersFlag = false;
var rankingViewSecs = 10;
app.post('/pregame', (req,res) => {
if (!gameFlag && !blockPlayersFlag){
res.render('pages/pregame');
}
else{
assert.deepStrictEqual(blockPlayersFlag, true);
if(rankingFlag)
res.render('pages/gip', {refreshTimeEst: totalGameTime+rankingViewSecs});
else
res.render('pages/gip', {refreshTimeEst: totalGameTime})
}
});
app.post('/waitForPlayers', (req,res) => {
res.render('pages/gameStaging');
});
app.post('/game', (req,res) => {
if (!gameFlag)
gameFlag = true;
res.render('pages/game');
});
app.post('/postgame', (req,res) => {
assert.deepStrictEqual(gameFlag, false)
res.render('pages/postgame');
});
app.post('/logout', (req,res) =>{
res.render('pages/login');
})
app.post('/login', (req, res) => {
var userID = req.body.username;
var userpwd = req.body.pwd;
var loginQuery = `SELECT * FROM logindb WHERE username='${userID}'`;
pool.query(loginQuery, async (error, result) => {
if (error)
res.end(error);
if (result.rows.length === 0)
res.render('pages/login', {loginMessage: 'Username entered does not match any accounts! Please sign up for a new account below.'});
else{
if(await bcrypt.compare(userpwd, result.rows[0].password)){
if ((result.rows[0].usertype == 'User'))
res.render('pages/home', {message: 'Successfully logged in!'});
else{
var usersQuery=`SELECT userid, username, email, usertype FROM logindb ORDER BY usertype, username`;
pool.query(usersQuery, (error, result) =>{
if (error)
res.end(error);
var allUsers = {'rows': result.rows};
res.render('pages/admin', allUsers);
});
}
}
else{
res.render('pages/login', {loginMessage: 'Password entered is incorrect! Please try again.'});
}
}
});
});
app.post('/signUpForm', async (req,res) => {
var insertUsername = req.body.username;
var insertPassword = req.body.password;
var confirm = req.body.confirmPassword;
var insertEmail = req.body.email;
const mailCode = randomstring.generate(20);
if(insertPassword !== confirm){
res.render('pages/signUp', {message: 'Passwords do not match!'});
}
else{
getAllquery = `SELECT * FROM logindb WHERE username='${insertUsername}'`;
pool.query(getAllquery, (error, result) => {
if(error)
res.end(error);
if (result.rows.length === 0){
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: 'cloud5sfu@gmail.com',
pass: 'battleblobs5'
}
});
let mailOptions = {
from: '"Cloud5" cloud5sfu@gmail.com',
to: insertEmail,
subject: "Email confirmation",
text: "Please confirm your email to finish creating your account. Your confirmation code is: " + mailCode
};
transporter.sendMail(mailOptions, (error, info) => {
if (error){
return console.log(error);
}
});
res.render('pages/mailConfirm', {insertUsername, insertPassword, insertEmail, mailCode});
}
else{
res.render('pages/signUp', {usernameMessage: 'Username already exists!'});
}
});
}
});
app.post('/mailCodeForm', async(req,res) => {
var mailCode = req.body.code;
var insertUsername = req.body.name;
var insertEmail = req.body.email;
var pwd = req.body.pwd;
var codeInput = req.body.mailCodeInput;
const salt = await bcrypt.genSalt();
const insertPassword = await bcrypt.hash(pwd, salt);
if(codeInput === mailCode){
var insertquery = `INSERT INTO logindb(username, password, email, confirmation_code) VALUES ('${insertUsername}', '${insertPassword}', '${insertEmail}', '${mailCode}');`;
pool.query(insertquery, (error, result) => {
if(error){
res.end(error);
}
res.render('pages/login',{signupMessage: 'Account created!'});
});
}
else{
res.render('pages/mailConfirm', {confirmationErr: 'Wrong confirmation code', insertUsername, insertPassword, insertEmail, mailCode});
}
});
app.post('/forgotPwdAction', (req,res) => {
var codeInput = req.body.forgotPwdCodeInput;
var name = req.body.forgotPwdName;
var newPwd = req.body.newPwd;
const forgotPwdCode = randomstring.generate(20);
var loginQuery = `SELECT * FROM logindb WHERE username='${name}'`;
pool.query(loginQuery, async (error, result) => {
if (error)
res.end(error);
if (result.rows.length === 0)
res.render('pages/forgotPwd', {loginMessage: 'Username entered does not match any accounts! Please try again.'});
else{
var getMailQuery=`SELECT email FROM logindb WHERE username = '${name}'`;
pool.query(getMailQuery, (error, result) => {
if (error){
res.end(error);
}
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: 'cloud5sfu@gmail.com',
pass: 'battleblobs5'
}
});
let mailOptions = {
from: '"Cloud5" cloud5sfu@gmail.com',
to: result.rows[0].email,
subject: "Change password",
text: "Your confirmation code for changing your password: " + forgotPwdCode
};
transporter.sendMail(mailOptions, (error, info) => {
if (error){
return console.log(error);
}
});
res.render("pages/forgotPwdConfirmation", {forgotPwdCode, name, newPwd});
});
}
});
});
app.post('/forgotPwdConfirmationAction', async (req,res) => {
var name = req.body.name;
var newPwd = req.body.newPwd;
var forgotPwdCode = req.body.forgotPwdCode;
var codeInput = req.body.forgotPwdCodeInput;
const salt = await bcrypt.genSalt();
const hashedNewPwd = await bcrypt.hash(newPwd, salt);
if (forgotPwdCode === codeInput){
var forgotPwd = `UPDATE logindb SET password = '${hashedNewPwd}' WHERE username = '${name}'`
pool.query(forgotPwd, (error, result) => {
if (error){
res.end(error);
}
res.render('pages/login',{forgotMessage: 'Password changed!'});
});
}
else{
res.render('pages/forgotPwdConfirmation', {confirmationErr: 'Wrong confirmation code', name, newPwd, forgotPwdCode});
}
});
app.get('/removeUser/:userID', (req,res) => {
console.log(req.params.userID);
var deleteUserQuery=`DELETE FROM logindb WHERE userid = ${req.params.userID}`;
pool.query(deleteUserQuery, (error, result) => {
if (error){
res.end(error);
}
var usersQuery=`SELECT userid, username, email, usertype FROM logindb ORDER BY usertype, username`;
pool.query(usersQuery, (error, result) => {
if (error){
res.end(error);
}
var allUsers = {'rows': result.rows};
res.render('pages/admin', allUsers);
});
});
});
var weatherTest = "Rain"
var playerCount = 0;
var playerAlive = 0;
var players = {};
var aliveIds = [];
var servBullets = [];
var servTraps = [];
var servHealthpacks = [];
var trapSecs = 30; var battleSecs = 120;
var totalGameTime; timerFlag = false;
var ranking = [];
var rankingFlag = true;
var isDraw = 0;
var trapTimer;
io.on('connection', function (socket) {
playerCount++;
playerAlive = playerCount;
//Empty rankings array
ranking = [];
isDraw = 0;
console.log('a user connected. Num of players: ' + playerCount);
if (playerCount == 4){
blockPlayersFlag = true;
if (gameFlag && !timerFlag){
totalGameTime = battleSecs + trapSecs;
timerFlag = true;
trapTimer = setInterval(function() {
io.sockets.emit('trapTimer', { countdown: totalGameTime-battleSecs });
if (totalGameTime-battleSecs < 1 ||
playerCount == 1 ||
playerAlive == 1){
if (playerCount == 1 || playerAlive == 1)
totalGameTime = 2;
else
totalGameTime = battleSecs+1;
clearInterval(trapTimer);
var battleTimer = setInterval(function(){
io.sockets.emit('battleTimer', { countdown: totalGameTime });
if((totalGameTime <= 1) && rankingFlag == true){
rankingFlag = false;
totalGameTime = rankingViewSecs+1;
for(var i = 0; i < ranking.length; i ++){
const removed = ranking[i];
aliveIds.splice(aliveIds.indexOf(removed), 1);
}
var tie = '';
for(var j = 0; j < aliveIds.length; j ++){
console.log(tie);
tie += aliveIds[j];
if(j !== (aliveIds.length - 1)){
tie += ', ';
ranking.push(' ');
}
}
ranking.push(tie);
io.emit('rankings', ranking);
}
if (totalGameTime < 1 && rankingFlag == false){
clearInterval(battleTimer);
gameFlag = false; timerFlag = false;
blockPlayersFlag = false;
rankingFlag = true;
}
totalGameTime--;
}, 1000)
}
totalGameTime--;
}, 1000);
}
}
io.sockets.emit('numPlayers', playerCount);
// create a new player and add it to our players object
players[socket.id] = {
//x: 1400,
//y: 1325,
x: Math.floor(Math.random() * 326) + 1075,
y: Math.floor(Math.random() * 326) + 1000,
colour: socket.colour,
playerId: socket.id,
playerUsername: socket.username
}
//send players object to new player
socket.emit('currentPlayers', players);
//update all other players of new player
socket.broadcast.emit('newPlayer', players[socket.id]);
socket.on('updateColour', function (colourData) {
socket.colour = colourData.colour;
players[socket.id].colour = colourData.colour;
socket.broadcast.emit('updateSprite', players[socket.id]);
});
socket.on('username', function(username){
socket.username = username;
players[socket.id].playerUsername = username;
aliveIds.push(username);
});
socket.on('playerMovement', function (movementData) {
players[socket.id].x = movementData.x;
players[socket.id].y = movementData.y;
socket.broadcast.emit('playerMoved', players[socket.id]);
});
socket.on('message', function(data){
io.emit('message', data);
});
socket.on('bulletFire', function (bulletInit) {
var newBullet = bulletInit;
newBullet.x = bulletInit.x;
newBullet.y = bulletInit.y;
newBullet.initX = bulletInit.initX;
newBullet.initY = bulletInit.initY;
newBullet.owner = socket.id;
servBullets.push(newBullet);
});
socket.on('bulletMovement', function (bulletsInfo){
for(var i = 0; i < bulletsInfo.length; i++){
servBullets[i].x = bulletsInfo[i].x;
servBullets[i].y = bulletsInfo[i].y;
}
});
socket.on('trapSet', function (trapInit) {
var newTrap = trapInit;
newTrap.x = trapInit.x;
newTrap.y = trapInit.y;
newTrap.owner = socket.id;
servTraps.push(newTrap);
});
socket.on('healthpackSet', function (healthpackInit){
var newHealthpack = healthpackInit;
newHealthpack.x = healthpackInit.x;
newHealthpack.y = healthpackInit.y;
servHealthpacks.push(newHealthpack);
});
socket.on('healthpackDespawn', function(){
for(var i = 0; i < servHealthpacks.length; i++){
servHealthpacks.splice(i,1);
i--;
}
});
socket.on('playerDied', function (deadPlayer){
playerAlive--;
var username = deadPlayer.username;
console.log(username + " was killed");
//Push dead player username to rankings array
ranking.push(username);
console.log(ranking);
io.sockets.emit('numPlayers', playerAlive);
//emit dead player username to client for rankings
io.emit('died', deadPlayer);
delete players[deadPlayer.id];
console.log(totalGameTime);
if ((playerAlive==1 || !playerAlive) && gameFlag){
for(var i = 0; i < 3; i ++){
const removed = ranking[i];
aliveIds.splice(aliveIds.indexOf(removed), 1);
}
ranking.push(aliveIds[0]);
io.emit('rankings', ranking);
}
});
socket.on('disconnect', function (){
playerCount--;
console.log('user disconnected. Num of players: ' + playerCount);
if (playerAlive > playerCount)
playerAlive--;
for(var i = 0; i < servTraps.length; i++){
if(servTraps[i].owner == socket.id){
servTraps.splice(i,1);
i--;
}
}
ranking.push(players[socket.id].playerUsername);
delete players[socket.id];
io.sockets.emit('numPlayers', playerCount);
io.emit('disconnect', socket.id);
if (playerCount==1 && gameFlag){
for(var i = 0; i < 3; i ++){
const removed = ranking[i];
aliveIds.splice(aliveIds.indexOf(removed), 1);
}
ranking.push(aliveIds[0]);
io.emit('rankings', ranking);
}
else if(playerCount==0 && !gameFlag)
totalGameTime = 0;
});
});
function gameLoop(){
for(var i = 0; i < servBullets.length; i++){
var currBullet = servBullets[i];
if(currBullet && servBullets[i]){
currBullet.x += currBullet.xSpeed;
currBullet.y += currBullet.ySpeed;
for(var id in players){
if(currBullet.owner != id){
var dx = players[id].x - currBullet.x;
var dy = players[id].y - currBullet.y;
var dist = Math.sqrt(dx*dx + dy*dy);
if(dist < 30){
io.emit('playerHit', id);
servBullets.splice(i,1);
i--;
}
}
}
if(currBullet.x < -10 || currBullet.x < currBullet.initX - 500 || currBullet.x > currBullet.initX + 500 || currBullet.y < -10 || currBullet.y < currBullet.initY - 500 || currBullet.y > currBullet.initY + 500){
servBullets.splice(i,1);
i--;
}
}
}
for(var i = 0; i < servTraps.length; i++){
var currTrap = servTraps[i];
if(currTrap && servTraps[i]){
for(var id in players){
if(currTrap.owner != id){
var dx = players[id].x - currTrap.x;
var dy = players[id].y - currTrap.y;
var dist = Math.sqrt(dx*dx + dy*dy);
if(dist < 20){
io.emit('trapHit', id, currTrap.x, currTrap.y);
servTraps.splice(i,1);
i--;
}
}
}
}
}
for(var i = 0; i < servHealthpacks.length; i++){
var currHealthpack = servHealthpacks[i];
if(currHealthpack && servHealthpacks[i]){
for(var id in players){
var dx = players[id].x - currHealthpack.x;
var dy = players[id].y - currHealthpack.y;
var dist = Math.sqrt(dx*dx + dy*dy);
if(dist < 20){
io.emit('healthpackHit',id);
servHealthpacks.splice(i,1);
i--;
}
}
}
}
io.emit('bulletsUpdate', servBullets);
io.emit('trapsUpdate', servTraps);
io.emit('healthpacksUpdate', servHealthpacks);
}
setInterval(gameLoop, 16);
if(!module.parent){
server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
}
//testing
module.exports = {
players: players,
playerCount: playerCount,
app: app,
servTraps: servTraps,
servHealthpacks: servHealthpacks,
servBullets: servBullets,
weatherTest: weatherTest,
trapSecs: trapSecs,
battleSecs: battleSecs,
gameFlag: gameFlag
}