This repository has been archived by the owner on Jul 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
97 lines (80 loc) · 2.34 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
const { Board } = require("./utils/Board");
const { userJoin, getCurrentUser, userLeave, getRoomUsers, getActivePlayers } = require("./utils/users");
const board = new Board();
let gameState = {
state: board.state,
actualPlayer: board.actualPlayer,
isGameOver: board.isGameOver,
winPlayer: board.winPlayer,
score: board.score,
};
const path = require("path");
const http = require("http");
const express = require("express");
const socketio = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(express.static(path.join(__dirname, "public")));
io.on("connection", socket => {
// On Connects
socket.on("JoinRoom", ({ username, room }) => {
const user = userJoin(socket.id, username, room); // Create a new user
socket.join(user.room);
// Join in room
socket.to(user.room).emit("status", gameState);
socket.to(user.room).emit("UpdatePlayers", getActivePlayers(user.room));
// Player Move
socket.on("PlayerMove", i => {
if (user.symbol === board.actualPlayer) {
board.move(i);
formateGameState();
io.to(user.room).emit("status", gameState);
io.to(user.room).emit("UpdatePlayers", getActivePlayers(user.room));
}
});
// New Board
socket.on("NewBoard", () => {
board.newBoard();
formateGameState();
io.to(user.room).emit("status", gameState);
io.to(user.room).emit("UpdatePlayers", getActivePlayers(user.room));
});
// Reset
socket.on("Reset", () => {
board.init();
formateGameState();
io.to(user.room).emit("status", gameState);
io.to(user.room).emit("UpdatePlayers", getActivePlayers(user.room));
});
updateUsersRoom(user);
});
// Quando o user sair
socket.on("disconnect", () => {
const user = getCurrentUser(socket.id);
if (user) {
io.to(user.room).emit("status", gameState);
io.to(user.room).emit("UpdatePlayers", getActivePlayers(user.room));
userLeave(socket.id);
updateUsersRoom(user);
}
});
});
// Obter Users da Sala
function updateUsersRoom(user) {
io.to(user.room).emit("UsersRoom", {
room: user.room,
users: getRoomUsers(user.room),
});
}
function formateGameState() {
gameState = {
state: board.state,
actualPlayer: board.actualPlayer,
isGameOver: board.isGameOver,
winPlayer: board.winPlayer,
score: board.score,
};
}
const PORT = process.env.PORT || 3000;
server.listen(PORT);