Simple Snake game Java code example

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right.

Article directory

  • Preface
  • 1. Description
  • 2. SnakeGame.java code

Foreword

Tips: You can add the general content to be recorded in this article here:

Simple Snake game Java code example

1. Description

You can save the above code to a file called SnakeGame.java and run it in your Java development environment. This program uses Java’s Swing library to create the game window and control the movement of the snake through the keyboard. The size of the game window is 300×300 pixels. The body of the greedy snake is composed of a series of small squares. It will constantly move and eat apples. When the greedy snake touches its own body or the window border, the game ends.

2. SnakeGame.java code

code show as below:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

public class SnakeGame extends JPanel implements ActionListener {<!-- -->

    private final int B_WIDTH = 300;
    private final int B_HEIGHT = 300;
    private final int DOT_SIZE = 10;
    private final int ALL_DOTS = 900;
    private final int RAND_POS = 29;
    private final int DELAY = 140;

    private final int x[] = new int[ALL_DOTS];
    private final int y[] = new int[ALL_DOTS];

    private int dots;
    private int apple_x;
    private int apple_y;

    private boolean leftDirection = false;
    private boolean rightDirection = true;
    private boolean upDirection = false;
    private boolean downDirection = false;
    private boolean inGame = true;

    private Timer timer;
    private Image ball;
    private Image apple;
    private Image head;

    public SnakeGame() {<!-- -->
        
        initBoard();
    }
    
    private void initBoard() {<!-- -->
        
        addKeyListener(new TAdapter());
        setBackground(Color.black);
        setFocusable(true);

        setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
        loadImages();
        initGame();
    }

    private void loadImages() {<!-- -->

        ImageIcon iid = new ImageIcon("src/resources/dot.png");
        ball = iid.getImage();

        ImageIcon iia = new ImageIcon("src/resources/apple.png");
        apple = iia.getImage();

        ImageIcon iih = new ImageIcon("src/resources/head.png");
        head = iih.getImage();
    }

    private void initGame() {<!-- -->

        dots = 3;

        for (int z = 0; z < dots; z + + ) {<!-- -->
            x[z] = 50 - z * 10;
            y[z] = 50;
        }

        locateApple();

        timer = new Timer(DELAY, this);
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {<!-- -->
        super.paintComponent(g);

        doDrawing(g);
    }
    
    private void doDrawing(Graphics g) {<!-- -->
        
        if (inGame) {<!-- -->

            g.drawImage(apple, apple_x, apple_y, this);

            for (int z = 0; z < dots; z + + ) {<!-- -->
                if (z == 0) {<!-- -->
                    g.drawImage(head, x[z], y[z], this);
                } else {<!-- -->
                    g.drawImage(ball, x[z], y[z], this);
                }
            }

            Toolkit.getDefaultToolkit().sync();

        } else {<!-- -->

            gameOver(g);
        }
    }

    private void gameOver(Graphics g) {<!-- -->
        
        String msg = "Game Over";
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = getFontMetrics(small);

        g.setColor(Color.white);
        g.setFont(small);
        g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
    }

    private void checkApple() {<!-- -->

        if ((x[0] == apple_x) & amp; & amp; (y[0] == apple_y)) {<!-- -->

            dots + + ;
            locateApple();
        }
    }

    private void move() {<!-- -->

        for (int z = dots; z > 0; z--) {<!-- -->
            x[z] = x[(z - 1)];
            y[z] = y[(z - 1)];
        }

        if (leftDirection) {<!-- -->
            x[0] -= DOT_SIZE;
        }

        if (rightDirection) {<!-- -->
            x[0] + = DOT_SIZE;
        }

        if (upDirection) {<!-- -->
            y[0] -= DOT_SIZE;
        }

        if (downDirection) {<!-- -->
            y[0] + = DOT_SIZE;
        }
    }

    private void checkCollision() {<!-- -->

        for (int z = dots; z > 0; z--) {<!-- -->

            if ((z > 4) & amp; & amp; (x[0] == x[z]) & amp; & amp; (y[0] == y[z])) {<!-- - ->
                inGame = false;
            }
        }

        if (y[0] >= B_HEIGHT) {<!-- -->
            inGame = false;
        }

        if (y[0] < 0) {<!-- -->
            inGame = false;
        }

        if (x[0] >= B_WIDTH) {<!-- -->
            inGame = false;
        }

        if (x[0] < 0) {<!-- -->
            inGame = false;
        }
        
        if (!inGame) {<!-- -->
            timer.stop();
        }
    }

    private void locateApple() {<!-- -->

        int r = (int) (Math.random() * RAND_POS);
        apple_x = ((r * DOT_SIZE));

        r = (int) (Math.random() * RAND_POS);
        apple_y = ((r * DOT_SIZE));
    }

    @Override
    public void actionPerformed(ActionEvent e) {<!-- -->

        if (inGame) {<!-- -->

            checkApple();
            checkCollision();
            move();
        }

        repaint();
    }

    private class TAdapter extends KeyAdapter {<!-- -->

        @Override
        public void keyPressed(KeyEvent e) {<!-- -->

            int key = e.getKeyCode();

            if ((key == KeyEvent.VK_LEFT) & amp; & amp; (!rightDirection)) {<!-- -->
                leftDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_RIGHT) & amp; & amp; (!leftDirection)) {<!-- -->
                rightDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_UP) & amp; & amp; (!downDirection)) {<!-- -->
                upDirection = true;
                rightDirection = false;
                leftDirection = false;
            }

            if ((key == KeyEvent.VK_DOWN) & amp; & amp; (!upDirection)) {<!-- -->
                downDirection = true;
                rightDirection = false;
                leftDirection = false;
            }
        }
    }
}