JAVA to achieve the classic "snake battle" game (JAVA little bamboo)

Posted by aspbyte on Sun, 23 Jan 2022 08:13:00 +0100

preface

Greedy snake (also known as greedy snake) game is a leisure puzzle game with multi platform versions such as PC and mobile phone. Simple and playable. The game makes the snake longer and longer by controlling the direction of the snake's head to eat.

This program is through java swing to realize the game "snake battle".

Main demand

1. By controlling the direction of the snake up, down, left and right and looking for food, you can get certain points for each bite, and the snake's body will grow

2. If a snake's head touches his own body, it is considered a failure

Main design

1. Set the form size of swing

2. Randomly initialize the position of the snake and the position of the food, and the food cannot fall on the snake's body.

4. Add a keyboard listener to monitor the up, down, left and right direction keys to control the up, down, left and right movement of the snake

5. When the snake is running, the head takes a step forward, adds a head node and removes the tail node.

6. After the snake eats a food, a node is added to the tail node of the snake, and the food disappears.

7. Every time the food is eaten by the snake, a new food node should be randomly generated again.

8. There is a counter to count the length and integral of the snake. If you eat a food, the length of the snake + 1 and the integral + 10

9. Start / pause the game by pressing space

Function screenshot

code implementation

Startup class

​
public class StartGame {
​
    public static void main(String[] args) {
        JFrame jf=new JFrame("Snake Wars");
        jf.setBounds(100, 100, 905, 720);
        jf.setResizable(false);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.add(new GamePanel());
        jf.setVisible(true);
    }
​
}
​
Copy code

Game core class

public class GamePanel extends JPanel implements KeyListener,ActionListener{
	//Snake data structure
	static int i=0;
	int length;
	int[] snakex=new int[600];
	int[] snakey=new int[600];
	String fx;
	boolean isStart=false;
	boolean isfail=false;
	int lx,ly;//One more coordinate after eating food
	//Target data structure
	int foodx,foody;
	//random number
	Random random =new Random();
	//timer
	Timer timer=new Timer(100, this);
	
	int score;
	
	public GamePanel(){
		init();
		//Add keyboard listener
		this.addKeyListener(this);
		//You must set that you can get focus to listen to keyboard events
		this.setFocusable(true);
		timer.start();
	}
	public void init(){
		score=0;
		length=3;
		snakex[0]=100;snakey[0]=100;
		snakex[1]=75;snakey[1]=100;
		snakex[2]=50;snakey[2]=100;
		fx="R";
		foodx=25+25*random.nextInt(850/25);
		foody=75+25*random.nextInt(600/25);
	}

	protected void paintComponent(Graphics g) {
		super.paintComponent(g);//Clear the screen so that it won't flash
		this.setBackground(Color.white);
		Data.headicno.paintIcon(this, g, 25, 11);
		g.setColor(new Color(104,197,107));
		g.fillRect(25, 75, 850, 600);
		//Drawing of snake head
		if(fx.equals("U")){
			Data.upicno.paintIcon(this, g, snakex[0], snakey[0]);
		}else if(fx.equals("D")){
			Data.downicno.paintIcon(this, g, snakex[0], snakey[0]);
		}else if(fx.equals("L")){
			Data.lefticno.paintIcon(this, g, snakex[0], snakey[0]);
		}else if(fx.equals("R")){
			Data.righticno.paintIcon(this, g, snakex[0], snakey[0]);
		}
		//Snake body drawing
		for(int i=1;i<length;++i){
			Data.bodyicno.paintIcon(this, g, snakex[i], snakey[i]);
		}
		//Drawing of food
		Data.foodicon.paintIcon(this, g, foodx, foody);
		//Pause drawing in start state
		if(isStart==false){
			g.setFont(new Font("Microsoft YaHei ",Font.BOLD,40));
			g.setColor(Color.WHITE);
			g.drawString("Start with a space/Pause the game", 275, 350);
		}
		//Drawing of failure conditions
		if(isfail==true){
			g.setFont(new Font("Microsoft YaHei ",Font.BOLD,40));
			g.setColor(Color.red);
			g.drawString("fail!Press space to restart", 275, 350);
		}
		//Drawing of integral
		g.setColor(Color.PINK);
		g.setFont(new Font("Microsoft YaHei ", Font.ITALIC, 15));
		g.drawString("length: "+length, 800, 30);
		g.drawString("integral: "+score, 800, 55);
	}
	//Interface method for realizing keyboard monitoring
	@Override
	public void keyPressed(KeyEvent e) {
		int keycode=e.getKeyCode();
		//Spacebar pause or restart
		if(keycode==KeyEvent.VK_SPACE){
			if(isfail==true){
				System.out.println(1);
				init();
				isfail=false;
			}
			else{
				System.out.println(2);
				isStart=!isStart;
				repaint();
			}
		}
		//Up, down, left and right
		if(keycode==KeyEvent.VK_UP){
			fx="U";
		}else if(keycode==KeyEvent.VK_DOWN){
			fx="D";
			//System.out.println("down");
		}else if(keycode==KeyEvent.VK_LEFT){
			fx="L";
		}else if(keycode==KeyEvent.VK_RIGHT){
			fx="R";
		}
	}
	@Override
	public void keyReleased(KeyEvent e) {}
	@Override
	public void keyTyped(KeyEvent e){}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(isStart==true&&isfail==false){
			
			//Body movement
			lx=snakex[length-1];
			ly=snakey[length-1];
			for(int i=length-1;i>0;--i){
				snakex[i]=snakex[i-1];
				snakey[i]=snakey[i-1];
			}
			//Head movement
			if(fx=="U"){
				snakey[0]-=25;
				if(snakey[0]<75)snakey[0]=650;
			}else if(fx=="D"){
				snakey[0]+=25;
				if(snakey[0]>650)snakey[0]=75;
			}else if(fx=="L"){
				snakex[0]-=25;
				if(snakex[0]<25)snakex[0]=850;
			}else if(fx=="R"){
				snakex[0]+=25;
				if(snakex[0]>850)snakex[0]=25;
			}
			//Failure judgment
			for(int i=1;i<length;++i){
				if(snakex[i]==snakex[0]&&snakey[i]==snakey[0]){
					isfail=true;
				}
			}
			//Eat food
			if(snakex[0]==foodx&&snakey[0]==foody){
				length++;
				score+=10;
				snakex[length-1]=lx;
				snakey[length-1]=ly;
				foodx=25+25*random.nextInt(850/25);
				foody=75+25*random.nextInt(600/25);
			}
			repaint();
		}
		
	}
	
}

Copy code

summary

Through the implementation of the game of "snake wars", I have a further understanding of the relevant knowledge of swing and a deeper understanding of the language java than before.

Some of the basic syntax of java, such as data types, operators, program flow control and arrays, are better understood. The core of java is the object-oriented idea. I finally realized some ideas about this concept.

Topics: Java Game Development