我不确定是否已经被询问过,但是我的代码与通常的蛇代码有些不同。我基本上已经有一些工作了,
我现在的问题是,每次吃水果时,使蛇更新并在tick()中重新渲染。
/**
* @returns {TickReturn}
*/
tick() {
// very simple movement code which assumes a single length snake
// no eating or dieing implemented yet.
let oldPosition = { ...this._snake[0]
};
switch (this._direction) {
case Direction.Up:
this._snake[0].y -= 1;
break;
case Direction.Down:
this._snake[0].y += 1;
break;
case Direction.Left:
this._snake[0].x -= 1;
break;
case Direction.Right:
this._snake[0].x += 1;
break;
}
if (this.eating(this._fruit)) {
this._fruit = this.nextFruitFn(); // update the position of the fruit
this.update(); // nothing's being done yet
}
return {
gameOver: this._isGameOver,
eating: false, // currently static, not doing anything yet
changes: [{
position: oldPosition,
tileValue: Tiles.Empty
},
{
position: this._snake[0],
tileValue: Tiles.Snake
},
{
position: this._fruit,
tileValue: Tiles.Fruit
}
]
};
}
eating(pos) {
let hasEaten = false;
this._snake.map((s, idx) => {
// if snake and position merged indices,
// then fruit has been eaten
hasEaten = (s.y === pos.y && s.x === pos.x) ? true : false;
if (hasEaten) {
this._board[pos.x][pos.y] = Tiles.Empty;
// make sure to clear the tile after eating
}
});
return hasEaten;
}
我在这里迷失了两件事:
{ y: y-1, x: x-1 }
?TickReturn
对象中正确呈现它?当前,它只是在某个位置更新this._snake[0]
。如何更新将包含蛇的后续部分的开关盒?目前,它只能固定在index 0
上移动,就像这样:
switch (this._direction) {
case Direction.Up:
this._snake[0].y -= 1;
break;
case Direction.Down:
this._snake[0].y += 1;
break;
case Direction.Left:
this._snake[0].x -= 1;
break;
case Direction.Right:
this._snake[0].x += 1;
break;
}
如果我开始考虑隔离墙,这也是一种类似的方法吗?这是我到目前为止的屏幕截图: