Snake/Java: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
No edit summary
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
An good Snake Game by IZzSaken
package zug;

edited on 21th May 2023


import javax.swing.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;


public class SnakeGame extends JPanel implements ActionListener {
import static java.lang.String.format;
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
private static final int UNIT_SIZE = 10;
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];
public class zug extends JPanel implements Runnable {
private final int[] y = new int[GAME_UNITS];
enum Dir {
private int bodyParts = 6;
up(0, -1), right(1, 0), down(0, 1), left(-1, 0);
private int applesEaten;
private int appleX;
private int appleY;
private char direction = 'R';
private boolean running = false;
private Timer timer;


Dir(int x, int y) {
public SnakeGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
this.x = x; this.y = y;
}
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(new MyKeyAdapter());
startGame();
}


private void startGame() {
final int x, y;
}
newApple();
running = true;
timer = new Timer(DELAY, this);
timer.start();
}


@Override
static final Random rand = new Random();
public void paintComponent(Graphics g) {
static final int WAND = -1;
super.paintComponent(g);
draw(g);
}


private void draw(Graphics g) {
volatile boolean gameOver = true;
if (running) {
g.setColor(Color.RED);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);


for (int i = 0; i < bodyParts; i++) {
Thread gameThread;
int score, highScore;
if (i == 0) {
int nRows = 108;
g.setColor(Color.GREEN);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
int nCols = 192;
Dir dir;

int[][] wand;
List<Point> zug, passagiere;
Font smallFont;

public zug() {
setPreferredSize(new Dimension(1920, 1080));
setBackground(Color.darkGray);
setFont(new Font("Arial", Font.BOLD, 48));
setFocusable(true);

smallFont = getFont().deriveFont(Font.BOLD, 18);
mauerErzeugen();

addMouseListener(
new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (gameOver) {

starteNeuesSpiel();
repaint();
}
}
});

addKeyListener(
new KeyAdapter() {

@Override
public void keyPressed(KeyEvent e) {

switch (e.getKeyCode()) {

case KeyEvent.VK_UP:
if (dir != Dir.down)
dir = Dir.up;
break;

case KeyEvent.VK_LEFT:
if (dir != Dir.right)
dir = Dir.left;
break;

case KeyEvent.VK_RIGHT:
if (dir != Dir.left)
dir = Dir.right;
break;

case KeyEvent.VK_DOWN:
if (dir != Dir.up)
dir = Dir.down;
break;
}
repaint();
}
});
}

public static void zeigeFenster(String text) {
JFrame fenster = new JFrame("Deutsche Bahn");
JLabel label = new JLabel(text);
fenster.getContentPane().add(label);
fenster.setSize(600, 200);
fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fenster.setVisible(true);
}

void starteNeuesSpiel() {
gameOver = false;

stop();
mauerErzeugen();
passagiere = new LinkedList<>();

dir = Dir.left;

if (score > highScore)
highScore = score;
score = 0;

zug = new ArrayList<>();
for (int x = 0; x < 7; x++)
zug.add(new Point(nCols / 2 + x, nRows / 2));

do
addPassagiere();
while(passagiere.isEmpty());

(gameThread = new Thread(this)).start();
}


void stop() {
if (gameThread != null) {
Thread tmp = gameThread;
gameThread = null;
tmp.interrupt();
}
}

void mauerErzeugen() {
wand = new int[nRows][nCols];
for (int r = 0; r < nRows; r++) {
for (int c = 0; c < nCols; c++) {
if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)
wand[r][c] = WAND;
}
}
}

@Override
public void run() {

while (Thread.currentThread() == gameThread) {

try {
Thread.sleep(Math.max(75 - score, 25));
} catch (InterruptedException e) {
return;
}

if (trifftWand() || trifftZug() || score == 15) {
gameOver();
} else {
} else {
if (sammeltPassagiereEin()) {
g.setColor(new Color(45, 180, 0));
score++;
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
verlängereZug();
}
bewegeZug();
addPassagiere();
}
}
repaint();
}
}
}


boolean trifftWand() {
g.setColor(Color.WHITE);
Point head = zug.get(0);
g.setFont(new Font("Arial", Font.BOLD, 14));
int nextCol = head.x + dir.x;
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten, (WIDTH - metrics.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize());
int nextRow = head.y + dir.y;
} else {
return wand [nextRow][nextCol] == WAND;
gameOver(g);
}
}
}

private void newApple() {
appleX = (int) (Math.random() * (WIDTH / UNIT_SIZE)) * UNIT_SIZE;
appleY = (int) (Math.random() * (HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
}


boolean trifftZug() {
private void move() {
Point head = zug.get(0);
for (int i = bodyParts; i > 0; i--) {
int nextCol = head.x + dir.x;
x[i] = x[i - 1];
int nextRow = head.y + dir.y;
y[i] = y[i - 1];
for (Point p : zug)
if (p.x == nextCol && p.y == nextRow)
return true;
return false;
}
}


boolean sammeltPassagiereEin() {
switch (direction) {
Point head = zug.get(0);
case 'U':
int nextCol = head.x + dir.x;
y[0] = y[0] - UNIT_SIZE;
int nextRow = head.y + dir.y;
break;
for (Point p : passagiere)
case 'D':
if (p.x == nextCol && p.y == nextRow) {
y[0] = y[0] + UNIT_SIZE;
return passagiere.remove(p);
break;
}
case 'L':
return false;
x[0] = x[0] - UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
}


void gameOver() {
private void checkApple() {
gameOver = true;
if ((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
zeigeFenster("Gut gemacht ! Der Code für die Bombe ist dein Score: "+score+ " " + "Suche nun nach 2 weiteren NFC Tags !");
stop();
applesEaten++;
newApple();
}
}
}


void bewegeZug() {
private void checkCollisions() {
// Check if head collides with body
for (int i = zug.size() - 1; i > 0; i--) {
Point p1 = zug.get(i - 1);
for (int i = bodyParts; i > 0; i--) {
Point p2 = zug.get(i);
if ((x[0] == x[i]) && (y[0] == y[i])) {
p2.x = p1.x;
running = false;
p2.y = p1.y;
}
}
Point head = zug.get(0);
head.x += dir.x;
head.y += dir.y;
}
}


// Check if head touches left border
void verlängereZug() {
Point tail = zug.get(zug.size() - 1);
if (x[0] < 0) {
int x = tail.x + dir.x;
running = false;
int y = tail.y + dir.y;
zug.add(new Point(x, y));
}
}


// Check if head touches right border
void addPassagiere() {
if (passagiere.size() < 10) {
if (x[0] >= WIDTH) {
running = false;

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 (wand[y][x] != 0)
continue;

Point p = new Point(x, y);
if (zug.contains(p) || passagiere.contains(p))
continue;

passagiere.add(p);
break;
}
} else if (passagiere.size() > 1)
passagiere.remove(0);
}
}
}
}


// Check if head touches top border
void zeichneWand(Graphics2D g) {
g.setColor(Color.black);
if (y[0] < 0) {
for (int r = 0; r < nRows; r++) {
running = false;
for (int c = 0; c < nCols; c++) {
if (wand[r][c] == WAND)
g.fillRect(c * 10, r * 10, 10, 10);
}
}
}
}


// Check if head touches bottom border
void zeichneZug(Graphics2D g) {
g.setColor(Color.red);
if (y[0] >= HEIGHT) {
for (Point p : zug)
running = false;
g.fillRect(p.x * 10, p.y * 10, 10, 10);


Point head = zug.get(0);
g.fillRect(head.x * 10, head.y * 10, 10, 10);
}
}


void zeichnePassagiere(Graphics2D g) {
if (!running) {
g.setColor(Color.pink);
timer.stop();
for (Point p : passagiere)
g.fillRect(p.x * 10, p.y * 10, 10, 10);
}
}
}


void zeichneStartbildschirm(Graphics2D g) {
private void gameOver(Graphics g) {
g.setColor(Color.white);
g.setColor(Color.WHITE);
g.setFont(getFont());
g.setFont(new Font("Arial", Font.BOLD, 20));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Sammle die Passagiere ein",650, 250);
g.drawString("Game Over", (WIDTH - metrics1.stringWidth("Game Over")) / 2, HEIGHT / 2);
g.setColor(Color.white);
g.setFont(smallFont);
g.drawString("Beliebige Maustaste zum Starten drücken", 780, 300);
}


g.setColor(Color.WHITE);
void zeichnePunktestand(Graphics2D g) {
g.setFont(new Font("Arial", Font.BOLD, 14));
int h = getHeight();
g.setFont(smallFont);
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten, (WIDTH - metrics2.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize());
g.setColor(Color.white);
}
String s = format("HighScore: %d Score: %d", highScore, score);
g.drawString(s, 30, h - 30);


@Override
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkApple();
checkCollisions();
}
}
repaint();
}


private class MyKeyAdapter extends KeyAdapter {

@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
public void keyPressed(KeyEvent e) {
Graphics2D g = (Graphics2D) gg;
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (direction != 'R') {
direction = 'L';

zeichneWand(g);
}
break;

if (gameOver) {
case KeyEvent.VK_RIGHT:
zeichneStartbildschirm(g);
if (direction != 'L') {
} else {
direction = 'R';
zeichneZug(g);
}
zeichnePassagiere(g);
break;
zeichnePunktestand(g);
case KeyEvent.VK_UP:
if (direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if (direction != 'U') {
direction = 'D';
}
break;
}
}
}
}

}
}


public static void main(String[] args) {

JFrame frame = new JFrame("Snake Game");

SnakeGame game = new SnakeGame();

frame.add(game);
public static void main(String[] args) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(
() -> {
frame.setResizable(false);
JFrame mainFrame = new JFrame();
frame.pack();
frame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle("Deutsche Bahn");
frame.setVisible(true);
mainFrame.setResizable(true);
mainFrame.add(new zug(), BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
});
}
}
}
}

Latest revision as of 19:50, 21 May 2023

An good Snake Game by IZzSaken

edited on 21th May 2023

import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class SnakeGame extends JPanel implements ActionListener {

   private static final int WIDTH = 300;
   private static final int HEIGHT = 300;
   private static final int UNIT_SIZE = 10;
   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];
   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;
   public SnakeGame() {
       setPreferredSize(new Dimension(WIDTH, HEIGHT));
       setBackground(Color.BLACK);
       setFocusable(true);
       addKeyListener(new MyKeyAdapter());
       startGame();
   }
   private void startGame() {
       newApple();
       running = true;
       timer = new Timer(DELAY, this);
       timer.start();
   }
   @Override
   public void paintComponent(Graphics g) {
       super.paintComponent(g);
       draw(g);
   }
   private void draw(Graphics g) {
       if (running) {
           g.setColor(Color.RED);
           g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
           for (int i = 0; i < bodyParts; i++) {
               if (i == 0) {
                   g.setColor(Color.GREEN);
                   g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
               } else {
                   g.setColor(new Color(45, 180, 0));
                   g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
               }
           }
           g.setColor(Color.WHITE);
           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() {
       appleX = (int) (Math.random() * (WIDTH / UNIT_SIZE)) * UNIT_SIZE;
       appleY = (int) (Math.random() * (HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
   }
   private void move() {
       for (int i = bodyParts; i > 0; i--) {
           x[i] = x[i - 1];
           y[i] = y[i - 1];
       }
       switch (direction) {
           case 'U':
               y[0] = y[0] - UNIT_SIZE;
               break;
           case 'D':
               y[0] = y[0] + UNIT_SIZE;
               break;
           case 'L':
               x[0] = x[0] - UNIT_SIZE;
               break;
           case 'R':
               x[0] = x[0] + UNIT_SIZE;
               break;
       }
   }
   private void checkApple() {
       if ((x[0] == appleX) && (y[0] == appleY)) {
           bodyParts++;
           applesEaten++;
           newApple();
       }
   }
   private void checkCollisions() {
       // Check if head collides with body
       for (int i = bodyParts; i > 0; i--) {
           if ((x[0] == x[i]) && (y[0] == y[i])) {
               running = false;
           }
       }
       // Check if head touches left border
       if (x[0] < 0) {
           running = false;
       }
       // Check if head touches right border
       if (x[0] >= WIDTH) {
           running = false;
       }
       // Check if head touches top border
       if (y[0] < 0) {
           running = false;
       }
       // Check if head touches bottom border
       if (y[0] >= HEIGHT) {
           running = false;
       }
       if (!running) {
           timer.stop();
       }
   }
   private void gameOver(Graphics g) {
       g.setColor(Color.WHITE);
       g.setFont(new Font("Arial", Font.BOLD, 20));
       FontMetrics metrics1 = getFontMetrics(g.getFont());
       g.drawString("Game Over", (WIDTH - metrics1.stringWidth("Game Over")) / 2, HEIGHT / 2);
       g.setColor(Color.WHITE);
       g.setFont(new Font("Arial", Font.BOLD, 14));
       FontMetrics metrics2 = getFontMetrics(g.getFont());
       g.drawString("Score: " + applesEaten, (WIDTH - metrics2.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize());
   }
   @Override
   public void actionPerformed(ActionEvent e) {
       if (running) {
           move();
           checkApple();
           checkCollisions();
       }
       repaint();
   }
   private class MyKeyAdapter extends KeyAdapter {
       @Override
       public void keyPressed(KeyEvent e) {
           switch (e.getKeyCode()) {
               case KeyEvent.VK_LEFT:
                   if (direction != 'R') {
                       direction = 'L';
                   }
                   break;
               case KeyEvent.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;
           }
       }
   }
   public static void main(String[] args) {
       JFrame frame = new JFrame("Snake Game");
       SnakeGame game = new SnakeGame();
       frame.add(game);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setResizable(false);
       frame.pack();
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }

}