您如何在Java蛇游戏中动态更新蛇?

时间:2018-10-08 08:00:00

标签: javascript

我不确定是否已经被询问过,但是我的代码与通常的蛇代码有些不同。我基本上已经有一些工作了,

  • 生成并渲染木板
  • 蛇运动(没有进食和死亡)
  • 在棋盘内随机生成水果
  • 被吃掉后再随机产生一个水果

我现在的问题是,每次吃水果时,使蛇更新并在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;
}

我在这里迷失了两件事:

  • 如何更新蛇形阵列?您是否只是简单地获取了当前的x,y索引并将它们都减少了1? { 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;
    }
    

如果我开始考虑隔离墙,这也是一种类似的方法吗?这是我到目前为止的屏幕截图:

enter image description here

0 个答案:

没有答案