Пример #1
0
 /*
  * When the snake eat a fruti its size must be increased by 1 piece. This piece is added in the
  * middle so the tail should shift by a position. The direction of this shift depends on the
  * current direction of the tail
  */
 public void eat() {
   // add a new piece to the snake
   SnakeTail tail = (SnakeTail) parts.get(parts.size() - 1);
   parts.add(parts.size() - 1, new SnakeBody(tail.getX(), tail.getY(), tail.direction));
   // shift the tail by 1 position with a direction that depends on its current position.
   switch (tail.direction) {
     case UP:
       tail.moveDown();
       break;
     case DOWN:
       tail.moveUp();
       break;
     case LEFT:
       tail.moveRight();
       break;
     case RIGHT:
       tail.moveLeft();
       break;
   }
 }
Пример #2
0
  /*
   * Advance the snake on the grid by a position that depends on the current snake direction.
   */
  public void advance() {
    int last = parts.size() - 1;
    SnakeHead head = (SnakeHead) parts.get(0);
    SnakeBody neck = parts.get(1);
    SnakeTail tail = (SnakeTail) parts.get(last);

    // move all the snake pieces but head, one step forward
    for (int i = last; i > 0; i--) {
      SnakeBody before = parts.get(i - 1);
      SnakeBody part = parts.get(i);
      part.setX(before.getX());
      part.setY(before.getY());
      part.direction = before.direction;
    }

    // move the head towards the snake direction.
    head.direction = direction;
    switch (direction) {
      case UP:
        head.moveUp();
        break;
      case LEFT:
        head.moveLeft();
        break;
      case DOWN:
        head.moveDown();
        break;
      case RIGHT:
        head.moveRight();
        break;
    }

    // determine the neck direction
    switch (neckDirection) {
      case UP_RIGHT:
      case LEFT_UP:
      case DOWN_LEFT:
      case RIGHT_DOWN:
      case LEFT_DOWN:
      case UP_LEFT:
      case DOWN_RIGHT:
      case RIGHT_UP:
        neck.direction = neckDirection;
        neckDirection = Direction.UP;
        break;
    }

    // determine the tail direction
    switch (tail.direction) {
      case DOWN_LEFT:
      case UP_LEFT:
        tail.direction = Direction.LEFT;
        break;
      case LEFT_UP:
      case RIGHT_UP:
        tail.direction = Direction.UP;
        break;
      case RIGHT_DOWN:
      case LEFT_DOWN:
        tail.direction = Direction.DOWN;
        break;
      case UP_RIGHT:
      case DOWN_RIGHT:
        tail.direction = Direction.RIGHT;
        break;
    }
  }