gomoku / index.html
CCsuper's picture
no board is shown - Initial Deployment
b06b77c verified
Raw History Blame Contribute Delete
19 kB
<!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>