forked from asundr/gwent-classic
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
147 lines (122 loc) · 5.29 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
const WebSocket = require('ws');
const PORT = process.env.PORT || 8080;
const wss = new WebSocket.Server({ port: PORT });
let sessions = {};
let players = [];
let nextPlayerId = 1;
// Helper function to generate a random 4-character code
function generateCode() {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let code = '';
for (let i = 0; i < 4; i++) {
code += characters.charAt(Math.floor(Math.random() * characters.length));
}
return code;
}
wss.on('connection', (ws) => {
ws.playerId = nextPlayerId++;
players.push(ws);
// Send a welcome message with the player's ID
ws.send(JSON.stringify({ type: 'welcome', playerId: ws.playerId }));
console.log(`# Player ${ws.playerId} connected`);
ws.on('message', (message) => {
const data = JSON.parse(message);
if (data.type === 'createSession') {
const sessionCode = generateCode();
// Create a new session and auto-join the creator
sessions[sessionCode] = { players: [ws], code: sessionCode, playersReady: 0 };
ws.sessionCode = sessionCode;
ws.send(JSON.stringify({ type: 'sessionCreated', code: sessionCode }));
console.log(`# Player ${ws.playerId} created Session ${sessionCode}`);
ws.send(JSON.stringify({ type: 'sessionJoined', code: sessionCode }));
}
if (data.type === "cancelSession") {
const sessionCode = data.code;
if (!sessions[sessionCode]) return;
console.log(`# Player ${ws.playerId} cancelled Session ${sessionCode}`);
delete sessions[ws.sessionCode];
}
if (data.type === "leaveSession") {
const sessionCode = data.code;
if (!sessions[sessionCode]) return;
console.log(`# Player ${ws.playerId} left Session ${sessionCode}`);
sessions[sessionCode].players = sessions[sessionCode].players.filter(player => player !== ws);
}
if (data.type === 'joinSession') {
const sessionCode = data.code;
if (sessions[sessionCode] && sessions[sessionCode].players.length === 1) {
sessions[sessionCode].players.push(ws);
ws.sessionCode = sessionCode;
ws.send(JSON.stringify({ type: 'sessionJoined', code: sessionCode }));
console.log(`# Player ${ws.playerId} joined Session ${sessionCode}`);
sessions[sessionCode].players.forEach((player, index) => {
player.send(JSON.stringify({ type: 'sessionReady', player: index + 1 }));
});
} else {
ws.send(JSON.stringify({ type: 'sessionInvalid' }));
console.log(`# Player ${ws.playerId} attempted to join invalid Session ${sessionCode}`);
}
}
if (data.type === "gameStart") {
if (ws.sessionCode && sessions[ws.sessionCode]) {
const session = sessions[ws.sessionCode];
if (!sessions[ws.sessionCode]?.firstPlayer) {
const firstPlayer = session.players[Math.floor(Math.random() * session.players.length)].playerId;
sessions[ws.sessionCode].firstPlayer = firstPlayer
}
console.log("firstPlayer = ", sessions[ws.sessionCode].firstPlayer)
session.players.forEach((player) => {
player.send(JSON.stringify({ type: 'coinToss', player: sessions[ws.sessionCode].firstPlayer }));
});
}
}
if (data.type === 'initial_reDraw') {
if (ws.sessionCode && sessions[ws.sessionCode]) {
const session = sessions[ws.sessionCode];
session.playersReady += 1;
console.log(`# Players ready in session ${ws.sessionCode}: ${session.playersReady}`);
if (session.playersReady === 2) {
session.players.forEach((player) => {
player.send(JSON.stringify({ type: 'start' }));
});
session.playersReady = 0;
}
}
}
// Relay messages to the other player in the same session
if (ws.sessionCode) {
const sessionPlayers = sessions[ws.sessionCode]?.players || [];
sessionPlayers.forEach((player) => {
if (player !== ws) {
player.send(JSON.stringify(data));
}
});
}
});
ws.on('close', () => {
console.log(`# Player ${ws.playerId} disconnected`);
// Check if the player has an active session
if (ws.sessionCode && sessions[ws.sessionCode]) {
const session = sessions[ws.sessionCode];
// Check if the player is the creator of the session
if (session.players[0] === ws) {
// If the creator disconnects, delete the session
console.log(`# Deleting session ${ws.sessionCode} because the creator left`);
if (session.players.length > 1) {
session.players[1].send(JSON.stringify({ type: 'unReady' }));
session.players[1].send(JSON.stringify({ type: 'sessionUnready' }));
}
delete sessions[ws.sessionCode];
} else {
// If a non-creator disconnects, remove them from the session and notify the creator
session.players = session.players.filter(player => player !== ws);
session.players[0].send(JSON.stringify({ type: 'unReady' }));
session.players[0].send(JSON.stringify({ type: 'sessionUnready' }));
console.log(`# Player ${ws.playerId} left the session ${ws.sessionCode}`);
}
}
// Remove the player from the players list
players = players.filter(player => player !== ws);
});
});
console.log(`## Server is up and running ##`);