您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
五子棋是一种经典的策略游戏,玩家通过在棋盘上交替落子,先形成五子连珠的一方获胜。本文将介绍如何使用JavaScript编写一个简单的五子棋小游戏。
首先,我们需要创建一个简单的HTML结构来显示棋盘和游戏状态。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>五子棋游戏</title>
<style>
#board {
display: grid;
grid-template-columns: repeat(15, 40px);
grid-template-rows: repeat(15, 40px);
gap: 1px;
background-color: #000;
}
.cell {
width: 40px;
height: 40px;
background-color: #fff;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.black {
background-color: black;
}
.white {
background-color: white;
}
</style>
</head>
<body>
<div id="board"></div>
<div id="status"></div>
<script src="gobang.js"></script>
</body>
</html>
在JavaScript中,我们需要创建一个15x15的棋盘,并为每个格子添加点击事件。
const boardSize = 15;
const board = document.getElementById('board');
const status = document.getElementById('status');
let currentPlayer = 'black';
let gameOver = false;
let boardState = Array.from({ length: boardSize }, () => Array(boardSize).fill(null));
function createBoard() {
for (let i = 0; i < boardSize; i++) {
for (let j = 0; j < boardSize; j++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.row = i;
cell.dataset.col = j;
cell.addEventListener('click', handleCellClick);
board.appendChild(cell);
}
}
}
createBoard();
当玩家点击一个格子时,我们需要检查该格子是否为空,并根据当前玩家的颜色落子。
function handleCellClick(event) {
if (gameOver) return;
const row = parseInt(event.target.dataset.row);
const col = parseInt(event.target.dataset.col);
if (boardState[row][col] !== null) return;
boardState[row][col] = currentPlayer;
event.target.classList.add(currentPlayer);
if (checkWin(row, col)) {
status.textContent = `${currentPlayer === 'black' ? '黑' : '白'}方获胜!`;
gameOver = true;
return;
}
currentPlayer = currentPlayer === 'black' ? 'white' : 'black';
status.textContent = `当前玩家:${currentPlayer === 'black' ? '黑' : '白'}方`;
}
我们需要编写一个函数来检查当前落子是否形成了五子连珠。
function checkWin(row, col) {
const directions = [
[1, 0], // 水平
[0, 1], // 垂直
[1, 1], // 对角线
[1, -1] // 反对角线
];
for (const [dx, dy] of directions) {
let count = 1;
// 正向检查
let x = row + dx;
let y = col + dy;
while (x >= 0 && x < boardSize && y >= 0 && y < boardSize && boardState[x][y] === currentPlayer) {
count++;
x += dx;
y += dy;
}
// 反向检查
x = row - dx;
y = col - dy;
while (x >= 0 && x < boardSize && y >= 0 && y < boardSize && boardState[x][y] === currentPlayer) {
count++;
x -= dx;
y -= dy;
}
if (count >= 5) {
return true;
}
}
return false;
}
现在,我们已经完成了五子棋游戏的基本功能。打开浏览器,点击棋盘上的格子,开始游戏吧!
通过以上步骤,我们使用JavaScript实现了一个简单的五子棋游戏。这个游戏虽然基础,但涵盖了HTML、CSS和JavaScript的基本用法。你可以在此基础上继续扩展,例如添加悔棋功能、计时器、对手等,使游戏更加丰富和有趣。
希望这篇文章对你有所帮助,祝你编程愉快!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。