APL/DEV 3.2/TP05/Serpent/Snake.java
2022-11-17 16:20:15 +01:00

80 lines
1.7 KiB
Java

import java.awt.event.KeyEvent;
import java.util.LinkedList;
public class Snake {
private int headX;
private int headY;
private Cell[][] grid;
LinkedList<Cell> snakeCells;
private int length;
private SnakePanel parent;
private int direction = KeyEvent.VK_RIGHT;
public Snake(SnakePanel parent) {
this.parent = parent;
this.grid = parent.getGrid();
length = 3;
headX = parent.sizeX / 2;
headY = parent.sizeY / 2;
snakeCells = new LinkedList<Cell>();
grid[headY][headX].setType(CellType.SNAKE);
snakeCells.addFirst(grid[headX][headY]);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public void performMove() {
switch (direction) {
case (KeyEvent.VK_RIGHT):
headX++;
break;
case (KeyEvent.VK_LEFT):
headX--;
break;
case (KeyEvent.VK_UP):
headY--;
break;
case (KeyEvent.VK_DOWN):
headY++;
break;
}
if (headY >= parent.sizeY || headX >= parent.sizeX) {
parent.gameOver();
return;
}
Cell newCell = grid[headY][headX];
if (newCell == null || newCell.getType() == CellType.SNAKE) {
parent.gameOver();
return;
}
snakeCells.addFirst(newCell);
newCell.setType(CellType.SNAKE);
newCell.repaint();
if (snakeCells.size() > length) {
Cell c = snakeCells.removeLast();
c.setType(CellType.EMPTY);
c.repaint();
}
}
}