Java GUI practice, greedy snake

Write a greedy snake

Keyboard monitor

Timer timer

Time monitoring

paint brush

1. Data center class

Define picture URL

Define Icon

Icons of head up, down, left and right, body, object and banner

2. Game startup class

The main method starts the game

Define main window

Set the main window size value, visible, size, and close events

Add Sketchpad

3. Game Sketchpad

  • Define data

    • Snake length
    • Snake coordinates
    • Head direction
    • Coordinates of food
    • random food coordinates
    • integral
    • Start state of the game
    • Failure status of the game
    • Timer timer (how many milliseconds does int execute once, object)
  • Constructor:

    • Call the initialization method,
    • Get focus
    • Get keyboard events
    • Start timer
  • Initialization method

    • Initialize the length of the snake
    • Initialize the snake's head position and body position
    • Initialize the orientation of the head
    • Coordinates of random food
    • Integral initialization 0
  • Draw Sketchpad

    • Clear screen
    • Set palette background color
    • Set the size and position of the sketchpad interface fillRect
    • Draw the banner and get the data from the data center
    • Draw the points
      • Set the integral font. setFont(Font)
      • Set slogan, drawString (font, x,y)
    • Draw food
    • Draw little snake head
      • Judge the four directions and use different ImageIcon
    • Draw the body of a snake
      • The coordinate is the last coordinate of the snake head
    • Determine whether the game starts
      • Set slogan, drawString (word, x,y)
    • Judge whether the game fails
      • Set slogan, drawString (word, x,y)
  • Keyboard listening events

    • You can implement the KeyListener interface and override the keypressed method
    • Listening space
    • Monitor up, down, left and right keys
  • Event listening needs to be refreshed through fixed events

    • Judge the start and failure status of the game
    • Determine whether you eat food
    • Let the snake's head move (for)
      • Judge direction and boundary
    • Let the little snake move (for) the body coordinates of the little snake are the coordinates of the previous section
    • Judge whether failed (for)
    • Redraw
    • Timer on

1. Data class

  • Define the picture data of each part
package com.ccc.testsnake;

import javax.swing.*;
import java.net.URL;

public class Data {
    private static URL urlHeader = Data.class.getResource("z-image/header.png");
    private static URL urlUp = Data.class.getResource("z-image/up.png");
    private static URL urlDown = Data.class.getResource("z-image/down.png");
    private static URL urlLeft = Data.class.getResource("z-image/left.png");
    private static URL urlRight = Data.class.getResource("z-image/right.png");
    private static URL urlBody = Data.class.getResource("z-image/body.png");
    private static URL urlfood = Data.class.getResource("z-image/food.png");
    private static URL urlfood2 = Data.class.getResource("z-image/up.png");
    public static ImageIcon headerImageIcon = new ImageIcon(urlHeader);
    public static ImageIcon UpImageIcon = new ImageIcon(urlUp);
    public static ImageIcon downImageIcon = new ImageIcon(urlDown);
    public static ImageIcon leftImageIcon = new ImageIcon(urlLeft);
    public static ImageIcon rightImageIcon = new ImageIcon(urlRight);
    public static ImageIcon bodyImageIcon = new ImageIcon(urlBody);
    public static ImageIcon foodImageIcon = new ImageIcon(urlfood);
    public static ImageIcon food2ImageIcon = new ImageIcon(urlfood2);
}

2. Startup class

  • Start the game and set the main form parameters
package com.ccc.testsnake;

import javax.swing.*;
import java.awt.*;

public class StartSnakeGame {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame("Space to start the game");

        //Add panel palette
        jFrame.add(new GamePanel());
        jFrame.setVisible(true);
        jFrame.setResizable(false);
        jFrame.setBackground(Color.WHITE);
        jFrame.setBounds(700,300,870,725);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

3. Drawing board

  • Draw a snake,
  • monitor
package com.ccc.testsnake;

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 {
    private int length;//Snake length
    private String direction;//Direction of snake head
    private int count ;//fraction
    private boolean isStart = false;//Start state
    private boolean isFailed = false;//Failure status
    private int[] snakeX;private int[] snakeY;
    private int foodX;private int foodY;
    private int food2X;private int food2Y;
    Random random;//random number
    Timer timer = new Timer(120,this);//timer

    public GamePanel() {
        init();
        this.addKeyListener(this);
        this.setFocusable(true);
        timer.start();
    }

    //Initialization method
    private void init(){
        length = 3;
        snakeX = new int[825];
        snakeY = new int[625];
        direction = "R";
        random = new Random();
        foodX = 300;foodY = 300;
        food2X = 600;food2Y = 600;
        //Initialize snake default coordinates
        for (int i = 0; i <length; i++) {
            snakeX[i] = 100-(25*i);snakeY[i] = 100;//Boundary x 25,y 75
        }
//        snakeX[0] = 100;snakeY[0] = 100;
//        snakeX[1] = 75;snakeY[1] = 100;
//        snakeX[2] = 50;snakeY[2] = 100;

    }
    //Drawing board


    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.BLACK);
        //Draw banners
        Data.headerImageIcon.paintIcon(this,g,0,11);
        g.fillRect(25,75,800,600);
        g.setColor(Color.PINK);
        g.setFont(new Font("Microsoft YaHei ",Font.BOLD,20));
        g.drawString("product       Points:"+count+"branch",440,30);
        g.drawString("How long do you have:"+length+"cm",440,50);
        //Draw food
        Data.foodImageIcon.paintIcon(this,g,foodX,foodY);
        if (((length+foodX)%3)==0){
            Data.food2ImageIcon.paintIcon(this,g,food2X,food2Y);
        }


        //Draw snake head
        if (direction .equals("U")){
            Data.UpImageIcon.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if(direction.equals("D")){
            Data.downImageIcon.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if(direction.equals("L")){
            Data.leftImageIcon.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if(direction.equals("R")){
            Data.rightImageIcon.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        //Painting body
        for (int i = 1; i < length; i++) {
            Data.bodyImageIcon.paintIcon(this,g,snakeX[i],snakeY[i]);
        }
        if (isFailed==true){
            g.setColor(Color.YELLOW);
            g.setFont(new Font("Microsoft YaHei ",Font.BOLD,28));
            if (count<500){
                g.drawString("Just eat so much! Press space to start again! score:"+count,200,400);
            }else if (count<1000){
                g.drawString("Are you full! Press space to start again! score:"+count,200,400);
            }else{
                g.drawString("Invincible!!! Press space to start again! score:"+count,200,400);
            }

        }
        if (isStart==false){
            g.setColor(Color.RED);
            g.setFont(new Font("Microsoft YaHei ",Font.BOLD,28));
            g.drawString("That's it? Start with a space!",300,400);
        }
    }
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode==KeyEvent.VK_SPACE){
            if (isFailed){
                isFailed = false;count =0;
            }else{
                isStart = !isStart;
            }
            repaint();
        }
        if(isStart==true && isFailed == false){
            if ((keyCode==KeyEvent.VK_UP || keyCode == KeyEvent.VK_W)&& direction!="D"){
                direction = "U";
            }else if ((keyCode==KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) && direction!="U"){
                direction = "D";
            }else if ((keyCode==KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) && direction!="R"){
                direction = "L";
            }else if ((keyCode==KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) && direction!="L"){
                direction = "R";
            }
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {
            if (isStart==true && isFailed==false){

                for (int i = 1; i < length; i++) {
                    //Food should not overlap with the body
                    if (foodX == snakeX[i] && foodY == snakeY[i]   ){
                        foodX = 25+25* random.nextInt(32);
                        foodY = 75+25* random.nextInt(24);

                    }
                    if (food2Y == snakeY[i] &&food2X == snakeX[i] ){
                        food2Y = 75+25* random.nextInt(23);
                        food2X = 25+25* random.nextInt(31);
                    }
                    //The head must not overlap the body
                    if (snakeX[0]==snakeX[i] && snakeY[0] ==snakeY[i]){
                        isFailed = true;
                        init();
                    }
                }

                //If the head coordinates are the same, it means that you have eaten the food. The length is increased by 1 and the score is increased by 20
                if (snakeX[0]==foodX && snakeY[0] == foodY){
                    length++;
                    count+=20;
                    foodX = 25+25* random.nextInt(32);
                    foodY = 75+25* random.nextInt(24);
                }else if (snakeX[0]==food2X && snakeY[0] == food2Y){
                    length+=5;count+=100;
                    food2X = 25+25* random.nextInt(32);
                    food2Y = 75+25* random.nextInt(24);
                    for (int i = 0; i < 5; i++) {
                        snakeX[length-1-i] = snakeX[length-6];
                        snakeY[length-1-i] = snakeY[length-6];
                    }
                }
                //The little snake moves
                for (int i = length-1; i >0 ; i--) {
                    snakeX[i] = snakeX[i-1];
                    snakeY[i] = snakeY[i-1];
                }
                //How do snakeheads move
                if (direction.equals("U")){
                    snakeY[0] -=25;
                }else  if (direction.equals("D")){
                    snakeY[0] +=25;
                }else  if (direction.equals("L")){
                    snakeX[0] -=25;
                }else  if (direction.equals("R")){
                    snakeX[0] +=25;
                }
                //Failed to hit the wall
                if (snakeX[0]==825 || snakeX[0]==0 || snakeY[0]==50 || snakeY[0]==675 ){
                    isFailed = true;
                    init();
                }
                repaint();
            }
    }





    @Override
    public void keyReleased(KeyEvent e) {

    }
    @Override
    public void keyTyped(KeyEvent e) {

    }
}

Tags: Java Back-end

Posted on Fri, 03 Dec 2021 21:00:44 -0500 by rdbdba