This repository was archived by the owner on Jun 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
103 lines (89 loc) · 2.31 KB
/
Copy pathgame.js
File metadata and controls
103 lines (89 loc) · 2.31 KB
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
const games = [];
// Creates initial game data
const createGame = ({ player, gameName, gameId }) => {
const game = {
gameName,
turn: 'white',
players: [
{
color: 'white',
socket: player,
},
],
chat: [{ player: 'admin', text: 'Welcome to the game!' }],
id: gameId,
playAgain: false,
resetGame: false,
};
games.push(game);
return game;
};
// Return all current games without socket info
const getSanitizedGames = () =>
games.map(({ players, ...game }) => ({
...game,
numberOfPlayers: players.length,
}));
// Return current game without socket info
const sanitizedGame = ({ players, ...game }) => {
const sanitizedplayers = players.map(({ color, socket }) => ({
color,
id: socket.id,
}));
return { ...game, players: sanitizedplayers, numberOfPlayers: players.length };
};
const getGameById = (gameId) => games.find((game) => game.id === gameId);
const addPlayerToGame = ({ player, gameId }) => {
const game = getGameById(gameId);
game.players.push({
color: 'black',
socket: player,
});
};
const updateGame = (io, socket) => {
const game = sanitizedGame(getGameById(socket.gameId));
io.sockets.in(socket.gameId).emit('game-updated', game);
};
const updateChat = (io, socket, msg) => {
const game = sanitizedGame(getGameById(socket.gameId));
const { color } = game.players.find((player) => player.id === socket.id);
game.chat.push({ player: color, text: msg });
io.sockets.in(socket.gameId).emit('chat-updated', game.chat);
};
const movePiece = ({ gameId, move }) => {
const game = getGameById(gameId);
game.move = move;
game.turn = game.turn === 'white' ? 'black' : 'white';
};
const setPlayAgain = (gameId) => {
const game = getGameById(gameId);
game.playAgain = !game.playAgain;
return game;
};
const setResetGame = (gameId) => {
const game = getGameById(gameId);
game.resetGame = !game.resetGame;
game.turn = 'white';
game.playAgain = false;
return game;
};
const endGame = (player) => {
const game = getGameById(player.gameId);
if (!game) return;
games.splice(games.indexOf(game), 1);
game.players.forEach((currentPlayer) => {
if (player !== currentPlayer.socket) currentPlayer.socket.emit('end-game');
});
};
module.exports = {
createGame,
getSanitizedGames,
getGameById,
addPlayerToGame,
updateGame,
updateChat,
movePiece,
setPlayAgain,
setResetGame,
endGame,
};