-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtetris_match.js
587 lines (503 loc) · 19.7 KB
/
tetris_match.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
580
581
582
583
584
585
586
587
const express = require("express");
const bcrypt = require("bcrypt");
const fs = require("fs");
const session = require("express-session");
const { isEmpty, containWordCharsOnly } = require("./utils");
// Create the Express app
const app = express();
// Use the 'public' folder to serve static files
app.use(express.static("public"));
// Use the json middleware to parse JSON data
app.use(express.json());
// Use the session middleware to maintain sessions
const gameSession = session({
secret: "game",
resave: false,
saveUninitialized: false,
rolling: true,
cookie: { maxAge: 300000 },
});
app.use(gameSession);
// Handle the /register endpoint
app.post("/register", (req, res) => {
// Get the JSON data from the body
const { username, avatar, name, password } = req.body;
console.log({ username, avatar, name, password });
// Reading the users.json file
const users = JSON.parse(fs.readFileSync("data/users.json"));
const scoreboards = JSON.parse(fs.readFileSync("data/scoreboard.json"));
console.log(users);
// Checking for the user data correctness
let isDataValid = false;
const dataList = [username, avatar, name, password];
const strings = ["username", "avatar", "name", "password"];
let s = "";
let isEmpty = false;
for (let i = 0; i < dataList.length; ++i) {
if (!dataList[i]) {
isEmpty = true;
s += strings[i] + ", ";
}
}
s = s.slice(0, s.length - 2);
let emptyErrorMsg = `${s} cannot be empty!`;
emptyErrorMsg =
emptyErrorMsg.charAt(0).toUpperCase() + emptyErrorMsg.slice(1);
if (isEmpty) {
res.json({ status: "error", error: emptyErrorMsg });
return;
}
if (!containWordCharsOnly(username))
errorMsg = "username should only contain Word Characters Only. ";
else if (username in users)
errorMsg = "Invalid username, a user already exist with this username";
else isDataValid = true;
if (!isDataValid) {
res.json({ status: "error", error: errorMsg });
return;
}
// Adding the new user account
const hash = bcrypt.hashSync(password, 10);
users[username] = {
avatar: avatar,
name: name,
password: hash,
};
scoreboards[1][username] = {
avatar: avatar,
name: name,
score: 0,
};
scoreboards[2][username] = {
avatar: avatar,
name: name,
score: 0,
};
// Saving the users.json file
fs.writeFileSync("data/users.json", JSON.stringify(users, null, " "));
fs.writeFileSync(
"data/scoreboard.json",
JSON.stringify(scoreboards, null, " ")
);
// Sending a success response to the browser
res.json({ status: "success" });
});
// Handle the /signin endpoint
app.post("/signin", (req, res) => {
// Get the JSON data from the body
const { username, password } = req.body;
// Reading the users.json file
const users = JSON.parse(fs.readFileSync("data/users.json"));
// Checking for username/password
let isDataValid = false;
if (!username) errorMsg = "Username cannot be empty";
else if (!password) errorMsg = "Password cannot be empty";
else if (!(username in users)) errorMsg = "User does not exist.";
else if (!bcrypt.compareSync(password, users[username].password))
errorMsg = "Incorrect password";
else isDataValid = true;
if (!isDataValid) {
res.json({ status: "error", error: errorMsg });
return;
}
const user = users[username];
const user_data = {
username,
avatar: user.avatar,
name: user.name,
};
req.session.user = user_data;
// Sending a success response with the user account
res.json({
status: "success",
user: user_data,
});
});
// Handle the /validate endpoint
app.get("/validate", (req, res) => {
// Getting req.session.user
const user = req.session.user;
if (!user) {
res.json({ status: "error", error: "Session user not defined. " });
return;
}
// Sending a success response with the user account
res.json({
status: "success",
user,
});
});
// Handle the /signout endpoint
app.get("/signout", (req, res) => {
// Deleting req.session.user
req.session.user = null;
// Sending a success response
res.json({ status: "success" });
});
const { createServer } = require("http");
const { Server } = require("socket.io");
const httpServer = createServer(app);
const io = new Server(httpServer);
const onlineUsers = {};
io.use((socket, next) => {
gameSession(socket.request, {}, next);
});
const randomId = () => Math.floor(100000 + Math.random() * 900000);
const roomReady = {};
// const publicMatch = [];
const publicMatchTimeMode = [];
const publicMatchSurvivalMode = [];
const TIME_MODE = 1;
const SURVIVAL_MODE = 2;
const roomMode = {};
const gameUID = {};
const roomPlayers = {};
const getPersonalBest = (username) => {
const scoreboard = JSON.parse(fs.readFileSync("data/scoreboard.json"));
return {
1: scoreboard[1][username].score,
2: scoreboard[2][username].score,
};
};
const getScoreboardPosition = (username) => {
const scoreboard = JSON.parse(fs.readFileSync("data/scoreboard.json"));
let scoreboardPosition = {};
for (let mode in scoreboard) {
const mode_scoreboard = scoreboard[mode];
mode_sorted = Object.keys(mode_scoreboard).sort(function (a, b) {
return mode_scoreboard[b].score - mode_scoreboard[a].score;
});
scoreboardPosition[mode] = mode_sorted.indexOf(username) + 1;
}
return scoreboardPosition;
};
// Use a web server to listen at port 8000
httpServer.listen(8000, () => {
console.log("Tetris Match server has started...");
io.on("connection", (socket) => {
// Add a new user to the online user list
const user = socket.request.session.user;
if (user) {
// User signed in
onlineUsers[user.username] = user;
// Broadcast to Browsers: Add a signed-in user to the online user list
io.emit("add user", JSON.stringify(user));
console.log(user);
// Send the user's best score to the browser
io.to(socket.id).emit(
"user best score",
JSON.stringify(getPersonalBest(user.username))
);
io.to(socket.id).emit(
"user scoreboard position",
JSON.stringify(getScoreboardPosition(user.username))
);
// When browser wants to Get the chatroom messages
socket.on("get messages", () => {
// Send the chatroom messages to the browser
const chatroom = fs.readFileSync("data/chatroom.json", "utf-8");
io.emit("messages", chatroom);
});
// Browser to Server: When user post a new message in the chatroom
socket.on("post message", (content) => {
const message = {
user,
datetime: new Date(),
content,
};
// Add the message to the chatroom JSON file
const chatroom = JSON.parse(
fs.readFileSync("data/chatroom.json")
);
chatroom.push(message);
fs.writeFileSync(
"data/chatroom.json",
JSON.stringify(chatroom, null, " ")
);
// Broadcast the new message to everyone
io.emit("add message", JSON.stringify(message));
});
// Browser to Server: when a user start typing
socket.on("show typing", () => {
// Broadcast the typing status to everyone
io.emit("show typing", JSON.stringify(user));
});
// When user Signs out
socket.on("disconnect", () => {
// Remove the user from the online user list
delete onlineUsers[user.username];
// Broadcast to Browsers: Remove a disconnected user from the online user list
io.emit("remove user", JSON.stringify(user));
});
let room = null;
/**
* Creates a new room for the Tetris match.
*
* @param {string} _mode - The mode of the Tetris match.
* @returns {string} The ID of the created room.
*/
const createRoom = (_mode) => {
// Create room
const _room = randomId();
// Check if Room already Exist
while (io.sockets.adapter.rooms.has(_room)) {
_room = randomId();
}
io.to(socket.id).emit("room created", _room, _mode);
if (!roomMode[_room]) roomMode[_room] = _mode;
socket.join(_room);
roomPlayers[_room] = user.username;
roomReady[_room] = 1;
console.log("Created and Joined room: ", _room);
room = _room;
return _room;
};
/**
* Joins a room and performs necessary checks before joining.
* @param {number} _room - The room number to join.
*/
const joinRoom = (_room) => {
_room = parseInt(_room);
const thisRoom = io.sockets.adapter.rooms.get(_room);
if (_room == null || !thisRoom) {
io.to(socket.id).emit("room not found");
return;
}
alreadyInRoom = thisRoom.has(socket.id);
// User not already in this room
if (!alreadyInRoom) {
if (thisRoom.size > 2) {
io.to(socket.id).emit("room full");
return;
}
console.log("Joining room: ", _room);
console.log("Room players: ", roomPlayers[_room]);
socket.join(_room);
socket.join("joined room", _room, roomMode[_room]);
io.to(_room).emit("set opponent", JSON.stringify(user));
console.log(onlineUsers);
}
room = _room;
roomReady[room]++;
if (thisRoom.size === 2 && roomReady[room] === 2) {
roomReady[room] = 0;
console.log("two people");
if (!alreadyInRoom) {
opponent = roomPlayers[room];
// console.log(
// "Opponent: ",
// opponent,
// onlineUsers[opponent],
// JSON.stringify(onlineUsers[opponent])
// );
io.to(socket.id).emit(
"set opponent",
JSON.stringify(onlineUsers[opponent])
);
}
io.to(room).emit("on your marks", roomMode[_room]);
gameUID[room] = room + "-" + Date.now();
delete roomPlayers[_room];
} else if (alreadyInRoom && thisRoom.size === 1) {
roomPlayers[_room] = user.username;
if (roomReady[room] === 0) {
roomReady[room] = 1;
}
}
};
socket.on("public match", (_mode) => {
if (
_mode === SURVIVAL_MODE &&
publicMatchSurvivalMode.length === 0
) {
const roomId = createRoom(SURVIVAL_MODE);
publicMatchSurvivalMode.push(roomId);
io.to(socket.id).emit("waiting for opponent");
return;
}
if (_mode === TIME_MODE && publicMatchTimeMode.length === 0) {
const roomId = createRoom(TIME_MODE);
// publicMatch.push(socket.id);
publicMatchTimeMode.push(roomId);
io.to(socket.id).emit("waiting for opponent");
return;
}
if (_mode === TIME_MODE) room = publicMatchTimeMode.shift();
else if (_mode === SURVIVAL_MODE)
room = publicMatchSurvivalMode.shift();
joinRoom(room);
});
socket.on("leave room", () => {
if (room == null) return;
roomReady[room] -= 1;
if (roomReady[room] < 0) roomReady[room] = 0;
console.log("Leaving room: ", room);
socket.leave(room);
if (publicMatchSurvivalMode.indexOf(room) > -1)
publicMatchSurvivalMode.splice(publicMatchSurvivalMode.indexOf(room), 1);
else if (publicMatchTimeMode.indexOf(room) > -1)
publicMatchTimeMode.splice(publicMatchTimeMode.indexOf(room), 1);
// If no more players in the room, delete the room
if (!io.sockets.adapter.rooms.get(room)) {
delete roomMode[room];
delete roomReady[room];
}
room = null;
});
socket.on("create room", (_mode) => {
createRoom(_mode);
});
socket.on("join room", (_room) => {
if (_room == null) createRoom();
// Join the room
else joinRoom(_room);
});
// let room_ready = 0;
socket.on("ready to start", () => {
roomReady[room]++;
if (roomReady[room] === 2) {
roomReady[room] = 0;
io.to(room).emit("start game");
}
});
socket.on("init game", (firstTetromino, tetrominos) => {
// Broadcast the game start time to everyone
socket.broadcast
.to(room)
.emit("init game", firstTetromino, tetrominos);
});
socket.on("push next tetromino", (letter) => {
// Broadcast the next tetromino to everyone
socket.broadcast.to(room).emit("push next tetromino", letter);
});
socket.on("post leave", () => {
socket.broadcast.to(room).emit("leave");
});
socket.on("update score", (score) => {
// Update the user's score
// user.score = score;
console.log("Sending update score to everyone");
// Broadcast the updated score to everyone
socket.broadcast.to(room).emit("update score", score);
});
socket.on("key down", (key) => {
// Broadcast the key down event to everyone
socket.broadcast.to(room).emit("key down", key);
});
socket.on("key up", (key) => {
// Broadcast the key up event to everyone
socket.broadcast.to(room).emit("key up", key);
});
socket.on("add cheat row", () => {
// Broadcast the add cheat row event to everyone
socket.broadcast.to(room).emit("add cheat row");
});
socket.on("add punish row", (hole) => {
// Broadcast the add cheat row event to everyone
socket.broadcast.to(room).emit("punish row", hole);
});
socket.on("game over", () => {
// Broadcast the game over event to everyone
socket.broadcast.to(room).emit("game over");
});
socket.on("get users", () => {
// Send the online users to the browser
io.emit("users", JSON.stringify(onlineUsers));
});
socket.on("get scoreboard", (_mode = 0, isGameOver = false) => {
// if (_mode === 0) return;
const scoreboard = JSON.parse(
fs.readFileSync("data/scoreboard.json", "utf-8")
);
if (isGameOver) {
io.emit(
"scoreboard",
_mode,
JSON.stringify(scoreboard[_mode]),
isGameOver
);
} else {
io.to(socket.id).emit(
"scoreboard",
1,
JSON.stringify(scoreboard[1]),
isGameOver
);
io.to(socket.id).emit(
"scoreboard",
2,
JSON.stringify(scoreboard[2]),
isGameOver
);
}
});
socket.on("set game stats", (_stats) => {
const games = JSON.parse(
fs.readFileSync("data/games.json", "utf-8")
);
if (!games[gameUID[room]])
games[gameUID[room]] = {
player1: {
username: user.username,
...onlineUsers[user.username],
stats: _stats,
},
// player2: {},
mode: roomMode[room],
datetime: new Date(),
};
else {
games[gameUID[room]].player2 = {
username: user.username,
...onlineUsers[user.username],
stats: _stats,
};
}
delete gameUID[room];
// socket.to(room).emit("opponent stats", _stats);
// fs.writeFileSync(
// "data/games.json",
// JSON.stringify(games, null, " ")
// );
const scoreboard = JSON.parse(
fs.readFileSync("data/scoreboard.json")
);
// Check personal best score
const mode = roomMode[room];
const _mode_scoreboard = scoreboard[mode];
const currentMatchScore = parseInt(_stats["score"]);
if (
!_mode_scoreboard[user.username] ||
currentMatchScore >
parseInt(_mode_scoreboard[user.username].score)
) {
scoreboard[mode][user.username] = {
avatar: user.avatar,
name: user.name,
timestamp: new Date(),
score: currentMatchScore,
};
fs.writeFileSync(
"data/scoreboard.json",
JSON.stringify(scoreboard, null, " ")
);
io.to(socket.id).emit(
"user best score",
JSON.stringify(getPersonalBest(user.username))
);
io.to(socket.id).emit(
"user scoreboard position",
JSON.stringify(getScoreboardPosition(user.username))
);
// TODO: Also update scoreboard
}
});
socket.on("request rematch", () => {
// io.to(room).emit("request rematch");
joinRoom(room);
// roomReady[room]++;
io.to(socket.id).emit("waiting for opponent");
});
}
});
});