import javax.swing.JPanel; import java.awt.*; import java.util.Random; import java.util.Timer; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class SnakePanel extends JPanel { private Cell[][] grid; private ScheduledExecutorService gameRunner; private Snake snake; public final int sizeX = 25; public final int sizeY = 25; public SnakePanel() { super(); grid = new Cell[sizeX][sizeY]; setLayout(new GridLayout(sizeY, sizeX)); for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { grid[x][y] = new Cell(); add(grid[x][y]); } } this.snake = new Snake(this); addKeyListener(new SnakeListener(this)); gameRunner = Executors.newSingleThreadScheduledExecutor(); gameRunner.scheduleAtFixedRate(new Runnable() { @Override public void run() { requestFocus(); snake.performMove(); } }, 0, 300, TimeUnit.MILLISECONDS); makeFruit(); } public void makeFruit() { Random r = new Random(); while (true) { int x, y; x = r.nextInt(sizeX); y = r.nextInt(sizeY); if (grid[x][y].getType() == CellType.EMPTY) { grid[x][y].setType(CellType.FRUIT); repaint(); return; } } } public void gameOver() { gameRunner.shutdown(); Timer gameOverTimer = new Timer(); gameOverTimer.scheduleAtFixedRate(new GameOverTask(this, gameOverTimer), 0, 60); } public Cell[][] getGrid() { return grid; } public Snake getSnake() { return snake; } }