html+js实现五子棋小游戏
时间: 2023-08-28 21:54:38 浏览: 49
当然!以下是一个使用 HTML 和 JavaScript 实现的五子小游戏的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>五子棋小游戏</title>
<style>
.board {
display: flex;
flex-wrap: wrap;
width: 400px;
height: 400px;
}
.cell {
box-sizing: border-box;
width: 20%;
height: 20%;
border: 1px solid #000;
cursor: pointer;
}
</style>
</head>
<body>
<div class="board"></div>
<script>
const boardSize = 15; // 棋盘大小
const board = document.querySelector('.board');
let currentPlayer = 'X';
let gameOver = false;
const cells = []; // 存储每个格子的状态,0 表示空,1 表示玩家 X,2 表示玩家 O
for (let i = 0; i < boardSize * boardSize; i++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.addEventListener('click', () => {
if (cells[i] === 0 && !gameOver) {
cell.innerHTML = currentPlayer;
cells[i] = currentPlayer === 'X' ? 1 : 2;
if (checkWin(i)) {
gameOver = true;
alert(currentPlayer + '赢了!');
}
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
});
board.appendChild(cell);
cells.push(0);
}
function checkWin(index) {
const row = Math.floor(index / boardSize);
const col = index % boardSize;
const directions = [
[0, 1], [1, 0], [1, 1], [1, -1] // 水平、垂直、对角线方向
];
for (let i = 0; i < directions.length; i++) {
const [dx, dy] = directions[i];
let count = 1;
let x = row + dx;
let y = col + dy;
while (x >= 0 && x < boardSize && y >= 0 && y < boardSize && cells[x * boardSize + y] === cells[index]) {
count++;
x += dx;
y += dy;
}
x = row - dx;
y = col - dy;
while (x >= 0 && x < boardSize && y >= 0 && y < boardSize && cells[x * boardSize + y] === cells[index]) {
count++;
x -= dx;
y -= dy;
}
if (count >= 5) {
return true;
}
}
return false;
}
</script>
</body>
</html>
```
这个示例中,棋盘由 HTML 的 `<div>` 元素组成,每个格子通过添加 `.cell` 类来表示。玩家可以通过点击格子来下棋,游戏会检测是否有玩家获胜。
希望这个示例对您有帮助!如果您有其他问题,请随时提问。