推箱子js代码
时间: 2023-08-13 12:06:24 浏览: 62
以下是一个简单的推箱子游戏的JavaScript代码:
```javascript
var box = document.getElementById("box"); // 获取箱子元素
var player = document.getElementById("player"); // 获取玩家元素
var boxes = document.getElementsByClassName("box"); // 获取所有箱子元素
var goals = document.getElementsByClassName("goal"); // 获取所有目标元素
// 定义玩家的初始位置
var playerRow = 2;
var playerCol = 2;
// 定义箱子的初始位置
var boxRows = [2, 3, 4];
var boxCols = [3, 4, 4];
// 将箱子放置到初始位置
for (var i = 0; i < boxes.length; i++) {
boxes[i].style.top = boxRows[i] * 50 + "px";
boxes[i].style.left = boxCols[i] * 50 + "px";
}
// 将目标放置到指定位置
for (var i = 0; i < goals.length; i++) {
goals[i].style.top = (i + 1) * 50 + "px";
goals[i].style.left = (i + 5) * 50 + "px";
}
// 监听键盘事件
document.addEventListener("keydown", function (event) {
if (event.key === "ArrowUp") {
move(-1, 0);
} else if (event.key === "ArrowDown") {
move(1, 0);
} else if (event.key === "ArrowLeft") {
move(0, -1);
} else if (event.key === "ArrowRight") {
move(0, 1);
}
});
function move(rowOffset, colOffset) {
var newRow = playerRow + rowOffset;
var newCol = playerCol + colOffset;
// 碰撞检测
var collision = false;
for (var i = 0; i < boxes.length; i++) {
if (boxRows[i] === newRow && boxCols[i] === newCol) {
collision = true;
var newBoxRow = boxRows[i] + rowOffset;
var newBoxCol = boxCols[i] + colOffset;
for (var j = 0; j < boxes.length; j++) {
if (j !== i && boxRows[j] === newBoxRow && boxCols[j] === newBoxCol) {
collision = true;
break;
}
}
if (!collision) {
boxes[i].style.top = newBoxRow * 50 + "px";
boxes[i].style.left = newBoxCol * 50 + "px";
boxRows[i] = newBoxRow;
boxCols[i] = newBoxCol;
} else {
return;
}
}
}
// 移动玩家
if (newRow >= 0 && newRow < 7 && newCol >= 0 && newCol < 10 && !collision) {
player.style.top = newRow * 50 + "px";
player.style.left = newCol * 50 + "px";
playerRow = newRow;
playerCol = newCol;
}
// 判断是否完成游戏
var completed = true;
for (var i = 0; i < boxes.length; i++) {
var inGoal = false;
for (var j = 0; j < goals.length; j++) {
if (boxRows[i] === parseInt(goals[j].style.top) / 50 && boxCols[i] === parseInt(goals[j].style.left) / 50) {
inGoal = true;
break;
}
}
if (!inGoal) {
completed = false;
break;
}
}
if (completed) {
alert("恭喜你完成游戏!");
}
}
```
这段代码实现了一个简单的推箱子游戏,可以使用HTML和CSS来创建游戏界面。该代码监听键盘事件,根据玩家的输入移动箱子和玩家,并检测是否完成游戏。
阅读全文