File size: 11,129 Bytes
faf907f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bdee50
faf907f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
class RoomTicTacToeGame {
    constructor() {
        this.currentRoomId = null;
        this.roomData = null;
        this.cells = document.querySelectorAll('.cell');
        this.gameStatus = document.getElementById('gameStatus');
        this.roomInfo = document.getElementById('roomInfo');
        this.chatMessages = document.getElementById('chatMessages');
        this.chatInput = document.getElementById('chatInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.gameArea = document.getElementById('gameArea');
        this.noRoom = document.getElementById('noRoom');
        
        this.initGame();
    }

    initGame() {
        this.cells.forEach((cell, index) => {
            cell.addEventListener('click', () => this.handleCellClick(index));
        });

        // Update room state every 2 seconds if in a room
        setInterval(() => {
            if (this.currentRoomId) {
                this.refreshRoomState();
            }
        }, 2000);
    }

    async createNewRoom() {
        try {
            const response = await fetch('/rooms', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            this.joinRoomById(data.room_id);
            
        } catch (error) {
            console.error('Failed to create room:', error);
            this.gameStatus.textContent = "Failed to create room. Try again.";
        }
    }

    async joinRoom() {
        const roomId = document.getElementById('roomIdInput').value.trim();
        if (!roomId) {
            this.gameStatus.textContent = "Please enter a room ID";
            return;
        }
        
        await this.joinRoomById(roomId);
    }

    async joinRoomById(roomId) {
        try {
            const response = await fetch(`/rooms/${roomId}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            this.currentRoomId = roomId;
            this.roomData = data.room_data;
            
            // Clear the input
            document.getElementById('roomIdInput').value = '';
            
            // Show game area and enable chat
            this.gameArea.style.display = 'block';
            this.noRoom.style.display = 'none';
            this.chatInput.disabled = false;
            this.sendBtn.disabled = false;
            this.chatInput.placeholder = "Type a message...";
            
            // Update display
            this.updateDisplay();
            this.loadChatHistory();
            
            this.gameStatus.textContent = `Joined room ${roomId}!`;
            
        } catch (error) {
            console.error('Failed to join room:', error);
            this.gameStatus.textContent = `Failed to join room ${roomId}. Check the room ID.`;
        }
    }

    leaveRoom() {
        this.currentRoomId = null;
        this.roomData = null;
        
        // Hide game area and disable chat
        this.gameArea.style.display = 'none';
        this.noRoom.style.display = 'block';
        this.chatInput.disabled = true;
        this.sendBtn.disabled = true;
        this.chatInput.placeholder = "Join a room first...";
        
        // Clear display
        this.clearBoard();
        this.gameStatus.textContent = "Create or join a room to start playing!";
        this.updateRoomInfo();
        
        // Clear chat
        this.chatMessages.innerHTML = `
            <div class="message ai">
                <div class="message-sender">System:</div>
                <div>Create or join a room to start chatting with Mistral AI!</div>
            </div>
        `;
    }

    async refreshRoomState() {
        if (!this.currentRoomId) return;
        
        try {
            const response = await fetch(`/rooms/${this.currentRoomId}`);
            
            if (!response.ok) {
                if (response.status === 404) {
                    this.gameStatus.textContent = "Room no longer exists!";
                    this.leaveRoom();
                    return;
                }
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            this.roomData = data.room_data;
            this.updateDisplay();
            
        } catch (error) {
            console.error('Failed to refresh room:', error);
        }
    }

    async handleCellClick(index) {
        if (!this.currentRoomId || !this.roomData) {
            this.gameStatus.textContent = "Join a room first!";
            return;
        }

        if (this.roomData.game_status !== 'active' || 
            this.roomData.board[index] !== '' || 
            this.roomData.current_player !== 'X') {
            return;
        }

        this.gameStatus.textContent = "Making your move...";
        
        try {
            const response = await fetch(`/rooms/${this.currentRoomId}/move`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    position: index
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            this.roomData = data.room_data;
            this.updateDisplay();
            this.loadChatHistory(); // Reload chat to get AI's move message
            
            if (this.roomData.game_status === 'active') {
                this.gameStatus.textContent = "Mistral is thinking...";
                setTimeout(() => {
                    if (this.roomData.current_player === 'X') {
                        this.gameStatus.textContent = "Your turn! Click a square.";
                    }
                }, 1000);
            }
            
        } catch (error) {
            console.error('Move failed:', error);
            this.gameStatus.textContent = "Move failed. Try again.";
        }
    }

    async sendChatMessage() {
        if (!this.currentRoomId) {
            return;
        }

        const message = this.chatInput.value.trim();
        if (!message) return;
        
        this.chatInput.value = '';
        
        try {
            const response = await fetch(`/rooms/${this.currentRoomId}/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    message: message
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            this.roomData = data.room_data;
                this.loadChatHistory();
            
        } catch (error) {
            console.error('Chat failed:', error);
            this.addChatMessage("Failed to send message", 'system');
        }
    }

    updateDisplay() {
        if (!this.roomData) return;

        // Update board
        this.roomData.board.forEach((cell, index) => {
            this.cells[index].textContent = cell;
            this.cells[index].className = 'cell';
            if (cell) {
                this.cells[index].classList.add(cell.toLowerCase());
            }
        });

        // Update game status
        if (this.roomData.game_status === 'won') {
            const winner = this.roomData.winner === 'X' ? 'You' : 'Mistral AI';
            this.gameStatus.textContent = `🎉 ${winner} won!`;
        } else if (this.roomData.game_status === 'draw') {
            this.gameStatus.textContent = "🤝 It's a draw!";
        } else if (this.roomData.current_player === 'X') {
            this.gameStatus.textContent = "Your turn! Click a square.";
        } else {
            this.gameStatus.textContent = "Mistral's turn...";
        }

        this.updateRoomInfo();
    }

    updateRoomInfo() {
        if (!this.roomData || !this.currentRoomId) {
            this.roomInfo.innerHTML = `
                <div>Status: No room selected</div>
                <div>Room ID: -</div>
                <div>Game Status: -</div>
                <div>Your Turn: -</div>
            `;
            return;
        }

        const isYourTurn = this.roomData.current_player === 'X' && this.roomData.game_status === 'active';
        this.roomInfo.innerHTML = `
            <div>Status: Connected</div>
            <div>Room ID: ${this.currentRoomId}</div>
            <div>Game Status: ${this.roomData.game_status}</div>
            <div>Your Turn: ${isYourTurn ? 'Yes' : 'No'}</div>
            <div>Moves: ${this.roomData.moves_count}/9</div>
        `;
    }


    loadChatHistory() {
        if (!this.roomData || !this.roomData.chat_history) return;

        this.chatMessages.innerHTML = '';
        
        this.roomData.chat_history.forEach(msg => {
            this.addChatMessage(msg.message, msg.sender);
        });
    }

    addChatMessage(message, sender) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${sender}`;
        
        const senderDiv = document.createElement('div');
        senderDiv.className = 'message-sender';
        
        let senderName;
        if (sender === 'user') senderName = 'You:';
        else if (sender === 'ai') senderName = 'Mistral AI:';
        else senderName = 'System:';
        
        senderDiv.textContent = senderName;
        
        const contentDiv = document.createElement('div');
        contentDiv.textContent = message;
        
        messageDiv.appendChild(senderDiv);
        messageDiv.appendChild(contentDiv);
        this.chatMessages.appendChild(messageDiv);
        
        // Scroll to bottom
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }

    clearBoard() {
        this.cells.forEach(cell => {
            cell.textContent = '';
            cell.className = 'cell';
        });
    }

    async resetGame() {
        if (!this.currentRoomId) return;
        
        // Create a new room instead of resetting current one
        await this.createNewRoom();
    }
}

// Global functions for HTML onclick events
let game;

function createNewRoom() {
    game.createNewRoom();
}

function joinRoom() {
    game.joinRoom();
}

function leaveRoom() {
    game.leaveRoom();
}

function sendChatMessage() {
    game.sendChatMessage();
}

function handleEnter(event) {
    if (event.key === 'Enter') {
        sendChatMessage();
    }
}

function resetGame() {
    game.resetGame();
}

// Initialize game when page loads
document.addEventListener('DOMContentLoaded', () => {
    game = new RoomTicTacToeGame();
});