用JavaScript写一个推箱子游戏
时间: 2023-07-01 22:05:23 浏览: 168
好的,下面是一个简单的推箱子游戏的 JavaScript 代码,可以在浏览器中运行:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>推箱子游戏</title>
<style>
table {
border-collapse: collapse;
}
td {
width: 50px;
height: 50px;
text-align: center;
vertical-align: middle;
border: 1px solid black;
}
td.player {
background-color: orange;
}
td.box {
background-color: yellow;
}
td.target {
background-color: green;
}
</style>
</head>
<body>
<table id="gameTable"></table>
<script>
const ROWS = 5;
const COLS = 5;
const map = [
[2, 2, 2, 2, 2],
[2, 0, 1, 0, 2],
[2, 0, 3, 0, 2],
[2, 0, 0, 0, 2],
[2, 2, 2, 2, 2]
];
let playerPos = {row: 1, col: 2};
let boxPos = {row: 2, col: 2};
function render() {
let table = document.getElementById("gameTable");
table.innerHTML = "";
for (let i = 0; i < ROWS; i++) {
let row = document.createElement("tr");
for (let j = 0; j < COLS; j++) {
let cell = document.createElement("td");
if (map[i][j] === 0) {
cell.onclick = function() {
movePlayer(i, j);
};
}
if (i === playerPos.row && j === playerPos.col) {
cell.classList.add("player");
} else if (i === boxPos.row && j === boxPos.col) {
cell.classList.add("box");
} else if (map[i][j] === 3) {
cell.classList.add("target");
}
row.appendChild(cell);
}
table.appendChild(row);
}
}
function movePlayer(row, col) {
let newRow = playerPos.row + row;
let newCol = playerPos.col + col;
if (map[newRow][newCol] === 0) {
playerPos.row = newRow;
playerPos.col = newCol;
} else if (map[newRow][newCol] === 3) {
playerPos.row = newRow;
playerPos.col = newCol;
alert("恭喜你,游戏通关!");
return;
} else if (map[newRow][newCol] === 2) {
return;
} else if (newRow === boxPos.row && newCol === boxPos.col) {
let newBoxRow = boxPos.row + row;
let newBoxCol = boxPos.col + col;
if (map[newBoxRow][newBoxCol] === 0) {
playerPos.row = newRow;
playerPos.col = newCol;
boxPos.row = newBoxRow;
boxPos.col = newBoxCol;
} else if (map[newBoxRow][newBoxCol] === 3) {
playerPos.row = newRow;
playerPos.col = newCol;
boxPos.row = newBoxRow;
boxPos.col = newBoxCol;
alert("恭喜你,游戏通关!");
return;
} else if (map[newBoxRow][newBoxCol] === 2) {
return;
}
}
render();
}
render();
</script>
</body>
</html>
```
这个代码实现了一个简单的推箱子游戏,包括地图、玩家、箱子和目标点等元素的绘制,以及玩家移动和箱子推动等游戏逻辑的处理。可以在浏览器中打开这个 HTML 文件,就可以开始游戏了。
阅读全文