/** 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);
  }
  @Override
  public void draw(Canvas canvas) {

    // draw each part of the snake.
    for (int i = 0; i < numberOfParts; i++) {
      SnakePart part = snakeParts.get(i);
      part.draw(canvas);
    }
  }
  /**
   * 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;
  }
  /** 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;
    }
  }
Beispiel #5
0
 public void advance() {
   SnakePart head = parts.get(0);
   int len = parts.size() - 1;
   for (int i = len; i > 0; i--) {
     SnakePart before = parts.get(i - 1);
     SnakePart part = parts.get(i);
     part.x = before.x;
     part.y = before.y;
   }
   if (direction == UP) head.y -= 1;
   if (direction == LEFT) head.x -= 1;
   if (direction == DOWN) head.y += 1;
   if (direction == RIGHT) head.x += 1;
   if (head.x < 0) head.x = 9;
   if (head.x > 9) head.x = 0;
   if (head.y < 0) head.y = 12;
   if (head.y > 12) head.y = 0;
 }