“This is the second day of my participation in the First Challenge 2022.

❤️ Author’s home page: Xiao Xu Zhu

❤️ About the author: Hello everyone, I am Xiao Xu Zhu. Java field quality creator 🏆, CSDN blog expert 🏆, Huawei cloud enjoy expert 🏆, Nuggets of the year popular author 🏆, Ali Cloud expert blogger 🏆

❤️ technology live, the appreciation

❤️ like 👍 collect ⭐ look again, form a habit

preface

Snake (also known as Snake) is a casual puzzle game available for PC and mobile. Easy and fun to play. The game makes snakes grow longer and longer by directing their heads to eat.

This procedure is through Java swing to achieve “Snake battle” this game.

The main requirements

1, by controlling the direction of the snake up, down, left and right, looking for food, each bite can get a certain number of points, the snake’s body will become longer

When the head of the snake touches his body, it fails

The main design

1. Set the swing form size

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 direction keys up and down to control the movement of the snake

5. When the snake is running, the head takes a step forward, adding a head node and removing 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, statistics snake length and integral, eat a food, snake length +1, integral +10

9. Start/pause the game by pressing the space button

Screenshot function

Code implementation

Start the class

public class StartGame {
​
    public static void main(String[] args) {
        JFrame jf=new JFrame("Battle of the Snake");
        jf.setBounds(100.100.905.720);
        jf.setResizable(false);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.add(new GamePanel());
        jf.setVisible(true); }}Copy the code

Game Core

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;// Add a coordinate after eating food
	// The target's data structure
	int foodx,foody;
	/ / random number
	Random random =new Random();
	/ / timer
	Timer timer=new Timer(100.this);
	
	int score;
	
	public GamePanel(a){
		init();
		// Add keyboard listener
		this.addKeyListener(this);
		// You must set focus to listen for keyboard events
		this.setFocusable(true);
		timer.start();
	}
	public void init(a){
		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 it doesn't flicker
		this.setBackground(Color.white);
		Data.headicno.paintIcon(this, g, 25.11);
		g.setColor(new Color(104.197.107));
		g.fillRect(25.75.850.600);
		// Snake head drawing
		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]);
		}
		// Food drawing
		Data.foodicon.paintIcon(this, g, foodx, foody);
		// Pause the drawing of the start state
		if(isStart==false){
			g.setFont(new Font(Microsoft Yahei,Font.BOLD,40));
			g.setColor(Color.WHITE);
			g.drawString("Press space to start/pause the game".275.350);
		}
		// Fail to draw
		if(isfail==true){
			g.setFont(new Font(Microsoft Yahei,Font.BOLD,40));
			g.setColor(Color.red);
			g.drawString("The failure! Press space to restart".275.350);
		}
		// Draw the 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);
	}
	// Implement keyboard listening interface methods
	@Override
	public void keyPressed(KeyEvent e) {
		int keycode=e.getKeyCode();
		// The space bar pauses or restarts
		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 decision
			for(int i=1; i<length; ++i){if(snakex[i]==snakex[0]&&snakey[i]==snakey[0]){
					isfail=true; }}/ / to 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 the code

conclusion

Through the “Snake battle” game implementation, let me have a further understanding of swing related knowledge, the Language of Java has a deeper understanding than before.

Basic Java syntax, such as data types, operators, program flow control, and arrays, is better understood. Java is the core of the core object oriented thought, for this concept, finally realized some.

The source code for

You can follow the blogger and contact the blogger