Snake/Java: Difference between revisions

2,711 bytes removed ,  11 months ago
no edit summary
No edit summary
 
(6 intermediate revisions by 5 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 */
/* */
/* Last Editied (09/01/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 SnakeSnakeGame extends JPanel implements RunnableActionListener {
private static final int WIDTH = 300;
enum Dir {
private static final int HEIGHT = 300;
up(0, -1), right(1, 0), down(0, 1), left(-1, 0);
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 Dir(int[] x, int= y)new {int[GAME_UNITS];
private final int[] this.xy = x;new this.y = yint[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() {
final int x, y;
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(new MyKeyAdapter());
startGame();
}
 
private void startGame() {
static final Random rand = new Random();
static final int WALL = -1newApple();
static final int MAX_ENERGY running = 1500true;
timer = new Timer(DELAY, this);
timer.start();
}
 
@Override
volatile boolean gameOver = true;
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
 
private void draw(Graphics g) {
Thread gameThread;
if (running) {
int score, hiScore;
g.setColor(Color.RED);
int nRows = 44;
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
int nCols = 64;
Dir dir;
int energy;
 
for (int i = 0; i < bodyParts; i++) {
int[][] grid;
if (i == 0) {
List<Point> snake, treats;
g.setColor(Color.GREEN);
Font smallFont;
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
 
public Snake() } else {
setPreferredSize g.setColor(new DimensionColor(64045, 180, 4400));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
setBackground(Color.white);
setFont(new Font("SansSerif", 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();
}
}
});
 
g.setColor(Color.WHITE);
addKeyListener(new KeyAdapter() {
g.setFont(new Font("Arial", Font.BOLD, 14));
 
FontMetrics metrics = getFontMetrics(g.getFont());
@Override
g.drawString("Score: " + applesEaten, (WIDTH - metrics.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize());
public void keyPressed(KeyEvent e) {
} else {
 
switch gameOver(e.getKeyCode()g) {;
}
 
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 startNewGamenewApple() {
appleX = (int) (Math.random() * (WIDTH / UNIT_SIZE)) * UNIT_SIZE;
gameOver = false;
appleY = (int) (Math.random() * (HEIGHT / 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();
}
 
private void stopmove() {
iffor (gameThreadint i != nullbodyParts; i > 0; i--) {
Thread tmpx[i] = gameThreadx[i - 1];
gameThready[i] = nully[i - 1];
tmp.interrupt();
}
}
 
void initGrid switch (direction) {
grid = new int[nRows][nCols]; case 'U':
for (int r = 0; r < nRows; r++)y[0] {= y[0] - UNIT_SIZE;
for (int c = 0break; c < nCols; c++) {
case 'D':
if (c == 0 || c == nCols - 1 || r == 0 || r == nRows - 1)
y[0] = gridy[r][c0] =+ WALLUNIT_SIZE;
} break;
case 'L':
x[0] = x[0] - UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
 
private void checkApple() {
@Override
if ((x[0] == appleX) && (y[0] == appleY)) {
public void run() {
bodyParts++;
 
applesEaten++;
while (Thread.currentThread() == gameThread) {
newApple();
 
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();
}
}
 
booleanprivate energyUsedvoid checkCollisions() {
energy// -=Check 10;if head collides with body
returnfor energy(int i <= bodyParts; i > 0; i--) {
if ((x[0] == x[i]) && (y[0] == y[i])) {
}
running = false;
 
boolean hitsWall() {
Point head = snake.get(0);
int nextCol = head.x + dir.x;
int nextRow = head.y + dir.y;
return grid[nextRow][nextCol] == WALL;
}
 
boolean hitsSnake() {
Point head = snake.get(0);
int nextCol = head.x + dir.x;
int nextRow = head.y + dir.y;
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 + dir.x;
int nextRow = head.y + dir.y;
for (Point p : treats)
if (p.x == nextCol && p.y == nextRow) {
return treats.remove(p);
}
return false;}
}
 
// Check if head touches left border
void gameOver() {
gameOverif =(x[0] true;< 0) {
stop() running = false;
}
 
// Check if head touches right border
void moveSnake() {
forif (int ix[0] >= snake.size() - 1; i > 0; i--WIDTH) {
Point p1running = snake.get(i - 1)false;
Point p2 = snake.get(i);
p2.x = p1.x;
p2.y = p1.y;
}
Point head = snake.get(0);
head.x += dir.x;
head.y += dir.y;
}
 
// Check if head touches top border
void growSnake() {
Pointif tail(y[0] =< snake.get(snake.size(0) - 1);{
int x = tail.x +running = dir.xfalse;
int y = tail.y + dir.y;}
snake.add(new Point(x, y));
}
 
// Check if head touches bottom border
void addTreat() {
if (treats.size()y[0] <>= 3HEIGHT) {
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);
}
}
}
 
if (!running) {
void drawGrid(Graphics2D g) {
g timer.setColorstop(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());
}
 
@Override
void drawTreats(Graphics2D g) {
public void actionPerformed(ActionEvent e) {
g.setColor(Color.green);
forif (Pointrunning) p : treats){
g.fillRectmove(p.x * 10, p.y * 10, 10, 10);
checkApple();
checkCollisions();
}
repaint();
}
 
private class MyKeyAdapter extends KeyAdapter {
void drawStartScreen(Graphics2D g) {
g.setColor(Color.blue);@Override
g.setFontpublic void keyPressed(getFont()KeyEvent e); {
switch (e.getKeyCode()) {
g.drawString("Snake", 240, 190);
case KeyEvent.VK_LEFT:
g.setColor(Color.orange);
g.setFont if (smallFontdirection != 'R'); {
direction = 'L';
g.drawString("(click to start)", 250, 240);
}
break;
 
case KeyEvent.VK_RIGHT:
void drawScore(Graphics2D g) {
int h = getHeight if (direction != 'L'); {
g.setFont(smallFont) direction = 'R';
g.setColor(getForeground()); }
String s = format("hiscore %d score %d", hiScore, score) break;
g.drawString(s, 30, h - 30); case KeyEvent.VK_UP:
if (direction != 'D') {
g.drawString(format("energy %d", energy), getWidth() - 150, h - 30);
direction = 'U';
}
}
 
break;
@Override
case KeyEvent.VK_DOWN:
public void paintComponent(Graphics gg) {
super.paintComponent if (ggdirection != 'U'); {
Graphics2D g = (Graphics2D) gg direction = 'D';
}
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON) break;
}
 
drawGrid(g);
 
if (gameOver) {
drawStartScreen(g);
} else {
drawSnake(g);
drawTreats(g);
drawScore(g);
}
}
 
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