Esempio n. 1
0
  /** Move the snake forward every update. */
  public void advance() {

    if (currentState == State.IDLE) {
      currentState = State.MOVING;
    }

    SnakePart head = snakeParts.get(0);

    int snakeLength = snakeParts.size() - 1;

    for (int i = snakeLength; i > 0; i--) {
      SnakePart previousPart = snakeParts.get(i - 1);
      SnakePart snakePart = snakeParts.get(i);
      // set the part's new position to the previous parts position.
      snakePart.setX(previousPart.getX());
      snakePart.setY(previousPart.getY());
    }

    switch (movementDirection) {
      case UP:
        head.setY(head.getY() - 1);
        break;
      case DOWN:
        head.setY(head.getY() + 1);
        break;
      case LEFT:
        head.setX(head.getX() - 1);
        break;
      case RIGHT:
        head.setX(head.getX() + 1);
        break;
    }
  }
Esempio n. 2
0
  /** Adds a new part to the end of the snake. */
  public void addPart() {

    numberOfParts++;

    SnakePart tailPart = snakeParts.get(snakeParts.size() - 1);
    SnakePart newTailPart = new SnakePart(tailPart.getX(), tailPart.getY(), snakeColor);
    snakeParts.add(newTailPart);
  }
Esempio n. 3
0
  /**
   * Checks whether any parts overlap.
   *
   * @return true if parts overlap, false otherwise.
   */
  public boolean checkGameOver() {

    int snakeLength = snakeParts.size();

    SnakePart head = snakeParts.get(0);

    for (int i = 1; i < snakeLength; i++) {
      SnakePart snakePart = snakeParts.get(i);
      if (head.getX() == snakePart.getX() && head.getY() == snakePart.getY()) {
        return true;
      }
    }

    // check boundary conditions
    if (head.getX() < 0 || head.getX() >= Utils.WORLD_WIDTH) {
      // check x coordinates.
      return true;
    } else if (head.getY() < 0 || head.getY() >= Utils.WORLD_HEIGHT) {
      // check y coordinates.
      return true;
    }

    return false;
  }