好吧,我正在尝试使用基本导入来做一个贪吃蛇游戏,但有时我被卡住了,因为 javascript 分配。
我将 oldSnake 的值指定为蛇在更改之前的值。
但是当我进入 forEach 时,已经分配的值发生了变化,我不知道为什么。
在进入 forEach 之前
进入forEach之后
我搜索了一下,没有找到任何地方,有人知道发生了什么吗?
import { snake } from "/snake.js";
let lastDirection = {y: 1, x:0};
export function updateGame(direction){
let oldSnake = snake;
if (!(direction.y == 0 && direction.x == 0)){
if((lastDirection.y == 1 && direction.y == -1 || lastDirection.y == -1 && direction.y == 1)
||(lastDirection.x == 1 && direction.x == -1 || lastDirection.x == -1 && direction.x == 1)){
direction = lastDirection;
}
snake.forEach((snakeSlice, index)=>{
lastDirection = direction;
if (index === 0){
snakeSlice.ypos+= direction.y;
snakeSlice.xpos+= direction.x;
}
else{
snakeSlice.ypos = oldSnake[index-1].ypos;
snakeSlice.xpos = oldSnake[index-1].xpos;
}
});
}
}