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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gomoku (Five in a Row) - Human vs AI</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
    <style>
        .board {
            display: grid;
            grid-template-columns: repeat(15, 1fr);
            grid-template-rows: repeat(15, 1fr);
            gap: 1px;
            background-color: #deb887;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            width: 600px;
            height: 600px;
        }
        .board-container {
            width: 620px;
            height: 620px;
        }
        .cell {
            aspect-ratio: 1/1;
            background-color: rgba(222, 184, 135, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            transition: all 0.2s ease;
            position: relative;
        }
        .cell:hover {
            background-color: rgba(222, 184, 135, 0.6);
        }
        .cell::before {
            content: '';
            position: absolute;
            width: 100%;
            height: 100%;
            border: 1px solid rgba(139, 69, 19, 0.3);
        }
        .piece {
            width: 80%;
            height: 80%;
            border-radius: 50%;
            z-index: 10;
        }
        .black {
            background: radial-gradient(circle at 30% 30%, #666, #000);
            box-shadow: 0 3px 5px rgba(0, 0, 0, 0.5);
        }
        .white {
            background: radial-gradient(circle at 30% 30%, #fff, #ddd);
            box-shadow: 0 3px 5px rgba(0, 0, 0, 0.3);
        }
        .win-line {
            position: absolute;
            background-color: rgba(255, 0, 0, 0.7);
            z-index: 5;
        }
        @media (max-width: 640px) {
            .board {
                grid-template-columns: repeat(15, minmax(0, 1fr));
                grid-template-rows: repeat(15, minmax(0, 1fr));
                gap: 0.5px;
                padding: 5px;
                width: 300px;
                height: 300px;
            }
            .board-container {
                width: 310px;
                height: 310px;
            }
        }
    </style>
</head>
<body class="bg-amber-50 min-h-screen flex flex-col items-center justify-center p-4">
    <div class="max-w-4xl w-full">
        <h1 class="text-3xl md:text-4xl font-bold text-center text-amber-900 mb-6">Gomoku (Five in a Row)</h1>
        
        <div class="flex flex-col md:flex-row gap-6 items-center md:items-start">
            <div class="board-container relative mx-auto">
                <div id="board" class="board"></div>
                <div id="win-line" class="win-line hidden"></div>
            </div>
            
            <div class="bg-white p-6 rounded-lg shadow-md w-full md:w-64">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-semibold text-gray-800">Game Info</h2>
                    <button id="reset-btn" class="p-2 rounded-full bg-amber-100 text-amber-800 hover:bg-amber-200 transition">
                        <i data-feather="refresh-cw"></i>
                    </button>
                </div>
                
                <div class="mb-6">
                    <div class="flex items-center justify-between mb-2">
                        <span class="font-medium">Player (Black)</span>
                        <div class="piece black w-6 h-6"></div>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="font-medium">AI (White)</span>
                        <div class="piece white w-6 h-6"></div>
                    </div>
                </div>
                
                <div id="status" class="p-3 bg-amber-100 rounded text-center text-amber-900 font-medium mb-4">
                    Your turn (Black)
                </div>
                
                <div class="space-y-2">
                    <div class="flex items-center gap-2">
                        <i data-feather="info" class="text-amber-600"></i>
                        <span class="text-sm text-gray-600">First move must be center</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <i data-feather="award" class="text-amber-600"></i>
                        <span class="text-sm text-gray-600">Connect 5 to win</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        feather.replace();
        
        document.addEventListener('DOMContentLoaded', () => {
            const board = document.getElementById('board');
            const status = document.getElementById('status');
            const resetBtn = document.getElementById('reset-btn');
            const winLine = document.getElementById('win-line');
            
            const BOARD_SIZE = 15;
            let currentPlayer = 'black'; // Human starts first
            let gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(null));
            let gameOver = false;
            
            // Initialize board
            function initializeBoard() {
                board.innerHTML = '';
                for (let row = 0; row < BOARD_SIZE; row++) {
                    for (let col = 0; col < BOARD_SIZE; col++) {
                        const cell = document.createElement('div');
                        cell.className = 'cell';
                        cell.dataset.row = row;
                        cell.dataset.col = col;
                        
                        // Center point for first move
                        if (row === Math.floor(BOARD_SIZE/2) && col === Math.floor(BOARD_SIZE/2)) {
                            cell.classList.add('bg-amber-300');
                        }
                        
                        cell.addEventListener('click', () => handleCellClick(row, col));
                        board.appendChild(cell);
                    }
                }
            }
            
            // Handle cell click
            function handleCellClick(row, col) {
                if (gameOver || gameBoard[row][col] !== null) return;
                
                // First move must be center
                if (currentPlayer === 'black' && 
                    Object.values(gameBoard.flat()).every(val => val === null) &&
                    !(row === Math.floor(BOARD_SIZE/2) && col === Math.floor(BOARD_SIZE/2))) {
                    status.textContent = 'First move must be center!';
                    return;
                }
                
                placePiece(row, col, currentPlayer);
                
                if (checkWin(row, col, currentPlayer)) {
                    gameOver = true;
                    status.textContent = currentPlayer === 'black' ? 'You win!' : 'AI wins!';
                    return;
                }
                
                if (isBoardFull()) {
                    gameOver = true;
                    status.textContent = "It's a draw!";
                    return;
                }
                
                currentPlayer = currentPlayer === 'black' ? 'white' : 'black';
                status.textContent = currentPlayer === 'black' ? 'Your turn (Black)' : 'AI thinking...';
                
                if (currentPlayer === 'white') {
                    setTimeout(makeAIMove, 800);
                }
            }
            
            // Place a piece on the board
            function placePiece(row, col, color) {
                gameBoard[row][col] = color;
                const cell = document.querySelector(`.cell[data-row="${row}"][data-col="${col}"]`);
                const piece = document.createElement('div');
                piece.className = `piece ${color}`;
                cell.appendChild(piece);
            }
            
            // Check for win condition
            function checkWin(row, col, color) {
                const directions = [
                    [0, 1],  // horizontal
                    [1, 0],  // vertical
                    [1, 1],  // diagonal down-right
                    [1, -1]  // diagonal down-left
                ];
                
                for (const [dx, dy] of directions) {
                    let count = 1;
                    
                    // Check in positive direction
                    for (let i = 1; i <= 4; i++) {
                        const newRow = row + i * dx;
                        const newCol = col + i * dy;
                        
                        if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE || 
                            gameBoard[newRow][newCol] !== color) {
                            break;
                        }
                        count++;
                    }
                    
                    // Check in negative direction
                    for (let i = 1; i <= 4; i++) {
                        const newRow = row - i * dx;
                        const newCol = col - i * dy;
                        
                        if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE || 
                            gameBoard[newRow][newCol] !== color) {
                            break;
                        }
                        count++;
                    }
                    
                    if (count >= 5) {
                        drawWinLine(row, col, dx, dy);
                        return true;
                    }
                }
                
                return false;
            }
            
            // Draw win line
            function drawWinLine(row, col, dx, dy) {
                // Find start and end of the winning line
                let startRow = row, startCol = col;
                let endRow = row, endCol = col;
                
                while (startRow - dx >= 0 && startCol - dy >= 0 && 
                       startCol - dy < BOARD_SIZE && 
                       gameBoard[startRow - dx][startCol - dy] === gameBoard[row][col]) {
                    startRow -= dx;
                    startCol -= dy;
                }
                
                while (endRow + dx < BOARD_SIZE && endCol + dy < BOARD_SIZE && 
                       endCol + dy >= 0 && 
                       gameBoard[endRow + dx][endCol + dy] === gameBoard[row][col]) {
                    endRow += dx;
                    endCol += dy;
                }
                
                // Get cell positions
                const startCell = document.querySelector(`.cell[data-row="${startRow}"][data-col="${startCol}"]`);
                const endCell = document.querySelector(`.cell[data-row="${endRow}"][data-col="${endCol}"]`);
                
                const startRect = startCell.getBoundingClientRect();
                const endRect = endCell.getBoundingClientRect();
                const boardRect = board.getBoundingClientRect();
                
                // Calculate line position and dimensions
                const lineWidth = Math.sqrt(
                    Math.pow(endRect.left - startRect.left, 2) + 
                    Math.pow(endRect.top - startRect.top, 2)
                ) + startRect.width;
                
                const lineAngle = Math.atan2(
                    endRect.top + endRect.height/2 - (startRect.top + startRect.height/2),
                    endRect.left + endRect.width/2 - (startRect.left + startRect.width/2)
                );
                
                // Position the line
                winLine.style.width = `${lineWidth}px`;
                winLine.style.height = '4px';
                winLine.style.left = `${startRect.left - boardRect.left + startRect.width/2}px`;
                winLine.style.top = `${startRect.top - boardRect.top + startRect.height/2}px`;
                winLine.style.transformOrigin = '0 0';
                winLine.style.transform = `rotate(${lineAngle}rad)`;
                winLine.classList.remove('hidden');
            }
            
            // Check if board is full
            function isBoardFull() {
                return gameBoard.flat().every(cell => cell !== null);
            }
            
            // AI move logic
            function makeAIMove() {
                if (gameOver) return;
                
                // Simple AI: first try to win, then block player, then random move
                let bestMove = null;
                
                // 1. Check if AI can win in the next move
                bestMove = findWinningMove('white');
                
                // 2. If not, check if player can win in the next move and block
                if (!bestMove) {
                    bestMove = findWinningMove('black');
                }
                
                // 3. If no immediate win/loss, make a strategic move
                if (!bestMove) {
                    bestMove = findStrategicMove();
                }
                
                // 4. If no strategic move found, make a random move
                if (!bestMove) {
                    bestMove = findRandomMove();
                }
                
                if (bestMove) {
                    const [row, col] = bestMove;
                    placePiece(row, col, 'white');
                    
                    if (checkWin(row, col, 'white')) {
                        gameOver = true;
                        status.textContent = 'AI wins!';
                        return;
                    }
                    
                    if (isBoardFull()) {
                        gameOver = true;
                        status.textContent = "It's a draw!";
                        return;
                    }
                    
                    currentPlayer = 'black';
                    status.textContent = 'Your turn (Black)';
                }
            }
            
            // Find winning move for given player
            function findWinningMove(player) {
                for (let row = 0; row < BOARD_SIZE; row++) {
                    for (let col = 0; col < BOARD_SIZE; col++) {
                        if (gameBoard[row][col] === null) {
                            gameBoard[row][col] = player;
                            if (checkWin(row, col, player)) {
                                gameBoard[row][col] = null; // Undo move
                                return [row, col];
                            }
                            gameBoard[row][col] = null; // Undo move
                        }
                    }
                }
                return null;
            }
            
            // Find strategic move (prioritize center and existing patterns)
            function findStrategicMove() {
                const center = Math.floor(BOARD_SIZE/2);
                const directions = [[0,1],[1,0],[1,1],[1,-1]];
                let bestScore = -1;
                let bestMove = null;
                
                for (let row = 0; row < BOARD_SIZE; row++) {
                    for (let col = 0; col < BOARD_SIZE; col++) {
                        if (gameBoard[row][col] !== null) continue;
                        
                        // Prefer center positions
                        let score = (BOARD_SIZE - Math.abs(row - center) - Math.abs(col - center)) / 2;
                        
                        // Check for patterns around this cell
                        for (const [dx, dy] of directions) {
                            // Check for AI patterns to extend
                            const aiPattern = countPattern(row, col, dx, dy, 'white');
                            if (aiPattern >= 2) score += aiPattern * 5;
                            
                            // Check for player patterns to block
                            const playerPattern = countPattern(row, col, dx, dy, 'black');
                            if (playerPattern >= 2) score += playerPattern * 3;
                        }
                        
                        if (score > bestScore) {
                            bestScore = score;
                            bestMove = [row, col];
                        }
                    }
                }
                
                return bestMove;
            }
            
            // Count consecutive pieces in a direction
            function countPattern(row, col, dx, dy, player) {
                let count = 0;
                
                for (let i = -4; i <= 4; i++) {
                    if (i === 0) continue; // Skip the current cell
                    
                    const newRow = row + i * dx;
                    const newCol = col + i * dy;
                    
                    if (newRow >= 0 && newRow < BOARD_SIZE && newCol >= 0 && newCol < BOARD_SIZE) {
                        if (gameBoard[newRow][newCol] === player) {
                            count++;
                        } else if (gameBoard[newRow][newCol] !== null) {
                            count = 0;
                            break;
                        }
                    }
                }
                
                return count;
            }
            
            // Find random valid move
            function findRandomMove() {
                const emptyCells = [];
                
                for (let row = 0; row < BOARD_SIZE; row++) {
                    for (let col = 0; col < BOARD_SIZE; col++) {
                        if (gameBoard[row][col] === null) {
                            emptyCells.push([row, col]);
                        }
                    }
                }
                
                if (emptyCells.length > 0) {
                    return emptyCells[Math.floor(Math.random() * emptyCells.length)];
                }
                
                return null;
            }
            
            // Reset game
            function resetGame() {
                gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(null));
                currentPlayer = 'black';
                gameOver = false;
                status.textContent = 'Your turn (Black)';
                winLine.classList.add('hidden');
                initializeBoard();
            }
            
            resetBtn.addEventListener('click', resetGame);
            
            // Initialize the game
            initializeBoard();
        });
    </script>
</body>
</html>