Snake/Java: Difference between revisions

2,245 bytes removed ,  1 year ago
no edit summary
m (→‎Code: small changes)
No edit summary
 
(13 intermediate revisions by 7 users not shown)
Line 1:
An good Snake Game by IZzSaken
==Code==
 
{{works with|Java|8}}
edited on 21th May 2023
<lang java>import java.awt.*;
 
import java.awt.*;
import java.awt.event.*;
import static java.lang.String.format;
import java.util.*;
import java.util.List;
import javax.swing.*;
 
public class SnakeSnakeGame extends JPanel implements RunnableActionListener {
private static final Randomint randWIDTH = new Random()300;
private static final int[][] dirsHEIGHT = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}300;
private static final int WALLUNIT_SIZE = -110;
private static final int GAME_UNITS = (WIDTH * HEIGHT) / (UNIT_SIZE * UNIT_SIZE);
private static final int DELAY = 75;
 
private final int[] x = new int[GAME_UNITS];
volatile boolean gameOver = true;
private final int[] y = new int[GAME_UNITS];
private int bodyParts = 6;
private int applesEaten;
private int appleX;
private int appleY;
private char direction = 'R';
private boolean running = false;
private Timer timer;
 
Threadpublic gameThread;SnakeGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
int score, hiScore;
setBackground(Color.BLACK);
int nRows = 44;
int nCols = 64 setFocusable(true);
addKeyListener(new MyKeyAdapter());
int dir;
int energy startGame();
}
 
private void startGame() {
int[][] grid;
newApple();
List<Point> snake, treats;
Font smallFont running = true;
timer = new Timer(DELAY, this);
timer.start();
}
 
@Override
public Snake() {
public void paintComponent(Graphics g) {
setPreferredSize(new Dimension(640, 440));
setBackground(Colorsuper.whitepaintComponent(g);
setFontdraw(new Font("SansSerif", Font.BOLD, 48)g);
}
setFocusable(true);
 
private void draw(Graphics g) {
smallFont = getFont().deriveFont(Font.BOLD, 18);
initGridif (running); {
g.setColor(Color.RED);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
 
for (int i = 0; i < bodyParts; i++) {
addMouseListener(new MouseAdapter() {
@Override if (i == 0) {
public void mousePressed(MouseEvent e) { g.setColor(Color.GREEN);
if g.fillRect(gameOver)x[i], {y[i], UNIT_SIZE, UNIT_SIZE);
} else startNewGame();{
repaintg.setColor(new Color(45, 180, 0));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
});
 
g.setColor(Color.WHITE);
addKeyListener(new KeyAdapter() {
g.setFont(new Font("Arial", Font.BOLD, 14));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten, (WIDTH - metrics.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize());
} else {
gameOver(g);
}
}
 
private void newApple() {
@Override
appleX = (int) (Math.random() * (WIDTH / UNIT_SIZE)) * UNIT_SIZE;
public void keyPressed(KeyEvent e) {
appleY = (int) (Math.random() * (HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
 
switch (e.getKeyCode()) {
 
case KeyEvent.VK_UP:
if (dir != 2)
dir = 0;
break;
 
case KeyEvent.VK_LEFT:
if (dir != 1)
dir = 3;
break;
 
case KeyEvent.VK_RIGHT:
if (dir != 3)
dir = 1;
break;
 
case KeyEvent.VK_DOWN:
if (dir != 0)
dir = 2;
break;
}
repaint();
}
});
}
 
private void startNewGamemove() {
gameOverfor (int i = falsebodyParts; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
 
stopswitch (direction); {
initGrid(); case 'U':
y[0] = y[0] - UNIT_SIZE;
 
dir = 3 break;
energy = 1500; case 'D':
y[0] = y[0] + UNIT_SIZE;
 
if (score > hiScore) break;
hiScorecase = score;'L':
score x[0] = x[0] - UNIT_SIZE;
break;
 
treats = new LinkedList<>(); case 'R':
snake x[0] = newx[0] + ArrayList<>()UNIT_SIZE;
for (int x = 0; x < 7 break; x++)
}
snake.add(new Point(nCols / 2 + x, nRows / 2));
 
(gameThread = new Thread(this)).start();
}
 
private void stopcheckApple() {
if (gameThread(x[0] !== appleX) && (y[0] == nullappleY)) {
Thread tmp = gameThreadbodyParts++;
gameThread = nullapplesEaten++;
tmp.interruptnewApple();
}
}
 
private void initGridcheckCollisions() {
grid// =Check newif int[nRows][nCols];head collides with body
for (int ri = 0bodyParts; ri <> nRows0; r++i--) {
forif (int c(x[0] == 0;x[i]) c&& <(y[0] nCols;== c++y[i])) {
if (crunning == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)false;
grid[r][c] = WALL;
}
}
}
 
// Check if head touches left border
@Override
public void run if (x[0] < 0) {
running = false;
}
 
// Check if head touches right border
while (Thread.currentThread() == gameThread) {
if (x[0] >= WIDTH) {
running = false;
}
 
// Check if head trytouches {top border
if Thread.sleep(Math.max(75y[0] -< score,0) 25));{
}running catch= (InterruptedException e) {false;
return;}
}
 
// Check if head energytouches -=bottom 10;border
if (energyy[0] <>= 0HEIGHT) {
running = gameOver()false;
 
else if (hitsWall())
gameOver();
 
else if (hitsSnake())
gameOver();
 
else if (eatsTreat()) {
score++;
energy = 1500;
growSnake();
}
 
if (!gameOver) {
moveSnake();
addTreat();
}
repaint();
}
}
 
void gameOver if (!running) {
gameOver = true timer.stop();
stop();
}
 
void drawGrid(Graphics2D g) {
g.setColor(Color.lightGray);
for (int r = 0; r < nRows; r++) {
for (int c = 0; c < nCols; c++) {
if (grid[r][c] == WALL)
g.fillRect(c * 10, r * 10, 10, 10);
}
}
}
 
private void drawSnakegameOver(Graphics2DGraphics g) {
g.setColor(Color.blueWHITE);
forg.setFont(new Font(Point"Arial", pFont.BOLD, : snake20));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.fillRect(p.x * 10, p.y * 10, 10, 10);
g.drawString("Game Over", (WIDTH - metrics1.stringWidth("Game Over")) / 2, HEIGHT / 2);
 
g.setColor(energy < 500 ? Color.red : Color.orangeWHITE);
Pointg.setFont(new headFont("Arial", = snakeFont.get(0BOLD, 14));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.fillRect(head.x * 10, head.y * 10, 10, 10);
g.drawString("Score: " + applesEaten, (WIDTH - metrics2.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize());
}
 
void drawTreats(Graphics2D g) {
g.setColor(Color.green);
for (Point p : treats)
g.fillRect(p.x * 10, p.y * 10, 10, 10);
}
 
void drawStartScreen(Graphics2D g) {
g.setColor(Color.blue);
g.setFont(getFont());
g.drawString("Snake", 240, 190);
g.setColor(Color.orange);
g.setFont(smallFont);
g.drawString("(click to start)", 250, 240);
}
 
void drawScore(Graphics2D g) {
int h = getHeight();
g.setFont(smallFont);
g.setColor(getForeground());
String s = format("hiscore %d score %d", hiScore, score);
g.drawString(s, 30, h - 30);
g.drawString(format("energy %d", energy), getWidth() - 150, h - 30);
}
 
@Override
public void paintComponentactionPerformed(GraphicsActionEvent gge) {
super.paintComponentif (ggrunning); {
Graphics2D g = move(Graphics2D) gg;
checkApple();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ONcheckCollisions();
 
drawGrid(g);
 
if (gameOver) {
drawStartScreen(g);
} else {
drawSnake(g);
drawTreats(g);
drawScore(g);
}
repaint();
}
 
private class MyKeyAdapter extends KeyAdapter {
void moveSnake() {
@Override
for (int i = snake.size() - 1; i > 0; i--) {
public void Point p1 = snake.getkeyPressed(iKeyEvent -e) 1);{
Pointswitch p2 = snake(e.getgetKeyCode(i);) {
p2.x = p1 case KeyEvent.x;VK_LEFT:
p2.y if (direction != p1.y;'R') {
direction = 'L';
}
Point head = snake.get(0);
head.x += dirs[dir][0];
head.y += dirs[dir][1];
}
 
void growSnake() {
Point tail = snake.get(snake.size() - 1);
int x = tail.x + dirs[dir][0];
int y = tail.y + dirs[dir][1];
snake.add(new Point(x, y));
}
 
void addTreat() {
if (treats.size() < 3) {
 
if (rand.nextInt(10) == 0) { // 1 in 10
 
if (rand.nextInt(4) != 0) { // 3 in 4
int x, y;
while (true) {
 
x = rand.nextInt(nCols);
y = rand.nextInt(nRows);
if (grid[y][x] != 0)
continue;
 
Point p = new Point(x, y);
if (snake.contains(p) || treats.contains(p))
continue;
 
treats.add(p);
break;
}
} else if (treats.size() > 1)break;
case treatsKeyEvent.remove(0);VK_RIGHT:
if (direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if (direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if (direction != 'U') {
direction = 'D';
}
break;
}
}
}
 
boolean hitsWall() {
Point head = snake.get(0);
int nextCol = head.x + dirs[dir][0];
int nextRow = head.y + dirs[dir][1];
return grid[nextRow][nextCol] == WALL;
}
 
boolean hitsSnake() {
Point head = snake.get(0);
int nextCol = head.x + dirs[dir][0];
int nextRow = head.y + dirs[dir][1];
for (Point p : snake)
if (p.x == nextCol && p.y == nextRow)
return true;
return false;
}
 
boolean eatsTreat() {
Point head = snake.get(0);
int nextCol = head.x + dirs[dir][0];
int nextRow = head.y + dirs[dir][1];
for (Point p : treats)
if (p.x == nextCol && p.y == nextRow) {
treats.remove(p);
return true;
}
return false;
}
 
public static void main(String[] args) {
JFrame frame = new JFrame("Snake Game");
SwingUtilities.invokeLater(() -> {
SnakeGame JFrame fgame = new JFrameSnakeGame();
frame.add(game);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Snake");
fframe.setResizable(false);
fframe.addpack(new Snake(), BorderLayout.CENTER);
fframe.packsetLocationRelativeTo(null);
fframe.setLocationRelativeTosetVisible(nulltrue);
f.setVisible(true);
});
}
}
}</lang>
3

edits