推箱子(Sokoban)是一款经典的益智游戏,玩家需要通过移动箱子到指定位置来通关。下面是一个简单的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>
.game-board {
display: grid;
grid-template-columns: repeat(8, 50px);
grid-gap: 2px;
}
.cell {
width: 50px;
height: 50px;
background-color: #ddd;
display: flex;
align-items: center;
justify-content: center;
}
.wall {
background-color: #333;
}
.player {
background-color: blue;
}
.box {
background-color: red;
}
.target {
background-color: green;
}
</style>
</head>
<body>
<div id="game-board" class="game-board"></div>
<script src="game.js"></script>
</body>
</html>
const board = [
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 2, 0, 0, 3, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1]
];
let playerPos = { x: 2, y: 2 };
function renderBoard() {
const gameBoard = document.getElementById('game-board');
gameBoard.innerHTML = '';
board.forEach((row, y) => {
row.forEach((cell, x) => {
const div = document.createElement('div');
div.classList.add('cell');
switch (cell) {
case 1:
div.classList.add('wall');
break;
case 2:
div.classList.add('player');
break;
case 3:
div.classList.add('box');
break;
case 4:
div.classList.add('target');
break;
}
gameBoard.appendChild(div);
});
});
}
document.addEventListener('keydown', (e) => {
let newX = playerPos.x;
let newY = playerPos.y;
switch (e.key) {
case 'ArrowUp':
newY -= 1;
break;
case 'ArrowDown':
newY += 1;
break;
case 'ArrowLeft':
newX -= 1;
break;
case 'ArrowRight':
newX += 1;
break;
}
if (board[newY][newX] === 1) return; // Hit a wall
if (board[newY][newX] === 3) {
const nextX = newX + (newX > playerPos.x ? 1 : newX < playerPos.x ? -1 : 0);
const nextY = newY + (newY > playerPos.y ? 1 : newY < playerPos.y ? -1 : 0);
if (board[nextY][nextX] !== 0 && board[nextY][nextX] !== 4) return; // Hit another box or wall
board[newY][newX] = 0;
board[nextY][nextX] = 3;
}
board[playerPos.y][playerPos.x] = 0;
playerPos = { x: newX, y: newY };
board[playerPos.y][playerPos.x] = 2;
renderBoard();
});
renderBoard();
通过以上代码和解释,你可以创建一个基本的推箱子游戏,并了解其基础概念和相关问题解决方法。
领取专属 10元无门槛券
手把手带您无忧上云