我的蛇在视觉上正常移动,蛇在每个蜱上长得更长,因为它的痕迹仍然被画出来。我尝试过使用clearRect来清除蛇尾后面的细胞,但这很笨重,因为我必须考虑到蛇向哪个方向移动以知道要清除哪个细胞。我错过了什么吗?由于某种原因,我查找的大多数JS蛇代码都没有遇到这个问题。 (我不会在那些程序中看到clearRect)你怎么能在视觉上摆脱最后一次勾选的蛇痕?
相关代码:
const createSnake = () => {
const snakeLength = Settings.getSnakeLength();
for (let snakeIndex = 0; snakeIndex < snakeLength; snakeIndex++) {
snake.push({xPosition: Settings.getUnitSize() * 5 + snakeIndex * Settings.getUnitSize(),
yPosition: Settings.getUnitSize() * 5});
}
};
const drawSnake = () => {
for (let snakeIndex = 0; snakeIndex < snake.length; snakeIndex++) {
context.fillRect(snake[snakeIndex].xPosition,
snake[snakeIndex].yPosition,
Settings.getUnitSize(),
Settings.getUnitSize());
}
};
const moveSnake = () => {
let oldTailNewHead = snake[0];
let oldHead = snake[snake.length - 1];
if (_direction === "right") {
oldTailNewHead.xPosition = oldHead.xPosition + Settings.getUnitSize();
oldTailNewHead.yPosition = oldHead.yPosition;
} else if (_direction === "left") {
oldTailNewHead.xPosition = oldHead.xPosition - Settings.getUnitSize();
oldTailNewHead.yPosition = oldHead.yPosition;
} else if (_direction === "down") {
oldTailNewHead.xPosition = oldHead.xPosition;
oldTailNewHead.yPosition = oldHead.yPosition + Settings.getUnitSize();
} else if (_direction === "up") {
oldTailNewHead.xPosition = oldHead.xPosition;
oldTailNewHead.yPosition = oldHead.yPosition - Settings.getUnitSize();
}
snake.shift();
snake.push(oldTailNewHead);
if (context.fillStyle !== "#000000") {
context.fillStyle = "#000000";
}
context.fillRect(oldTailNewHead.xPosition,
oldTailNewHead.yPosition,
Settings.getUnitSize(),
Settings.getUnitSize());
// context.clearRect(snake[0].xPosition - Settings.getUnitSize(),
// snake[0].yPosition,
// Settings.getUnitSize(),
// Settings.getUnitSize());
};
createSnake和drawSnake被调用一次以初始化蛇。每隔几百毫秒使用setInterval调用moveSnake。我暂时注释掉了clearRect部分,因为它只有在蛇的后部向右移动时才有效。 (可以预见,因为直接我清理直接在尾部左侧)。