我是JavaScript的新手,并试图构建一个Snake风格的游戏。我在间隔更新函数中有一个条件语句,检查蛇正在移动的方向,它调用Snake对象中的移动方法以保持其运行。最初,我直接在更新功能中使用了这个条件,它按预期工作 - 蛇一直移动直到它撞到墙壁,它会停下来等待不同的方向输入,它会接受并继续向不同的方向前进。
看起来像这样:
//before, with the checks being done in GamePlay.update()
var Snake = (() => {
let x = 10 * GameBoard.unit;
let y = 10 * GameBoard.unit;
let dir = "r";
let body = [];
body.unshift({x, y});
const moveRight = () => {
x = body[0].x + GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveLeft = () => {
x = body[0].x - GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveUp = () => {
y = body[0].y - GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveDown = () => {
y = body[0].y + GameBoard.unit;
body.unshift({x, y});
body.pop();
}
return {body, dir, moveLeft, moveRight, moveDown, moveUp};
})();
//inside IIFE called GamePlay
const update = () => {
if (Snake.dir == "l" && Snake.body[0].x >= GameBoard.LEFT_WALL){
Snake.moveLeft();
}
else if (Snake.dir == "u" && Snake.body[0].y >= GameBoard.TOP_WALL){
Snake.moveUp();
}
else if (Snake.dir == "r" && Snake.body[0].x <= GameBoard.RIGHT_WALL){
Snake.moveRight();
}
else if (Snake.dir == "d" && Snake.body[0].y <= GameBoard.BOTTOM_WALL){
Snake.moveDown();
}
}
为了将代码组织到适当的对象中,我尝试将条件移动移动到Snake对象中,将其放入名为 movement()的方法中,该方法将从 update()功能,如下所示:
//after, update conditionals moved from GamePlay.update() to Snake.movement()
var Snake = (() => {
let x = 10 * GameBoard.unit;
let y = 10 * GameBoard.unit;
let dir = "r";
let body = [];
body.unshift({x, y});
const moveRight = () => {
console.log("in moveRight");
x = body[0].x + GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveLeft = () => {
x = body[0].x - GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveUp = () => {
y = body[0].y - GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const moveDown = () => {
y = body[0].y + GameBoard.unit;
body.unshift({x, y});
body.pop();
}
const movement = () => {
console.log("called");
if (dir == "l" && body[0].x >= GameBoard.LEFT_WALL){
console.log("in l");
moveLeft();
}
else if (dir == "u" && body[0].y >= GameBoard.TOP_WALL){
console.log("in u");
moveUp();
}
else if (dir == "r" && body[0].x <= GameBoard.RIGHT_WALL){
console.log("in r");
moveRight();
}
else if (dir == "d" && body[0].y <= GameBoard.BOTTOM_WALL){
console.log("in d");
moveDown();
}
}
const alive = () => {
return true;
}
return {body, dir, movement};
})();
// ... in GamePlay
const update = () => {
Snake.movement();
}
然而,这导致在Snake进入右侧墙壁后它的运动停止运转(它在启动时的初始运动是向右的)。在碰到墙之前, console.log(“被叫”)和 console.log(“在r”中)按预期输出,但在击中墙后只有“被叫”日志继续,而“在r中”停止,如果 body [0] .x 大于 GameBoard.RIGHT_WALL ,这将有意义。然后蛇停止接受任何输入,并且不会向上或向下移动,这不应受 body [0] .x 过大的影响。
我的困惑来自这样一个事实,即两种情况下的行为不同,当它是相同的条件代码时,只是重构为一个对象方法,以及为什么当它在外面继续这样做时,它会停止接受方向输入宾语。