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

79 lines
1.8 KiB
Java
Raw Normal View History

2022-11-17 16:20:15 +01:00
import javax.swing.JPanel;
import java.awt.*;
2022-11-18 10:05:14 +01:00
import java.util.Random;
2022-11-17 16:20:15 +01:00
import java.util.Timer;
2022-11-18 10:05:14 +01:00
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
2022-11-17 16:20:15 +01:00
public class SnakePanel extends JPanel {
private Cell[][] grid;
2022-11-18 10:05:14 +01:00
private ScheduledExecutorService gameRunner;
2022-11-17 16:20:15 +01:00
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]);
}
}
2022-11-18 10:05:14 +01:00
2022-11-17 16:20:15 +01:00
this.snake = new Snake(this);
addKeyListener(new SnakeListener(this));
2022-11-18 10:05:14 +01:00
gameRunner = Executors.newSingleThreadScheduledExecutor();
gameRunner.scheduleAtFixedRate(new Runnable() {
2022-11-17 16:20:15 +01:00
@Override
public void run() {
requestFocus();
snake.performMove();
}
2022-11-18 10:05:14 +01:00
}, 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;
}
}
2022-11-17 16:20:15 +01:00
}
public void gameOver() {
2022-11-18 10:05:14 +01:00
gameRunner.shutdown();
2022-11-17 16:20:15 +01:00
Timer gameOverTimer = new Timer();
gameOverTimer.scheduleAtFixedRate(new GameOverTask(this, gameOverTimer), 0, 60);
}
public Cell[][] getGrid() {
return grid;
}
public Snake getSnake() {
return snake;
}
}