推箱子(Sokoban)是一款经典的益智游戏,玩家需要通过移动箱子,将它们推到指定的目标位置。下面是一个简单的JavaScript实现推箱子游戏的示例代码。
以下是一个简单的推箱子游戏的JavaScript实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>推箱子游戏</title>
<style>
.wall { background-color: #000; }
.player { background-color: blue; }
.box { background-color: red; }
.target { background-color: green; }
.empty { background-color: #fff; }
</style>
</head>
<body>
<div id="game-board"></div>
<script>
const board = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 2, 3, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
];
const playerPos = { x: 2, y: 2 };
const boxPos = { x: 3, y: 2 };
const targetPos = { x: 3, y: 3 };
function renderBoard() {
const gameBoard = document.getElementById('game-board');
gameBoard.innerHTML = '';
board.forEach((row, y) => {
row.forEach((cell, x) => {
const div = document.createElement('div');
div.style.width = '50px';
div.style.height = '50px';
div.style.display = 'inline-block';
div.style.border = '1px solid #ccc';
if (cell === 1) {
div.className = 'wall';
} else if (x === playerPos.x && y === playerPos.y) {
div.className = 'player';
} else if (x === boxPos.x && y === boxPos.y) {
div.className = 'box';
} else if (x === targetPos.x && y === targetPos.y) {
div.className = 'target';
} else {
div.className = 'empty';
}
gameBoard.appendChild(div);
});
});
}
document.addEventListener('keydown', (e) => {
let newX = playerPos.x;
let newY = playerPos.y;
switch (e.key) {
case 'ArrowUp': newY--; break;
case 'ArrowDown': newY++; break;
case 'ArrowLeft': newX--; break;
case 'ArrowRight': newX++; break;
}
if (board[newY][newX] !== 1) {
if (newX === boxPos.x && newY === boxPos.y) {
const newBoxX = newX + (newX - playerPos.x);
const newBoxY = newY + (newY - playerPos.y);
if (board[newBoxY][newBoxX] !== 1 && board[newBoxY][newBoxX] !== 3) {
boxPos.x = newBoxX;
boxPos.y = newBoxY;
}
}
playerPos.x = newX;
playerPos.y = newY;
}
renderBoard();
});
renderBoard();
</script>
</body>
</html>
div
元素作为游戏板。renderBoard
函数用于渲染游戏板。通过以上代码和解释,你可以快速上手实现一个简单的推箱子游戏。
领取专属 10元无门槛券
手把手带您无忧上云