-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
362 lines (301 loc) · 10.6 KB
/
server.js
File metadata and controls
362 lines (301 loc) · 10.6 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
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
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
// Serve static files
app.use(express.static(path.join(__dirname)));
// Game rooms storage
const gameRooms = new Map();
class GameRoom {
constructor(roomId) {
this.roomId = roomId;
this.players = [];
this.gameState = {
currentPlayer: 1,
round: 1,
maxRounds: 10,
scores: { player1: 0, player2: 0 },
gamePhase: 'waiting', // waiting, showing-target, placing-needle, scored
targetAngle: 0,
targetRange: 20,
needleAngle: 0,
isGameStarted: false
};
}
addPlayer(socket, playerName) {
if (this.players.length >= 2) {
return false; // Room is full
}
const playerNumber = this.players.length + 1;
const player = {
socket: socket,
id: socket.id,
name: playerName || `Player ${playerNumber}`,
playerNumber: playerNumber
};
this.players.push(player);
socket.join(this.roomId);
console.log(`Player ${player.name} joined room ${this.roomId}`);
// Notify all players in the room (send only serializable data)
this.broadcastToRoom('player-joined', {
player: { name: player.name, playerNumber: player.playerNumber },
playerCount: this.players.length,
gameState: { ...this.gameState }
});
// If room is full, prepare to start game
if (this.players.length === 2) {
this.gameState.isGameStarted = true;
this.broadcastToRoom('game-ready', {
players: this.getSerializablePlayers(),
gameState: { ...this.gameState }
});
}
return {
id: player.id,
name: player.name,
playerNumber: player.playerNumber
};
}
getSerializablePlayers() {
return this.players.map(p => ({
name: p.name,
playerNumber: p.playerNumber
}));
}
removePlayer(socketId) {
const playerIndex = this.players.findIndex(p => p.id === socketId);
if (playerIndex === -1) return false;
const removedPlayer = this.players.splice(playerIndex, 1)[0];
console.log(`Player ${removedPlayer.name} left room ${this.roomId}`);
// Reset game if a player leaves
this.gameState.isGameStarted = false;
this.resetGame();
this.broadcastToRoom('player-left', {
player: { name: removedPlayer.name, playerNumber: removedPlayer.playerNumber },
playerCount: this.players.length,
gameState: { ...this.gameState }
});
return true;
}
startRound() {
this.gameState.gamePhase = 'target-shown';
this.generateTargetPosition();
this.broadcastToRoom('round-started', {
targetAngle: this.gameState.targetAngle,
targetRange: this.gameState.targetRange,
gameState: { ...this.gameState }
});
}
generateTargetPosition() {
this.gameState.targetAngle = 10 + Math.random() * 160;
console.log(`Room ${this.roomId}: Target angle: ${this.gameState.targetAngle}°`);
}
showTarget() {
// This is now called when the guide player enables needle placement
this.gameState.gamePhase = 'placing-needle';
this.broadcastToRoom('target-hidden', {
gameState: { ...this.gameState }
});
}
hideTarget() {
this.gameState.gamePhase = 'placing-needle';
this.broadcastToRoom('target-hidden', {
gameState: { ...this.gameState }
});
}
placeNeedle(needleAngle) {
console.log(`Room ${this.roomId}: Placing needle at ${needleAngle}°, target was ${this.gameState.targetAngle}°`);
this.gameState.needleAngle = needleAngle;
// Calculate score
const angleDifference = Math.abs(needleAngle - this.gameState.targetAngle);
let points = 0;
let message = '';
// Zones are defined as total ranges, but we need to check half-ranges from center
// 5° zone = ±2.5° from center
// 15° zone = ±7.5° from center
// 25° zone = ±12.5° from center
if (angleDifference <= 2.5) {
points = 5;
message = 'Parfait!';
} else if (angleDifference <= 7.5) {
points = 3;
message = 'Très bien!';
} else if (angleDifference <= 12.5) {
points = 1;
message = 'Pas mal!';
} else {
points = 0;
message = 'Manqué!';
}
console.log(`Room ${this.roomId}: Angle difference: ${angleDifference}°, Points: ${points}`);
// Update score
this.gameState.scores[`player${this.gameState.currentPlayer}`] += points;
this.gameState.gamePhase = 'scored';
this.broadcastToRoom('needle-placed', {
needleAngle: needleAngle,
targetAngle: this.gameState.targetAngle,
points: points,
message: message,
angleDifference: angleDifference,
gameState: { ...this.gameState }
});
console.log(`Room ${this.roomId}: Score updated and needle-placed event sent`);
}
nextTurn() {
// Switch player or advance round
if (this.gameState.currentPlayer === 1) {
this.gameState.currentPlayer = 2;
} else {
this.gameState.currentPlayer = 1;
this.gameState.round++;
}
if (this.gameState.round > this.gameState.maxRounds) {
this.endGame();
return;
}
this.gameState.gamePhase = 'waiting';
this.gameState.needleAngle = 90; // Reset needle
this.broadcastToRoom('turn-changed', {
gameState: { ...this.gameState }
});
}
endGame() {
this.gameState.gamePhase = 'ended';
const winner = this.gameState.scores.player1 > this.gameState.scores.player2 ? 1 :
this.gameState.scores.player2 > this.gameState.scores.player1 ? 2 : 0;
this.broadcastToRoom('game-ended', {
winner: winner,
scores: { ...this.gameState.scores },
gameState: { ...this.gameState }
});
}
newGame() {
this.resetGame();
this.broadcastToRoom('game-reset', {
gameState: { ...this.gameState }
});
}
resetGame() {
this.gameState = {
currentPlayer: 1,
round: 1,
maxRounds: 10,
scores: { player1: 0, player2: 0 },
gamePhase: 'waiting',
targetAngle: 0,
targetRange: 20,
needleAngle: 90,
isGameStarted: this.players.length === 2
};
}
broadcastToRoom(event, data) {
io.to(this.roomId).emit(event, data);
}
isEmpty() {
return this.players.length === 0;
}
}
// Socket.io connection handling
io.on('connection', (socket) => {
console.log(`User connected: ${socket.id}`);
socket.on('join-room', (data) => {
const { roomId, playerName, maxRounds } = data;
// Create room if it doesn't exist
if (!gameRooms.has(roomId)) {
const room = new GameRoom(roomId);
// Set max rounds if provided (only for room creator)
if (maxRounds) {
room.gameState.maxRounds = maxRounds;
}
gameRooms.set(roomId, room);
}
const room = gameRooms.get(roomId);
const player = room.addPlayer(socket, playerName);
if (!player) {
socket.emit('room-full');
return;
}
socket.emit('joined-room', {
roomId: roomId,
player: player,
gameState: { ...room.gameState }
});
});
socket.on('start-round', () => {
const room = findPlayerRoom(socket.id);
if (room && room.gameState.isGameStarted) {
room.startRound();
}
});
socket.on('show-target', () => {
const room = findPlayerRoom(socket.id);
if (room && room.gameState.gamePhase === 'showing-target') {
room.showTarget();
}
});
socket.on('place-needle', (data) => {
const room = findPlayerRoom(socket.id);
console.log('Place needle event received. Room phase:', room?.gameState.gamePhase, 'Needle angle:', data.needleAngle);
// Allow needle placement in both target-shown and placing-needle phases
if (room && (room.gameState.gamePhase === 'placing-needle' || room.gameState.gamePhase === 'target-shown')) {
room.placeNeedle(data.needleAngle);
} else {
console.log('Cannot place needle - wrong phase or no room');
}
});
socket.on('next-turn', () => {
const room = findPlayerRoom(socket.id);
if (room && room.gameState.gamePhase === 'scored') {
room.nextTurn();
}
});
socket.on('new-game', () => {
const room = findPlayerRoom(socket.id);
if (room) {
room.newGame();
}
});
socket.on('disconnect', () => {
console.log(`User disconnected: ${socket.id}`);
const room = findPlayerRoom(socket.id);
if (room) {
room.removePlayer(socket.id);
// Clean up empty rooms
if (room.isEmpty()) {
gameRooms.delete(room.roomId);
console.log(`Room ${room.roomId} deleted (empty)`);
}
}
});
});
function findPlayerRoom(socketId) {
for (const room of gameRooms.values()) {
if (room.players.find(p => p.id === socketId)) {
return room;
}
}
return null;
}
// API endpoint to get room info (optional, for debugging)
app.get('/api/rooms', (req, res) => {
const roomsInfo = Array.from(gameRooms.entries()).map(([roomId, room]) => ({
roomId,
playerCount: room.players.length,
gamePhase: room.gameState.gamePhase,
round: room.gameState.round
}));
res.json(roomsInfo);
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Half-Circle multiplayer server running on port ${PORT}`);
console.log(`Game available at: http://localhost:${PORT}`);
});