Skip to content

chore(game): fix collision test and AI snakes

scyzw14 requested to merge dev-game into master

https://csprojects.nottingham.edu.cn/scyzw14/snake/-/issues/28 https://csprojects.nottingham.edu.cn/scyzw14/snake/-/issues/25

We need 2 getFacingBlock methods: getFacingBlock and getFacingBlockAfterAction instead of only the original getFacingBlock. Otherwise the collision detection will use the current moving direction instead of the next moving direction.

private SnakeGameLevel.Direction getNextHeadDirection(SnakeGameLevel.Action action) {
  if (action == null) return this.headDirection;
  return switch (action) {
      case LEFT -> switch (this.headDirection) {
          case PosX -> SnakeGameLevel.Direction.PosZ;
          case NegX -> SnakeGameLevel.Direction.NegZ;
          case PosZ -> SnakeGameLevel.Direction.NegX;
          case NegZ -> SnakeGameLevel.Direction.PosX;
      };
      case RIGHT -> switch (this.headDirection) {
          case PosX -> SnakeGameLevel.Direction.NegZ;
          case NegX -> SnakeGameLevel.Direction.PosZ;
          case PosZ -> SnakeGameLevel.Direction.PosX;
          case NegZ -> SnakeGameLevel.Direction.NegX;
      };
  };
}

private SnakeGameLevel.Direction getNextHeadDirection() {
  return getNextHeadDirection(this.nextAction);
}

private void updateHeadDirection(SnakeGameLevel.Action action) {
  this.headDirection = getNextHeadDirection(action);
}

private static BlockPosition getFacingBlock(BlockPosition head, SnakeGameLevel.Direction direction) {
  return switch (direction) {
      case PosX -> new BlockPosition(head.x() + 1, head.y(), head.z());
      case NegX -> new BlockPosition(head.x() - 1, head.y(), head.z());
      case PosZ -> new BlockPosition(head.x(), head.y(), head.z() + 1);
      case NegZ -> new BlockPosition(head.x(), head.y(), head.z() - 1);
  };
}

public BlockPosition getFacingBlock() {
  return getFacingBlock(this.getHead().position, this.headDirection);
}

public BlockPosition getFacingBlockAfterAction() {
  return getFacingBlock(this.getHead().position, this.getNextHeadDirection());
}

Merge request reports