Home > Java > javaTutorial > How to implement the Snake game in Java

How to implement the Snake game in Java

醉折花枝作酒筹
Release: 2021-04-16 19:10:50
forward
3970 people have browsed it

This article will give you a detailed introduction to the method of implementing the Snake game in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to implement the Snake game in Java

1. Program structure

 The program structure diagram is as shown:
How to implement the Snake game in Java

2. Program design ideas

2.1 Data class

  • Function: Connect to the statics folder and convert the pictures in the static resource package into icons to facilitate drawing on the panel.
  • Implementation: Use class.getResource(String path) method.

 The code is as follows:

package com.snake;import javax.swing.*;import java.net.URL;public class Data {
    //贪吃蛇头部
    public static URL upUrl = Data.class.getResource("/statics/up.png");
    public static ImageIcon up = new ImageIcon(upUrl);
    public static URL downUrl = Data.class.getResource("/statics/down.png");
    public static ImageIcon down = new ImageIcon(downUrl);
    public static URL leftUrl = Data.class.getResource("/statics/left.png");
    public static ImageIcon left = new ImageIcon(leftUrl);
    public static URL rightUrl = Data.class.getResource("/statics/right.png");
    public static ImageIcon right = new ImageIcon(rightUrl);
    //贪食蛇身体
    public static URL bodyUrl = Data.class.getResource("/statics/body.png");
    public static ImageIcon body = new ImageIcon(bodyUrl);
    //食物
    public static URL foodUrl = Data.class.getResource("/statics/food.png");
    public static ImageIcon food = new ImageIcon(foodUrl);}
Copy after login

2.2 StartGame class

  • Function: Create a game window and add a game panel to the window.
  • Implementation: Use the JFrame class to create a game window, and use its add() method to add a GamePanel class instantiation object.

 The code is as follows:

package com.snake;import javax.swing.*;import java.awt.*;public class StartGame {
    public static void main(String[] args){
        //建立游戏窗口
        JFrame frame = new JFrame("Java-贪吃蛇小游戏");//标题
        frame.setSize(900,720);//窗口大小
        frame.setLocationRelativeTo(null);//窗口显示屏幕中间
        frame.setResizable(false);//固定窗口大小
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗体关闭事件
        frame.add(new GamePanel());//添加游戏内容
        frame.setVisible(true);//设置窗体可见
    }}
Copy after login

2.3 GamePanel class

  • Function: implement the dynamic page of the game.
  • Implementation: (1) init() method: initialize the position of the snake;
               (2) eat() method: use random seeds to randomize the position of the food, and make a determination. The food position cannot be the same as the snake The positions coincide;
            (3) Inherit the JPanel class, override the paintComponent (Graphics g) method, and draw the title bar, the position of the snake (draw the snake head according to the direction snake head direction variable), and the snake body in the method , points bar, game reminder items and failure judgment items;
                  (4) Implement the keyPressed(KeyEvent e) method in the KeyListener interface, obtain keyboard input, and change the game state or the snake head direction variable according to the keyboard input;
                (5) Implement the actionPerformed(ActionEvent e) method in the ActionListener interface, perform snake movement operations based on the game state and direction variables (note that direct turning back operations are disabled), and perform food eating and death determinations. Use the Timer to make the game dynamically change, and use the repaint() method to update the interface in real time.
     The code is as follows:
package com.snake;import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.Random;public class GamePanel extends JPanel implements KeyListener, ActionListener {
    int[] snakeX = new int[500];//贪吃蛇横坐标
    int[] snakeY = new int[500];//贪吃蛇纵坐标
    int foodX;//食物横坐标
    int foodY;//食物蛇纵坐标
    int length;//贪吃蛇的长度
    String  direction;//贪吃蛇头方向
    int score;//积分
    Random r = new Random();
    Timer timer = new Timer(100,this);
    boolean isStart;
    boolean isFail;
    //构造函数
    public GamePanel(){
        init();
        this.setFocusable(true);
        this.addKeyListener(this);
        timer.start();
    }
    private void init(){
        length=3;
        snakeX[0]=100;snakeY[0]=100;
        snakeX[1]=75;snakeY[1]=100;
        snakeX[2]=50;snakeY[2]=100;
        direction = "R";
        eat(foodX,foodY);
        isStart = false;
        isFail = false;
        score = 0;

    }
    private void eat(int x,int y){
        x= 25 + 25*r.nextInt(34);
        y= 75 + 25*r.nextInt(24);
        for (int i = 0; i < length; i++) {
            if(snakeX[i]==x&&snakeY[i]==y){
                x = 25 + 25*r.nextInt(34);
                y = 75 + 25*r.nextInt(24);
            }
        }
        foodX = x;foodY = y;
    }
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.white);//设置背景板为白色
        //画标题
        g.setColor(Color.GREEN);
        g.setFont(new Font("幼圆",Font.BOLD,50));
        g.drawString("贪吃蛇游戏",300,60);
        //绘制游戏区域
        g.setColor(Color.GRAY);
        g.fillRect(25,75,850,600);
        //画贪吃蛇头部
        if(direction=="R"){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        else if(direction=="L"){
            Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        if(direction=="U"){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        else if(direction=="D"){
            Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        //画身体
        for (int i = 1; i < length ; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }
        //画食物
        Data.food.paintIcon(this,g,foodX,foodY);
        //绘制积分栏
        g.setColor(Color.BLACK);
        g.setFont(new Font("幼圆",Font.BOLD,20));
        g.drawString("长度:"+length,730,30);
        g.drawString("得分:"+score,730,60);
        //游戏开始提醒
        if(isStart==false){
            g.setColor(Color.BLACK);
            g.setFont(new Font("幼圆",Font.BOLD,40));
            g.drawString("按空格键开始游戏",300,300);
        }
        //失败判断
        if(isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("幼圆",Font.BOLD,40));
            g.drawString("游戏失败,按空格键重新开始",300,300);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();//获取按下的按键
        //判断空格
        if(keyCode==KeyEvent.VK_SPACE){
            if(isFail){
                isFail = false;
                init();
            }
            else{
                isStart = !isStart;
            }
            repaint();
        }
        //判断方向
        if(keyCode==KeyEvent.VK_LEFT&&direction!="R"){
            direction = "L";
        }
        else if(keyCode==KeyEvent.VK_RIGHT&&direction!="L"){
            direction = "R";
        }
        else if(keyCode==KeyEvent.VK_UP&&direction!="D"){
            direction = "U";
        }
        else if(keyCode==KeyEvent.VK_DOWN&&direction!="U"){
            direction = "D";
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {

    }
    @Override
    public void keyTyped(KeyEvent e) {
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        //判断游戏状态
        if(isStart&&!isFail){
            //移动身体
            for (int i = length-1; i > 0 ; i--) {
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }
            //移动头部
            if(direction=="R"){
                snakeX[0] += 25;
                if(snakeX[0]>850){
                    snakeX[0] = 25;
                }
            }
            else  if(direction=="L"){
                snakeX[0] -= 25;
                if(snakeX[0]<25){
                    snakeX[0] = 850;
                }
            }
            else  if(direction=="U"){
                snakeY[0] -= 25;
                if(snakeY[0]<75){
                    snakeY[0] = 650;
                }
            }
            else  if(direction=="D"){
                snakeY[0] += 25;
                if(snakeY[0]>650){
                    snakeY[0] = 75;
                }
            }
            //吃食物
            if(snakeX[0]==foodX&&snakeY[0]==foodY){
                length++;
                score += 10;
                eat(foodX,foodY);
            }
            //死亡判定
            for (int i = 1; i < length; i++) {
                if(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
                    isFail=true;
                }
            }
            repaint();
        }
        timer.start();
    }}
Copy after login

3. Game display

How to implement the Snake game in Java

Recommendation: "java video tutorial"

The above is the detailed content of How to implement the Snake game in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template