Snake Terminé

This commit is contained in:
HORVILLE 2022-11-18 10:05:14 +01:00
parent 43627048d8
commit b7f44474fc
3 changed files with 32 additions and 10 deletions

View File

@ -1,6 +1,4 @@
import javax.swing.*;
import java.awt.*;
public class Main {

View File

@ -55,15 +55,19 @@ public class Snake {
break;
}
if (headY >= parent.sizeY || headX >= parent.sizeX) {
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);

View File

@ -1,12 +1,15 @@
import javax.swing.JPanel;
import java.awt.*;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class SnakePanel extends JPanel {
private Cell[][] grid;
private Timer moveTimer;
private ScheduledExecutorService gameRunner;
private Snake snake;
public final int sizeX = 25;
@ -25,12 +28,12 @@ public class SnakePanel extends JPanel {
add(grid[x][y]);
}
}
int i = 0;
this.snake = new Snake(this);
addKeyListener(new SnakeListener(this));
moveTimer = new Timer();
moveTimer.scheduleAtFixedRate(new TimerTask() {
gameRunner = Executors.newSingleThreadScheduledExecutor();
gameRunner.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
@ -38,11 +41,28 @@ public class SnakePanel extends JPanel {
snake.performMove();
}
}, 200, 200);
}, 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() {
moveTimer.cancel();
gameRunner.shutdown();
Timer gameOverTimer = new Timer();
gameOverTimer.scheduleAtFixedRate(new GameOverTask(this, gameOverTimer), 0, 60);