import java.awt.event.KeyEvent; import java.util.LinkedList; public class Snake { private int headX; private int headY; private Cell[][] grid; LinkedList 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(); 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 (headX < 0 || headY < 0 || headY >= parent.sizeY || headX >= parent.sizeX) { parent.gameOver(); return; } Cell newCell = grid[headY][headX]; if (newCell == null || newCell.getType() == CellType.SNAKE) { parent.gameOver(); return; } else if (newCell.getType() == CellType.FRUIT) { length++; parent.makeFruit(); } snakeCells.addFirst(newCell); newCell.setType(CellType.SNAKE); newCell.repaint(); if (snakeCells.size() > length) { Cell c = snakeCells.removeLast(); c.setType(CellType.EMPTY); c.repaint(); } } }