Snake/Java: Difference between revisions

2,535 bytes removed ,  11 months ago
no edit summary
No edit summary
No edit summary
 
(5 intermediate revisions by 4 users not shown)
Line 1:
An good Snake Game by IZzSaken
==Code==
 
{{works with|Java|8}}
edited on 21th May 2023
<lang java>
 
/***************************************************/
/* Sourced By Samuel Dennis */
/* */
/* Created On (09/01/2019) */
/* Last Editied (11/18/2019) */
/***************************************************/
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 TestCodeSnake extends JPanel implements Runnable {
enum Dir {
up(0, -1), right(1, 0), down(0, 1), left(-1, 0);
Dir(int x, int y) {
this.x = x; this.y = y;
}
final int x, y;
}
 
public class SnakeGame extends JPanel implements ActionListener {
static final Random rand = new Random();
private static final int WALLWIDTH = -1300;
private static final int MAX_ENERGYHEIGHT = 1500300;
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];
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;
 
public SnakeGame() {
Thread gameThread;
setPreferredSize(new Dimension(WIDTH, HEIGHT));
int score, hiScore;
setBackground(Color.BLACK);
int nRows = 44;
setFocusable(true);
int nCols = 64;
addKeyListener(new MyKeyAdapter());
Dir dir;
int energy startGame();
}
 
private void startGame() {
int[][] grid;
newApple();
List<Point> snake, treats;
running = true;
Font smallFont;
timer = new Timer(DELAY, this);
timer.start();
}
 
@Override
public TestCodeSnake() {
public void paintComponent(Graphics g) {
setPreferredSize(new Dimension(640, 440));
setBackground(Color super.WHITEpaintComponent(g);
draw(g);
setFont(new Font("TimesNewRoman", Font.BOLD, 48));
}
setFocusable(true);
smallFont = getFont().deriveFont(Font.BOLD, 18);
initGrid();
addMouseListener(
new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (gameOver) {
startNewGame();
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();
}
});
}
 
private void startNewGamedraw(Graphics g) {
gameOver = false;if (running) {
g.setColor(Color.RED);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
stop();
initGrid();
treats = new LinkedList<>();
dir = Dir.left;
energy = MAX_ENERGY;
if (score > hiScore)
hiScore = score;
score = 0;
snake = new ArrayList<>();
for (int x = 0; x < 7; x++)
snake.add(new Point(nCols / 2 + x, nRows / 2));
do
addTreat();
while(treats.isEmpty());
(gameThread = new Thread(this)).start();
}
 
for (int i = 0; i < bodyParts; i++) {
void stop() {
if (gameThreadi !== null0) {
Thread tmp = gameThread g.setColor(Color.GREEN);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
gameThread = null;
tmp.interrupt(); } else {
g.setColor(new Color(45, 180, 0));
}
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
 
void initGrid() {
grid = 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)
grid[r][c] = WALL;
}
}
}
 
@Override
public void run() {
while (Thread.currentThread() == gameThread) {
try {
Thread.sleep(Math.max(75 - score, 25));
} catch (InterruptedException e) {
return;
}
if (energyUsed() || hitsWall() || hitsSnake()) {
gameOver();
} else {
if (eatsTreat()) {
score++;
energy = MAX_ENERGY;
growSnake();
}
moveSnake();
addTreat();
}
repaint();
}
}
 
g.setColor(Color.WHITE);
boolean energyUsed() {
g.setFont(new Font("Arial", Font.BOLD, 14));
energy -= 10;
FontMetrics metrics = getFontMetrics(g.getFont());
return energy <= 0;
g.drawString("Score: " + applesEaten, (WIDTH - metrics.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize());
}
} else {
gameOver(g);
}
}
 
boolean hitsWallprivate void newApple() {
appleX = (int) (Math.random() * (WIDTH / UNIT_SIZE)) * UNIT_SIZE;
Point head = snake.get(0);
appleY = (int) (Math.random() * (HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
int nextCol = head.x + dir.x;
}
int nextRow = head.y + dir.y;
return grid[nextRow][nextCol] == WALL;
}
 
boolean hitsSnakeprivate void move() {
for (int i = bodyParts; i > 0; i--) {
Point head = snake.get(0);
int nextCol = head. x[i] += dir.x[i - 1];
int nextRow = head. y[i] += dir.y[i - 1];
for (Point p : snake)}
if (p.x == nextCol && p.y == nextRow)
return true;
return false;
}
 
boolean eatsTreat switch (direction) {
Point head = snake.get(0); case 'U':
int nextCol y[0] = head.xy[0] +- dir.xUNIT_SIZE;
int nextRow = head.y + dir.y break;
for (Point p : treats) case 'D':
if (p.x == nextCol && p. y[0] == nextRow)y[0] + {UNIT_SIZE;
return treats.remove(p) break;
} case 'L':
x[0] = x[0] - UNIT_SIZE;
return false;
break;
}
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
 
private void gameOvercheckApple() {
if ((x[0] == appleX) && (y[0] == appleY)) {
gameOver = true;
stop() bodyParts++;
applesEaten++;
}
newApple();
}
}
 
private void moveSnakecheckCollisions() {
for (int i// =Check snake.size()if -head 1;collides iwith > 0; i--) {body
for Point(int p1i = snake.get(bodyParts; i -> 1)0; i--) {
Point p2 if ((x[0] == snake.getx[i]) && (y[0] == y[i]);) {
p2.x running = p1.xfalse;
p2.y = p1.y; }
}
Point head = snake.get(0);
head.x += dir.x;
head.y += dir.y;
}
 
// Check if head touches left border
void growSnake() {
Point tail =if snake.get(snake.size()x[0] -< 10); {
int x = tail.x + dir.x running = false;
int y = tail.y + dir.y;}
snake.add(new Point(x, y));
}
 
// Check if head touches right border
void addTreat() {
if (treats.size()x[0] <>= 3WIDTH) {
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 (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)
treats.remove(0);
}
}
}
 
// Check if head touches top border
void drawGrid(Graphics2D g) {
g.setColor if (Color.blacky[0] < 0); {
for (int r = 0; r <running nRows= false; r++) {
}
for (int c = 0; c < nCols; c++) {
if (grid[r][c] == WALL)
g.fillRect(c * 10, r * 10, 10, 10);
}
}
}
 
// Check if head touches bottom border
void drawSnake(Graphics2D g) {
g.setColor if (Color.redy[0] >= HEIGHT); {
for (Point p : snake) running = false;
}
g.fillRect(p.x * 10, p.y * 10, 10, 10);
g.setColor(energy < 500 ? Color.red : Color.orange);
Point head = snake.get(0);
g.fillRect(head.x * 10, head.y * 10, 10, 10);
}
 
if (!running) {
void drawTreats(Graphics2D g) {
g timer.setColorstop(Color.green);
for (Point p : treats)}
}
g.fillRect(p.x * 10, p.y * 10, 10, 10);
}
 
private void drawStartScreengameOver(Graphics2DGraphics g) {
g.setColor(Color.redWHITE);
g.setFont(getFontnew Font("Arial", Font.BOLD, 20));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("SNAKE", 240, 190);
g.drawString("Game Over", (WIDTH - metrics1.stringWidth("Game Over")) / 2, HEIGHT / 2);
g.setColor(Color.orange);
g.setFont(smallFont);
g.drawString("(Click To START)", 250, 240);
}
 
g.setColor(Color.WHITE);
void drawScore(Graphics2D g) {
g.setFont(new Font("Arial", Font.BOLD, 14));
int h = getHeight();
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.setFont(smallFont);
g.drawString("Score: " + applesEaten, (WIDTH - metrics2.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize());
g.setColor(getForeground());
}
String s = format("Hi-Score: %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.paintComponent if (ggrunning); {
Graphics2D g = move(Graphics2D) gg;
checkApple();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ONcheckCollisions();
}
drawGrid repaint(g);
}
 
if (gameOver) {
private class MyKeyAdapter extends KeyAdapter {
drawStartScreen(g);
} else {@Override
public drawSnakevoid keyPressed(gKeyEvent e); {
drawTreats switch (ge.getKeyCode()); {
drawScore(g); 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");
SwingUtilities.invokeLater(
SnakeGame ()game ->= {new SnakeGame();
JFrame mainFrame = new JFrameframe.add(game);
mainFrameframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrameframe.setTitlesetResizable("SNAKE"false);
mainFrameframe.setResizablepack(true);
frame.setLocationRelativeTo(null);
mainFrame.add(new TestCodeSnake(), BorderLayout.CENTER);
mainFrameframe.packsetVisible(true);
}
mainFrame.setLocationRelativeTo(null);
}
mainFrame.setVisible(true);
});
}
}</lang>
3

edits