File size: 14,309 Bytes
a24fc4c
 
 
 
 
 
 
205ca02
ff3579e
 
a24fc4c
ff3579e
 
 
 
 
 
a24fc4c
 
 
ff3579e
 
a24fc4c
 
 
 
 
ff3579e
 
a24fc4c
 
 
 
 
 
ff3579e
45c744a
a24fc4c
 
 
ff3579e
a24fc4c
 
ff3579e
 
a24fc4c
 
 
 
 
ff3579e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a24fc4c
ff3579e
 
a24fc4c
 
 
 
 
 
 
ff3579e
 
 
a24fc4c
 
95109ca
a24fc4c
 
 
ff3579e
a24fc4c
 
 
 
 
 
 
 
 
 
 
 
 
ff3579e
 
 
a24fc4c
 
 
 
 
 
 
ff3579e
a24fc4c
 
 
 
 
ff3579e
a24fc4c
 
 
 
ff3579e
a24fc4c
 
 
 
ff3579e
a24fc4c
 
 
 
 
 
 
 
 
 
 
95109ca
a24fc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff3579e
a24fc4c
 
 
 
 
ff3579e
a24fc4c
 
ff3579e
 
 
a24fc4c
ff3579e
a24fc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff3579e
a24fc4c
ff3579e
 
 
a24fc4c
 
 
 
 
ff3579e
 
 
 
a24fc4c
 
 
 
 
 
 
ff3579e
 
 
 
 
a24fc4c
 
ff3579e
 
 
 
a24fc4c
 
 
ff3579e
 
a24fc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff3579e
a24fc4c
ff3579e
a24fc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff3579e
 
 
a24fc4c
ff3579e
a24fc4c
 
 
 
 
ff3579e
 
a24fc4c
 
45c744a
ff3579e
 
 
 
 
 
 
 
a24fc4c
 
 
ff3579e
 
a24fc4c
ff3579e
 
a24fc4c
 
 
 
 
ff3579e
a24fc4c
 
 
 
ff3579e
 
a24fc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff3579e
 
 
a24fc4c
 
 
 
95109ca
 
 
a24fc4c
 
 
 
 
 
95109ca
ff3579e
a24fc4c
 
 
 
 
 
ff3579e
 
 
 
a24fc4c
 
 
 
 
 
 
 
 
ff3579e
 
 
 
 
a24fc4c
 
 
 
 
 
 
ff3579e
 
a24fc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95109ca
a24fc4c
 
 
 
 
 
 
 
 
 
ff3579e
 
 
a24fc4c
 
 
 
 
ff3579e
 
 
a24fc4c
ff3579e
a24fc4c
ff3579e
a24fc4c
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
// Initialize Socket.IO connection with proper configuration
const socket = io({
    reconnection: true,
    reconnectionAttempts: 5,
    reconnectionDelay: 1000,
    transports: ['websocket', 'polling']  // Try WebSocket first, fallback to polling
});

class Game {
    constructor() {
        // Initialize core game state
        this.state = {
            gameId: null,
            currentPhase: 'landing',
            players: [],
            currentQuestion: null,
            isRecording: false,
            recordingTime: 30,
            listeningTime: 60,
            votingTime: 60,
            recordings: new Map(),
            votes: new Map(),
            impostor: null,
            maxPlayers: 5,
            minPlayers: 3,
            isConnected: false,
            errorDisplayed: false
        };

        // Initialize game when DOM is ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initialize());
        } else {
            this.initialize();
        }
    }

    initialize() {
        console.log('Initializing game components...');
        this.bindUIElements();
        this.initializeEventListeners();
        this.initializeSocketHandlers();
        this.showPage('landing');
    }

    bindUIElements() {
        console.log('Binding UI elements...');
        // Cache all UI elements for quick access
        this.ui = {
            gameContainer: document.getElementById('game-container'),
            pages: {
                landing: document.getElementById('landing-page'),
                setup: document.getElementById('setup-page'),
                recording: document.getElementById('recording-page'),
                listening: document.getElementById('listening-page'),
                voting: document.getElementById('voting-page'),
                results: document.getElementById('results-page')
            },
            buttons: {
                play: document.getElementById('play-button'),
                addPlayer: document.getElementById('add-player-button'),
                start: document.getElementById('start-button'),
                record: document.getElementById('record-button')
            },
            displays: {
                timer: document.getElementById('timer-display'),
                question: document.getElementById('question-display'),
                playerList: document.getElementById('player-list')
            }
        };

        // Log UI element bindings for debugging
        console.log('UI Elements bound:', {
            landing: !!this.ui.pages.landing,
            setup: !!this.ui.pages.setup,
            playButton: !!this.ui.buttons.play
        });
    }

    initializeEventListeners() {
        console.log('Setting up event listeners...');
        
        // Button click handlers
        if (this.ui.buttons.play) {
            this.ui.buttons.play.addEventListener('click', () => this.handlePlayButton());
        }

        if (this.ui.buttons.addPlayer) {
            this.ui.buttons.addPlayer.addEventListener('click', () => this.addPlayer());
        }

        if (this.ui.buttons.start) {
            this.ui.buttons.start.addEventListener('click', () => this.startGame());
        }

        if (this.ui.buttons.record) {
            this.ui.buttons.record.addEventListener('click', () => this.toggleRecording());
        }

        // Window resize handler for responsive layout
        window.addEventListener('resize', () => this.handleResize());
    }

    initializeSocketHandlers() {
        // Connection events
        socket.on('connect', () => {
            console.log('Connected to server');
            this.state.isConnected = true;
            this.clearError();
        });

        socket.on('disconnect', () => {
            console.log('Disconnected from server');
            this.state.isConnected = false;
            this.handleError('Connection lost. Attempting to reconnect...');
        });

        socket.on('connect_error', (error) => {
            console.error('Connection error:', error);
            this.handleError('Unable to connect to server. Please check your connection.');
        });

        // Game events
        socket.on('connection_success', (data) => {
            console.log('Connection successful:', data);
        });

        socket.on('game_created', (data) => {
            console.log('Game created:', data);
            if (data.status === 'success') {
                this.state.gameId = data.gameId;
                this.clearError();
                this.showPage('setup');
                this.addDefaultPlayers();
            } else {
                this.handleError('Failed to create game');
            }
        });

        socket.on('game_error', (data) => {
            console.error('Game error:', data);
            this.handleError(data.error || 'An error occurred');
        });

        socket.on('player_joined', (data) => {
            console.log('Player joined:', data);
            if (data.status === 'success') {
                // Update player list and UI
                const newPlayer = {
                    id: data.playerId,
                    name: data.playerName
                };
                this.state.players.push(newPlayer);
                this.updatePlayerList();
                this.updatePlayerControls();
            }
        });

        socket.on('round_started', (data) => {
            console.log('Round started:', data);
            this.handleRoundStart(data);
        });

        socket.on('recording_submitted', (data) => {
            console.log('Recording submitted:', data);
            this.updateRecordingStatus(data);
        });

        socket.on('round_result', (data) => {
            console.log('Round result:', data);
            this.handleRoundResult(data);
        });
    }

    async handlePlayButton() {
        console.log('Play button clicked');
        try {
            if (!this.state.isConnected) {
                throw new Error('Not connected to server');
            }
            this.clearError();
            await this.createGame();
        } catch (error) {
            console.error('Error handling play button:', error);
            this.handleError('Failed to start game. Please try again.');
        }
    }

    createGame() {
        return new Promise((resolve, reject) => {
            console.log('Creating new game...');
            
            // Reset game state
            this.state.gameId = null;
            this.state.players = [];
            
            // Emit create game event
            socket.emit('create_game');
            
            // Set timeout for response
            const timeout = setTimeout(() => {
                reject(new Error('Game creation timeout'));
            }, 5000);

            // Handle response
            socket.once('game_created', (data) => {
                clearTimeout(timeout);
                if (data.status === 'success') {
                    console.log('Game created successfully:', data);
                    resolve(data);
                } else {
                    reject(new Error(data.error || 'Failed to create game'));
                }
            });

            // Handle error
            socket.once('game_error', (data) => {
                clearTimeout(timeout);
                reject(new Error(data.error || 'Failed to create game'));
            });
        });
    }

    addDefaultPlayers() {
        console.log('Adding default players');
        if (!this.state.gameId) {
            console.error('No game ID available');
            return;
        }
        
        // Add two default players
        this.addPlayer('Player 1');
        this.addPlayer('Player 2');
    }

    addPlayer(defaultName = null) {
        if (this.state.players.length >= this.state.maxPlayers) {
            this.handleError('Maximum players reached');
            return;
        }

        const playerName = defaultName || `Player ${this.state.players.length + 1}`;
        console.log('Adding player:', playerName);

        socket.emit('join_game', {
            gameId: this.state.gameId,
            playerName: playerName
        });
    }

    async startGame() {
        console.log('Starting game...');
        try {
            const response = await fetch('/api/start_game', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    gameId: this.state.gameId
                })
            });

            const data = await response.json();
            if (data.status === 'success') {
                this.handleRoundStart(data);
            } else {
                throw new Error(data.error || 'Failed to start game');
            }
        } catch (error) {
            console.error('Error starting game:', error);
            this.handleError('Failed to start game');
        }
    }

    handleRoundStart(data) {
        console.log('Round starting:', data);
        this.state.currentQuestion = data.question;
        this.state.currentPhase = 'recording';
        this.showPage('recording');
        this.updateQuestionDisplay();
        this.startTimer(this.state.recordingTime);
    }

    updateQuestionDisplay() {
        if (this.ui.displays.question && this.state.currentQuestion) {
            this.ui.displays.question.textContent = this.state.currentQuestion;
        }
    }

    updatePlayerList() {
        if (!this.ui.displays.playerList) return;

        const playerList = this.ui.displays.playerList;
        playerList.innerHTML = '';
        
        const gridContainer = document.createElement('div');
        gridContainer.className = 'player-grid';

        this.state.players.forEach(player => {
            const playerCard = document.createElement('div');
            playerCard.className = 'player-card';
            
            const circle = document.createElement('div');
            circle.className = 'player-circle';
            circle.textContent = player.id;

            const name = document.createElement('div');
            name.className = 'player-name';
            name.textContent = player.name;

            playerCard.appendChild(circle);
            playerCard.appendChild(name);
            gridContainer.appendChild(playerCard);
        });

        playerList.appendChild(gridContainer);
    }

    updatePlayerControls() {
        if (this.ui.buttons.addPlayer) {
            this.ui.buttons.addPlayer.disabled = 
                this.state.players.length >= this.state.maxPlayers;
        }

        if (this.ui.buttons.start) {
            this.ui.buttons.start.disabled = 
                this.state.players.length < this.state.minPlayers;
        }
    }

    handleError(message) {
        console.error('Error:', message);
        
        // Prevent multiple error messages
        if (this.state.errorDisplayed) {
            return;
        }
        
        this.state.errorDisplayed = true;
        const errorElement = document.createElement('div');
        errorElement.className = 'error-message';
        errorElement.textContent = message;
        
        if (this.ui.gameContainer) {
            this.ui.gameContainer.appendChild(errorElement);
            setTimeout(() => {
                errorElement.remove();
                this.state.errorDisplayed = false;
            }, 3000);
        }
    }

    clearError() {
        const errorMessages = document.querySelectorAll('.error-message');
        errorMessages.forEach(msg => msg.remove());
        this.state.errorDisplayed = false;
    }

    showPage(pageName) {
        console.log('Showing page:', pageName);
        
        Object.values(this.ui.pages).forEach(page => {
            if (page) {
                page.classList.remove('active');
            }
        });

        const pageToShow = this.ui.pages[pageName];
        if (pageToShow) {
            pageToShow.classList.add('active');
            this.state.currentPhase = pageName;
        } else {
            console.error(`Page ${pageName} not found`);
        }
    }

    startTimer(duration) {
        let timeLeft = duration;
        this.updateTimerDisplay(timeLeft);

        this.timer = setInterval(() => {
            timeLeft--;
            this.updateTimerDisplay(timeLeft);

            if (timeLeft <= 0) {
                clearInterval(this.timer);
                this.handlePhaseEnd();
            }
        }, 1000);
    }

    updateTimerDisplay(timeLeft) {
        if (this.ui.displays.timer) {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            this.ui.displays.timer.textContent = 
                `${minutes}:${seconds.toString().padStart(2, '0')}`;
        }
    }

    handlePhaseEnd() {
        switch (this.state.currentPhase) {
            case 'recording':
                this.showPage('listening');
                this.startTimer(this.state.listeningTime);
                break;
            case 'listening':
                this.showPage('voting');
                this.startTimer(this.state.votingTime);
                break;
            case 'voting':
                this.showPage('results');
                break;
        }
    }

    cleanup() {
        // Clear timers
        if (this.timer) clearInterval(this.timer);
        
        // Remove event listeners
        window.removeEventListener('resize', this.handleResize);
        
        // Reset game state
        this.state = {
            gameId: null,
            currentPhase: 'landing',
            players: [],
            currentQuestion: null,
            isRecording: false,
            isConnected: false,
            errorDisplayed: false
        };
    }

    handleResize() {
        if (window.innerWidth < 768) {
            this.ui.gameContainer.classList.add('mobile');
        } else {
            this.ui.gameContainer.classList.remove('mobile');
        }
    }
}

// Initialize the game when the DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    console.log('Initializing game...');
    window.game = new Game();
});