A simple Gomoku game where two players take turns to place black and white stones on a 15x15 board. The first player to align five stones in a row, column, or diagonal wins.
Prompt
create a Gomoku game.
HTML
<div class="gomoku-board" id="board"></div><div id="info" class="info">Black's turn</div>
CSS
.gomoku-board { display: grid; grid-template-columns: repeat(15, 30px); grid-template-rows: repeat(15, 30px); gap: 1px; margin: 20px auto; border: 2px solid #333; background-color: #ccc; } .gomoku-board div { width: 30px; height: 30px; background-color: #f2f2f2; display: flex; justify-content: center; align-items: center; font-size: 24px; } .info { text-align: center; margin-top: 10px; font-size: 18px; color: #333; }JS
(function() {
const boardElement = document.getElementById('board');
const infoElement = document.getElementById('info');
const SIZE = 15;
let board = Array(SIZE * SIZE).fill(null);
let currentPlayer = 'Black';
boardElement.innerHTML = board.map((_, index) => `<div data-index="${index}"></div>`).join('');
boardElement.addEventListener('click', (event) => {
const target = event.target;
const index = parseInt(target.getAttribute('data-index'));
if (board[index] || checkWin()) return;
board[index] = currentPlayer;
target.textContent = currentPlayer === 'Black' ? '⚫' : '⚪';
if (checkWin()) {
infoElement.textContent = `${currentPlayer} wins!`;
} else {
currentPlayer = currentPlayer === 'Black' ? 'White' : 'Black';
infoElement.textContent = `${currentPlayer}'s turn`;
}
});
function checkWin() {
const directions = [[1, 0], [0, 1], [1, 1], [1, -1]];
for (let i = 0; i < board.length; i++) {
for (let [dx, dy] of directions) {
if (checkDirection(i, dx, dy)) return true;
}
}
return false;
}
function checkDirection(index, dx, dy) {
const row = Math.floor(index / SIZE);
const col = index % SIZE;
const current = board[index];
if (!current) return false;
for (let n = 1; n < 5; n++) {
const newRow = row + dy * n;
const newCol = col + dx * n;
const newIndex = newRow * SIZE + newCol;
if (
newRow < 0 || newRow >= SIZE ||
newCol < 0 || newCol >= SIZE ||
board[newIndex] !== current
) {
return false;
}
}
return true;
}
})();Comments (0)
Log in to comment.
Working...