APL/DEV 3.2/TP05/Serpent/SnakePanel.java

59 lines
1.3 KiB
Java
Raw Normal View History

2022-11-17 16:20:15 +01:00
import javax.swing.JPanel;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;
public class SnakePanel extends JPanel {
private Cell[][] grid;
private Timer moveTimer;
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]);
}
}
int i = 0;
this.snake = new Snake(this);
addKeyListener(new SnakeListener(this));
moveTimer = new Timer();
moveTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
requestFocus();
snake.performMove();
}
}, 200, 200);
}
public void gameOver() {
moveTimer.cancel();
Timer gameOverTimer = new Timer();
gameOverTimer.scheduleAtFixedRate(new GameOverTask(this, gameOverTimer), 0, 60);
}
public Cell[][] getGrid() {
return grid;
}
public Snake getSnake() {
return snake;
}
}