Write the code for the snake game on Java
- User
Write the code for the snake game on Java
- Assistant
Write the code for the snake game on Java
Sure! Below is a simple implementation of the classic Snake game in Java using the Swing library for the GUI. The game involves controlling a snake to eat food while avoiding collisions with the walls or itself.
Note: To run this code, you need to have Java installed on your computer. Save the code files with the appropriate filenames as indicated.
SnakeGame.javaThis is the main class that sets up the game window.
import javax.swing.JFrame;
public class SnakeGame {
public static void main(String[] args) {
JFrame frame = new JFrame("Snake Game");
GamePanel game_panel = new GamePanel();
frame.add(game_panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack(); // Sizes the frame so that all its contents are at or above their preferred sizes.
frame.setLocationRelativeTo(null); // Centers the frame on the screen
frame.setVisible(true);
}
}
GamePanel.javaThis class contains the game logic, rendering, and key handling.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class GamePanel extends JPanel implements ActionListener {
private static final int SCREEN_WIDTH = 600; // Width of the game screen
private static final int SCREEN_HEIGHT = 600; // Height of the game screen
private static final int UNIT_SIZE = 25; // Size of each unit in the game
private static final int GAME_UNITS = (SCREEN_WIDTH * SCREEN_HEIGHT) / (UNIT_SIZE * UNIT_SIZE); // Total game units
private static final int DELAY = 75; // Delay for the timer (controls the speed of the game)
private final int x[] = new int[GAME_UNITS]; // x positions of snake body parts
private final int y[] = new int[GAME_UNITS]; // y positions of snake body parts
private int bodyParts = 6; // Initial length of the snake
private int applesEaten; // Number of apples eaten
private int appleX; // x position of the apple
private int appleY; // y position of the apple
private char direction = 'R'; // Initial direction: 'U' = up, 'D' = down, 'L' = left, 'R' = right
private boolean running = false; // Game state
private Timer timer;
private Random random;
public GamePanel() {
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
newApple(); // Spawn the first apple
running = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if (running) {
// Optionally draw a grid
/*
for (int i = 0; i < SCREEN_HEIGHT / UNIT_SIZE; i++) {
g.drawLine(i * UNIT_SIZE, 0, i * UNIT_SIZE, SCREEN_HEIGHT);
g.drawLine(0, i * UNIT_SIZE, SCREEN_WIDTH, i * UNIT_SIZE);
}
*/
// Draw the apple
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
// Draw the snake
for (int i = 0; i < bodyParts; i++) {
if (i == 0) {
// Head of the snake
g.setColor(Color.green);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
} else {
// Body of the snake
g.setColor(new Color(45, 180, 0));
// Optionally can make the color change with length
// g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
// Display score
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 30));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten,
(SCREEN_WIDTH - metrics.stringWidth("Score: " + applesEaten)) / 2,
g.getFont().getSize());
} else {
gameOver(g);
}
}
public void newApple() {
appleX = random.nextInt((int) (SCREEN_WIDTH / UNIT_SIZE)) * UNIT_SIZE;
appleY = random.nextInt((int) (SCREEN_HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
}
public void move() {
// Shifts each segment to the position of the segment ahead of it
for (int i = bodyParts; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
// Moves the head in the current direction
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;
}
}
public void checkApple() {
// Checks if the snake's head is on the apple
if ((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++; // Increase snake size
applesEaten++; // Increase score
newApple(); // Spawn a new apple
}
}
public void checkCollisions() {
// Checks if head collides with body
for (int i = bodyParts; i > 0; i--) {
// Head collides with body part
if ((x[0] == x[i]) && (y[0] == y[i])) {
running = false;
break;
}
}
// Check if head touches left border
if (x[0] < 0) {
running = false;
}
// Check if head touches right border
if (x[0] >= SCREEN_WIDTH) {
running = false;
}
// Check if head touches top border
if (y[0] < 0) {
running = false;
}
// Check if head touches bottom border
if (y[0] >= SCREEN_HEIGHT) {
running = false;
}
// Stop the timer if game is not running
if (!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
// Display the score
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 30));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten,
(SCREEN_WIDTH - metrics1.stringWidth("Score: " + applesEaten)) / 2,
g.getFont().getSize());
// Display Game Over text
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("Game Over",
(SCREEN_WIDTH - metrics2.stringWidth("Game Over")) / 2,
SCREEN_HEIGHT / 2);
}
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkApple();
checkCollisions();
}
repaint(); // Calls paintComponent
}
public class MyKeyAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
// Prevents the snake from reversing
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;
}
}
}
}
Instructions to Run the Game:
Set Up the Project:
Add the Classes:
SnakeGame.java and GamePanel.java.Compile and Run:
SnakeGame class. A window should open displaying the game.Gameplay:
Explanation of the Code:
GamePanel to it.JPanel method to draw game elements.Feel free to modify and expand upon this basic game to add more features, such as levels, obstacles, or a high-score system. Happy coding!
Not yet included in a published release.