File size: 9,548 Bytes
c64ad8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

document.addEventListener('DOMContentLoaded', () => {
    // Game sounds
    const sounds = {
        click: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-arcade-game-jump-coin-216.mp3'),
        win: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-winning-chimes-2015.mp3'),
        draw: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-retro-arcade-lose-2027.mp3'),
        reset: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-quick-jump-arcade-game-239.mp3'),
        background: new Audio('https://assets.mixkit.co/music/preview/mixkit-game-show-suspense-waiting-668.mp3'),
        modeChange: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-arcade-mechanical-bling-210.mp3')
    };

    sounds.background.loop = true;
// Game state
    let board = ['', '', '', '', '', '', '', '', ''];
    let autoPlayInterval = null;
let currentPlayer = 'X';
    let gameActive = true;
    let gameMode = 'player'; // 'player' or 'ai'
    let scores = { X: 0, O: 0 };
    // DOM elements
    const bodyElement = document.body;
    const boardElement = document.querySelector('.grid');
    const autoPlayButton = document.createElement('button');
    autoPlayButton.id = 'autoPlay';
    autoPlayButton.className = 'px-4 py-2 bg-purple-500 text-white rounded-lg font-medium shadow hover:bg-purple-600 transition';
    autoPlayButton.textContent = 'Auto Play';
    document.querySelector('.flex.space-x-2').appendChild(autoPlayButton);
const currentPlayerElement = document.getElementById('currentPlayer');
    const gameStatusElement = document.getElementById('gameStatus');
    const scoreXElement = document.getElementById('scoreX');
    const scoreOElement = document.getElementById('scoreO');
    const resetButton = document.getElementById('resetGame');
    const playerModeButton = document.getElementById('playerMode');
    const aiModeButton = document.getElementById('aiMode');
    // Apply dynamic background with animated gradient
    function applyDynamicBackground() {
        const colors = [
            ['#3B82F6', '#EC4899'],
            ['#EC4899', '#10B981'],
            ['#10B981', '#F59E0B'],
            ['#F59E0B', '#6366F1'],
            ['#6366F1', '#3B82F6'],
            ['#8B5CF6', '#F43F5E'],
            ['#F43F5E', '#14B8A6']
        ];
        
        const [color1, color2] = colors[Math.floor(Math.random() * colors.length)];
        bodyElement.style.background = `linear-gradient(135deg, ${color1} 0%, ${color2} 100%)`;
        bodyElement.style.backgroundAttachment = 'fixed';
        bodyElement.style.backgroundSize = '200% 200%';
        bodyElement.style.animation = 'gradientPulse 6s ease infinite';
    }

    // Add gradient animation keyframes to style
    const style = document.createElement('style');
    style.textContent = `
        @keyframes gradientPulse {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
    `;
    document.head.appendChild(style);
    // Initialize the game
    function initGame() {
        if (autoPlayInterval) {
            clearInterval(autoPlayInterval);
            autoPlayInterval = null;
            autoPlayButton.textContent = 'Auto Play';
        }
        
        sounds.background.currentTime = 0;
        sounds.background.volume = 0.2;
        sounds.background.play();
board = ['', '', '', '', '', '', '', '', ''];
        currentPlayer = 'X';
        gameActive = true;
        renderBoard();
        updateGameInfo();
    }

    // Render the game board
    function renderBoard() {
        boardElement.innerHTML = '';
        board.forEach((cell, index) => {
            const cellElement = document.createElement('div');
            cellElement.className = `cell bg-gray-50 rounded-lg shadow-md flex items-center justify-center ${cell === 'X' ? 'cell-x' : 'cell-o'}`;
            cellElement.textContent = cell;
            cellElement.addEventListener('click', () => handleCellClick(index));
            boardElement.appendChild(cellElement);
        });
    }
    // Auto play mode with enhanced visuals
    function toggleAutoPlay() {
        if (autoPlayInterval) {
            clearInterval(autoPlayInterval);
            autoPlayInterval = null;
            autoPlayButton.textContent = 'Auto Play';
            autoPlayButton.classList.remove('bg-yellow-500');
            autoPlayButton.classList.add('bg-purple-500');
            gameActive = true;
        } else {
            sounds.modeChange.play();
            autoPlayButton.textContent = 'Stop Auto Play';
            autoPlayButton.classList.remove('bg-purple-500');
            autoPlayButton.classList.add('bg-yellow-500');
            initGame();
            autoPlayInterval = setInterval(() => {
                if (!gameActive) {
                    setTimeout(() => {
                        applyDynamicBackground();
                        initGame();
                    }, 1500);
                    return;
                }
                const emptyCells = board.map((cell, index) => cell === '' ? index : null).filter(val => val !== null);
                if (emptyCells.length > 0) {
                    const randomIndex = Math.floor(Math.random() * emptyCells.length);
                    handleCellClick(emptyCells[randomIndex], true);
                }
            }, 600);
        }
    }
// Handle cell click
    function handleCellClick(index, isAutoPlay = false) {
if (!gameActive || board[index] !== '') return;

        // Make move
        sounds.click.play();
        board[index] = currentPlayer;
        renderBoard();
        applyDynamicBackground();
// Check for win or draw
        if (checkWin()) {
            sounds.win.play();
            handleWin();
        } else if (checkDraw()) {
            sounds.draw.play();
            handleDraw();
} else {
            // Switch player
            currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
            updateGameInfo();

            // AI move if in AI mode
            if (gameMode === 'ai' && currentPlayer === 'O' && gameActive) {
                setTimeout(makeAIMove, 500);
            }
        }
    }

    // AI move logic (simple random move)
    function makeAIMove() {
        const emptyCells = board.map((cell, index) => cell === '' ? index : null).filter(val => val !== null);
        if (emptyCells.length > 0) {
            const randomIndex = Math.floor(Math.random() * emptyCells.length);
            handleCellClick(emptyCells[randomIndex]);
        }
    }

    // Check for win
    function checkWin() {
        const winPatterns = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8], // rows
            [0, 3, 6], [1, 4, 7], [2, 5, 8], // columns
            [0, 4, 8], [2, 4, 6]             // diagonals
        ];

        return winPatterns.some(pattern => {
            const [a, b, c] = pattern;
            return board[a] !== '' && board[a] === board[b] && board[a] === board[c];
        });
    }

    // Check for draw
    function checkDraw() {
        return board.every(cell => cell !== '');
    }

    // Handle win
    function handleWin() {
        gameActive = false;
        scores[currentPlayer]++;
        updateScores();
        gameStatusElement.textContent = `Player ${currentPlayer} wins!`;
        highlightWinningCells();
    }

    // Handle draw
    function handleDraw() {
        gameActive = false;
        gameStatusElement.textContent = "It's a draw!";
    }

    // Highlight winning cells
    function highlightWinningCells() {
        const winPatterns = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],
            [0, 3, 6], [1, 4, 7], [2, 5, 8],
            [0, 4, 8], [2, 4, 6]
        ];

        const winningPattern = winPatterns.find(pattern => {
            const [a, b, c] = pattern;
            return board[a] !== '' && board[a] === board[b] && board[a] === board[c];
        });

        if (winningPattern) {
            winningPattern.forEach(index => {
                boardElement.children[index].classList.add('winning-cell');
            });
        }
    }

    // Update game info
    function updateGameInfo() {
        currentPlayerElement.textContent = `Player ${currentPlayer}'s Turn`;
    }

    // Update scores
    function updateScores() {
        scoreXElement.textContent = scores.X;
        scoreOElement.textContent = scores.O;
    }

    // Event listeners
    resetButton.addEventListener('click', () => {
        sounds.reset.play();
        initGame();
        applyDynamicBackground();
    });

    autoPlayButton.addEventListener('click', toggleAutoPlay);
playerModeButton.addEventListener('click', () => {
        gameMode = 'player';
        playerModeButton.classList.remove('bg-gray-200', 'text-gray-700');
        playerModeButton.classList.add('bg-blue-500', 'text-white');
        aiModeButton.classList.remove('bg-blue-500', 'text-white');
        aiModeButton.classList.add('bg-gray-200', 'text-gray-700');
        initGame();
    });

    aiModeButton.addEventListener('click', () => {
        gameMode = 'ai';
        aiModeButton.classList.remove('bg-gray-200', 'text-gray-700');
        aiModeButton.classList.add('bg-blue-500', 'text-white');
        playerModeButton.classList.remove('bg-blue-500', 'text-white');
        playerModeButton.classList.add('bg-gray-200', 'text-gray-700');
        initGame();
    });
    // Initialize with intro animation
    setTimeout(() => {
        applyDynamicBackground();
        initGame();
    }, 500);
});