The Java greedy snake that the old programmer spent two days doing
introduction:
Everyone has one or even several great dreams in childhood. My childhood dream:
1. Monkey King, because I want to be a demon subduer and 72 changers. The most important thing is that I can go wherever I want and take off as soon as I follow!
2. Gourd babies, because when they are separated, they stand alone and have unique skills; When fit, it is perfect and invincible. If you want to be big, you will be big and if you want to be small, you will be small!
3. Militarist, I liked watching Anti Japanese TV dramas since I was a child. I felt that it was not easy for our country to come out of suffering. At that time, I hoped to become a militarist and defend our country!
4. Scientists, the teacher told us that scientists are the pillars of the country! I also hope to become an outstanding scientist and improve the science and technology of our country.
5. Engineer, become an excellent engineer, can build our country!
With these dreams, after more than ten years of hard study, I came to the city from the countryside, went out of school, came to the society, and became an IT Engineer.
This is also good. At least it can be regarded as completing the childhood dream. Although it is not very excellent, it is also very hard. IT engineers are also engineers!
And you? Guys, you can leave a message about your dreams and let everyone croak!
What I want to do now:
1. To do well in one's own post is to contribute to the country!
2. Take a small AD and turn it into 200 kg. It's very Carry and flying feathers can kill the enemy!
This is not small. Ad asked me to take the upper score, because my weight is less than 90 kg. How did I play? So I decided to fatten AD and turn ad from a water snake into a python!
Small AD:_ Brother Ming, take me up! Come on, it's numb
Ming Shiyin: what hero do you play?
Little AD: my new hero is very powerful. Guess!
Ming Shiyin: Yuan Fang? The thief is fierce. I bet there are no bullets in your gun!
Small AD: No, the attack speed is very fast.
Ming Shiyin: Di Renjie? It's time for arrest!
Little AD: someone else's cannon.
Ming Shiyin: Huang Zhong? A cannon, tough life does not need explanation!
Little AD: no, very cute.
Mingshiyin: Miss Rabbit ear, do you want one? It's enough for you.
Little AD: it's little Luban.
Ming Shiyin: that's it. Does anyone need technical support; IQ 250. I see. No wonder you can't score. Let me recommend you a new hero.
Little AD: what hero?
Ming Shiyin: the disaster of Python - Godzilla.
Little AD: No, what? Seems familiar, the name sounds a little fierce (du)
Mingshiyin: let's go. I'll take you to practice level first!
Little AD: OK
design sketch
Let's start with the final rendering. The interface here doesn't look very good, but I don't think it's a big problem. Just put the functions in place!
Realization idea
Two canvases:
Canvas 1: it is used to draw static things, such as game area border, grid, scoring area box, time box, button, etc., which do not need to be refreshed.
Canvas 2: used to draw dynamic parts of the game, such as snakes, snake movement, food, snake eating food growth, integral display, time update, etc.
code implementation
create a window
First, create a game form class GameFrame, which is inherited to JFrame and used to display on the screen (window object). Each game has a window. Set the window title, size, layout, etc.
/* * Game form class */ public class GameFrame extends JFrame { public GameFrame() { setTitle("Greedy snake");//Set title setSize(788, 476);//Set size getContentPane().setBackground(new Color(169,169,169));//Add background setLayout(new BorderLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Click the close button to close the program setLocationRelativeTo(null); //Set center setResizable(false); //Modifying the interface size is not allowed } }
Little AD: brother Ming, what are you doing? Didn't you take me to practice heroes?
Ming Shiyin: Yes, I'm warming up. Wait!
Little AD: Oh.
Canvas 1
Create panel container BackPanel inherit to JPanel
/* * Background canvas class */ public class BackPanel extends JPanel{ BackPanel panel=this; private JFrame mainFrame=null; //Initialization related parameters in the structure public BackPanel(JFrame frame){ this.setLayout(null); this.setOpaque(false); this.mainFrame = frame; mainFrame.setVisible(true); } }
Create another Main class to start the window.
public class Main { //Main class public static void main(String[] args) { GameFrame frame = new GameFrame(); BackPanel panel = new BackPanel(frame); frame.add(panel); frame.setVisible(true);//Set display } }
Right click to execute the Main class, and the window is created
Little AD: brother, are you playing games?
Ming Shiyin: No, I'm taking you to play wild and upgrade!
Little AD: are you really playing games?
Mingshiyin: Oh, no, I'm taking you to fight wild upgrade!
Little AD: brother, can you really do this?
Mingshiyin: I want to train you into a 200kg ADC
Little AD: I'll go to you. I'll find you if I can't get married.
Ming Shiyin: OK, I have many fans. You can choose one to take home at that time. I'll send you red envelopes! You give happy candy!
Little AD: brother Ming is really good!
Create menu and menu options
create menu
private void initMenu(){ // Create menu and menu options jmb = new JMenuBar(); JMenu jm1 = new JMenu("game"); jm1.setFont(new Font("Imitation Song Dynasty", Font.BOLD, 15));// Set the font displayed in the menu JMenu jm2 = new JMenu("help"); jm2.setFont(new Font("Imitation Song Dynasty", Font.BOLD, 15));// Set the font displayed in the menu JMenuItem jmi1 = new JMenuItem("Start a new game"); JMenuItem jmi2 = new JMenuItem("sign out"); jmi1.setFont(new Font("Imitation Song Dynasty", Font.BOLD, 15)); jmi2.setFont(new Font("Imitation Song Dynasty", Font.BOLD, 15)); JMenuItem jmi3 = new JMenuItem("Operating instructions"); jmi3.setFont(new Font("Imitation Song Dynasty", Font.BOLD, 15)); JMenuItem jmi4 = new JMenuItem("Failure judgment"); jmi4.setFont(new Font("Imitation Song Dynasty", Font.BOLD, 15)); jm1.add(jmi1); jm1.add(jmi2); jm2.add(jmi3); jm2.add(jmi4); jmb.add(jm1); jmb.add(jm2); mainFrame.setJMenuBar(jmb);// Put menu Bar on JFrame jmi1.addActionListener(this); jmi1.setActionCommand("Restart"); jmi2.addActionListener(this); jmi2.setActionCommand("Exit"); jmi3.addActionListener(this); jmi3.setActionCommand("help"); jmi4.addActionListener(this); jmi4.setActionCommand("lost"); }
Implement ActionListener and override the method actionPerformed
Implementation of actionPerformed method
@Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); System.out.println(command); UIManager.put("OptionPane.buttonFont", new FontUIResource(new Font("Song style", Font.ITALIC, 18))); UIManager.put("OptionPane.messageFont", new FontUIResource(new Font("Song style", Font.ITALIC, 18))); if ("Exit".equals(command)) { Object[] options = { "determine", "cancel" }; int response = JOptionPane.showOptionDialog(this, "Are you sure you want to exit", "", JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (response == 0) { System.exit(0); } }else if("Restart".equals(command)){ if(!"end".equals(gamePanel.gameFlag)){ JOptionPane.showMessageDialog(null, "Cannot restart in the game!", "Tips!", JOptionPane.INFORMATION_MESSAGE); }else{ if(gamePanel!=null) { gamePanel.restart(); btnStart.setText("suspend"); } } }else if("help".equals(command)){ JOptionPane.showMessageDialog(null, "[lower][S],[Left][A],[right][D],[upper][W]Control direction", "Tips!", JOptionPane.INFORMATION_MESSAGE); }else if("lost".equals(command)){ JOptionPane.showMessageDialog(null, "If a snake bites itself, it will fail!", "Tips!", JOptionPane.INFORMATION_MESSAGE); }else if("start".equals(command)){ mainFrame.requestFocus(); if("start".equals(gamePanel.gameFlag)){//Enter pause gamePanel.pause(); btnStart.setText("continue"); }else if("pause".equals(gamePanel.gameFlag)){//Enter continue gamePanel.goOn(); btnStart.setText("suspend"); }else if("end".equals(gamePanel.gameFlag)){//Enter reopen gamePanel.restart(); btnStart.setText("suspend"); } } }
Draw game area
Draw game area border
//bound box private void drawBorder(Graphics g) { BasicStroke bs_2=new BasicStroke(12L,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER); Graphics2D g_2d=(Graphics2D)g; g_2d.setColor(new Color(128,128,128)); g_2d.setStroke(bs_2); RoundRectangle2D.Double rect = new RoundRectangle2D.Double(6, 6, 613, 413, 2, 2); g_2d.draw(rect); }
Draw the auxiliary area on the right
//Draw the right area border private void drawBorderRight(Graphics g) { BasicStroke bs_2=new BasicStroke(12L,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER); Graphics2D g_2d=(Graphics2D)g; g_2d.setColor(new Color(128,128,128)); g_2d.setStroke(bs_2); RoundRectangle2D.Double rect = new RoundRectangle2D.Double(636, 6, 140, 413, 2, 2); g_2d.draw(rect); }
Override the paint method in the BackPanel and call the two area drawing methods just now.
Draw integral area
//Draw integral area private void drawCount(Graphics g) { BasicStroke bs_2=new BasicStroke(3L,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER); Graphics2D g_2d=(Graphics2D)g; g_2d.setColor(new Color(70,70,70)); g_2d.setStroke(bs_2); g_2d.drawRect(650, 17, 110, 80); //score g.setFont(new Font("Song style", Font.BOLD, 20)); g.drawString("score:",680, 40); }
Draw time area
//Draw time area private void drawTime(Graphics g) { BasicStroke bs_2=new BasicStroke(3L,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER); Graphics2D g_2d=(Graphics2D)g; g_2d.setColor(new Color(70,70,70)); g_2d.setStroke(bs_2); g_2d.drawRect(650, 120, 110, 120); //time g.setFont(new Font("Song style", Font.BOLD, 20)); g.drawString("Time:",680, 140); }
Draw grid (30 columns and 20 rows)
//Draw mesh private void drawGrid(Graphics g) { Graphics2D g_2d=(Graphics2D)g; g_2d.setColor(new Color(255,255,255,150)); int x1=12; int y1=20; int x2=612; int y2=20; for (int i = 0; i <= ROWS; i++) { y1 = 12 + 20*i; y2 = 12 + 20*i; g_2d.drawLine(x1, y1, x2, y2); } y1=12; y2=412; for (int i = 0; i <= COLS; i++) { x1 = 12 + 20*i; x2 = 12 + 20*i; g_2d.drawLine(x1, y1, x2, y2); } }
Call in the paint method
Create a pause button in the right area of the game
//initialization private void init() { // Start / stop button btnStart = new JButton(); btnStart.setFont(new Font("Blackbody", Font.PLAIN, 18)); btnStart.setFocusPainted(false); btnStart.setText("suspend"); btnStart.setBounds(660, 300, 80, 43); btnStart.setBorder(BorderFactory.createRaisedBevelBorder()); this.add(btnStart); btnStart.addActionListener(this); btnStart.setActionCommand("start"); }
The basic layout is now complete.
Little AD: brother Ming, what game is this!
Ming Shiyin: AD take-off games.
Little AD: This..., It seems that I have to learn.
Mingshiyin: I can't say that. Am I the kind of person who forces others to learn.
Little AD: brother Ming is really a good man!
Ming Shiyin: Thank you for your compliment. Let's continue.
Canvas 2
GamePanel inherits from JPanel and overrides the paint method
Modify the Main class and put the canvas 2 in the window
public class Main { //Main class public static void main(String[] args) { GameFrame frame = new GameFrame(); BackPanel panel = new BackPanel(frame); frame.add(panel); GamePanel gamePanel = new GamePanel(frame); panel.setGamePanel(gamePanel); frame.add(gamePanel); frame.setVisible(true);//Set display } }
Canvas 2 draws a small square
Because the game area is divided into small grids, each small grid is a unit, and the whole grid is a two-dimensional array of 30 and 20.
Therefore, the first element in the first row, represented by the array subscript, is 0,0, and the second element in the first row is 0,1
In this way, it is easy to do. We create a Block class and set the coordinates and width height to draw the box (the width height is fixed at 20, which corresponds to the grid).
package main; import java.awt.Graphics; public class Block { private int x=0; private int y=0; private GamePanel panel=null; private String dir = "right"; //Default right private int step = 1; public Block(int x,int y,GamePanel panel){ this.x=x; this.y=y; this.panel=panel; } //draw void draw(Graphics g){ g.fillRect(12+x*20, 12+y*20, 20, 20); } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
Instantiate this class and invoke draw rendering in the paint method.
//Create small squares private void createClock() { int x=0; int y=0; Block block = new Block(x, y,this); curBlock=block; }
@Override public void paint(Graphics g) { super.paint(g); if(curBlock!=null){ curBlock.draw(g); } }
The renderings are as follows:
Add a method to set the direction in the Block class
Of course, we should limit that we can't reverse it, because the greedy Snake game doesn't run such an operation.
public void setDir(String dir){ //Ensure that reverse operation is not allowed if("right".equals(dir) && "left".equals(this.dir)){ return ; } if("left".equals(dir) && "right".equals(this.dir)){ return ; } if("up".equals(dir) && "down".equals(this.dir)){ return ; } if("down".equals(dir) && "up".equals(this.dir)){ return ; } this.dir=dir; }
GamePanel add keyboard event
//Add keyboard monitor private void createKeyListener() { KeyAdapter l = new KeyAdapter() { //Press @Override public void keyPressed(KeyEvent e) { if(!"start".equals(gameFlag)) return ; int key = e.getKeyCode(); switch (key) { //Upward case KeyEvent.VK_UP: case KeyEvent.VK_W: if(curBlock!=null) curBlock.setDir("up"); break; //towards the right case KeyEvent.VK_RIGHT: case KeyEvent.VK_D: if(curBlock!=null) curBlock.setDir("right"); break; //down case KeyEvent.VK_DOWN: case KeyEvent.VK_S: if(curBlock!=null) curBlock.setDir("down"); break; //towards the left case KeyEvent.VK_LEFT: case KeyEvent.VK_A: if(curBlock!=null) curBlock.setDir("left"); break; } } //release @Override public void keyReleased(KeyEvent e) { } }; //Add keyboard monitoring to the main frame mainFrame.addKeyListener(l); }
Create a move method in the Block class
Variable description:
xDir Boolean value: true indicates horizontal movement, false indicates up and down movement;
step is the number of steps: when xDir is true, we set it to 1 and - 1 to move horizontally, 1 to the right and - 1 to the left; When xDir is false, move down to 1 and move up to - 1.
Method description:
1. If xdir is true, let x+step;
2. On the contrary, if xDir is false, let y+step;
3. Perform redrawing to move.
//move void move(){ boolean xDir = false;//Whether to move horizontally if("right".equals(dir) || "left".equals(dir) ){//about xDir = true; if("right".equals(dir)){//right step=1; }else { step=-1; } }else if("up".equals(dir) || "down".equals(dir) ){//Up and down xDir = false; if("down".equals(dir)){//lower step=1; }else { step=-1; } } if(xDir){//Move in the X direction, step positive number to the right, negative number to the left x += step; }else{//For the movement in Y direction, step is positive downward and negative upward y += step; } panel.repaint(); }
Call the move method (thread)
//Game thread, used to automatically move private class GameThread implements Runnable { @Override public void run() { while (true) { if("start".equals(gameFlag)){ curBlock.move(); } try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Start the thread in the GamePanel
mainThread = new Thread(new GameThread()); mainThread.start();
After startup, it moves to the right by default. I can control the direction by pressing the up, down, left and right keys.
Little AD: brother Ming, you're so good. How did you learn it? What can I recommend for my thin ADC?
Ming Shiyin: Yes, I got a set of "knowledge atlas of learning and growth of Java engineers" from CSDN officials. The size is 870mm x 560mm. After unfolding, it is the size of a desk and can also be folded into the size of a book. The original is 129 yuan and the current price is 29 yuan.
Little AD: can I do the same?
Ming Shiyin: Yes, this picture is in hand. I have java to help Xiaobai advance from zero to an advanced Java Engineer. Interested partners can learn about it!
Draw snake
Just a small square is definitely not enough. The characteristics of greedy snakes are as follows:
1. Snakehead - direction key to control movement
2. Snake body - follow the snake head
3. Increase the snake's body length after eating the real thing
Snake class
Snake is composed of small blocks, so you can use a List set to store multiple blocks.
In view of the above three points, I think:
1. The snakehead completely uses the Block instance, because the Block instance can meet the movement of the snakehead. We can add a color to the snakehead.
2. The snake's body moves with the snake's head. Starting from the end of the snake's body (the last element of the collection), set the position of each box to the position of the previous box. To achieve the effect of moving. The snake head moves by itself.
3. When you eat the real thing, create a block instance and add it to the end of the collection to increase the snake's body.
Draw snake
public class Snake { private List blocks = new ArrayList(); private GamePanel panel = null; private Block head=null; public Snake(GamePanel panel){ this.panel=panel; //Initialize snake initSnake(); } //Initialize snake private void initSnake() { //Snakehead head = createClock(1,0,Color.red); //Snake body createClock(0,0,null); } //Create small squares private Block createClock(int x,int y,Color color) { Block block = new Block(x, y,color,panel); blocks.add(block); return block; } //draw void draw(Graphics g){ Block block = null; for (int i = 0; i < blocks.size(); i++) { block = (Block)blocks.get(i); block.draw(g); } } }
The above code is easy to understand. By default, a snake head is created in 1,0, and a snake body is created in 0,0.
Create an instance of Snake in GamePanel and call it in the paint method (the original block code is to be written off).
private void createSnake() { snake = new Snake(this); }
public void paint(Graphics g) { super.paint(g); //curBlock.draw(g); if(snake!=null){ snake.draw(g); } }
At this time, the red snake head and the black snake body are drawn.
Snake Movement
1. Move the body and assign the position of the previous box to the next one (in reverse order)
2. The head moves alone
//move void move(){ //Snake body movement //Take one of the positions of the latter (in reverse order) Block body = null; Block lastBody = null; for (int i = blocks.size()-1; i >=1; i--) { body = (Block)blocks.get(i); lastBody = (Block)blocks.get(i-1); body.setX(lastBody.getX()); body.setY(lastBody.getY()); } //Snake head moves alone if(head!=null) head.move(); //Repainting does not need to be invoked in block. panel.repaint(); }
Modify the moving method of snake in the thread
//Game thread, used to automatically move private class GameThread implements Runnable { @Override public void run() { while (true) { if("start".equals(gameFlag)){ if(snake!=null) snake.move(); //curBlock.move(); } try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Little AD: that's the disaster of Python?
Ming Shiyin: isn't this when he was a child? What's the hurry!
Little AD: I believe you. Are you sure it's not lady gaga?
Ming Shiyin: even if it is, it is also a boy snake!
Little AD: why do you only go to the right.
Mingshiyin: look at me.
Set the direction according to the keyboard, just set the direction of the snake head, because the snake body automatically follows.
//Set direction public void setDir(String dir){ if(head!=null) head.setDir(dir); }
In the GamePanel, the keyboard monitoring is slightly modified (originally the monitoring box, now the monitoring snake)
//Add keyboard monitor private void createKeyListener() { KeyAdapter l = new KeyAdapter() { //Press @Override public void keyPressed(KeyEvent e) { if(!"start".equals(gameFlag)) return ; int key = e.getKeyCode(); switch (key) { //Upward case KeyEvent.VK_UP: case KeyEvent.VK_W: //if(curBlock!=null) curBlock.setDir("up"); if(snake!=null) snake.setDir("up"); break; //towards the right case KeyEvent.VK_RIGHT: case KeyEvent.VK_D: // if(curBlock!=null) curBlock.setDir("right"); if(snake!=null) snake.setDir("right"); break; //down case KeyEvent.VK_DOWN: case KeyEvent.VK_S: // if(curBlock!=null) curBlock.setDir("down"); if(snake!=null) snake.setDir("down"); break; //towards the left case KeyEvent.VK_LEFT: case KeyEvent.VK_A: // if(curBlock!=null) curBlock.setDir("left"); if(snake!=null) snake.setDir("left"); break; } } //release @Override public void keyReleased(KeyEvent e) { } }; //Add keyboard monitoring to the main frame mainFrame.addKeyListener(l); }
Little AD: it's a bit like the king's left and right operation.
Ming Shiyin: that's not true
Little AD: but it just swims around. I think of Teletubbies.
Ming Shiyin: Well, yes, just like you can't get out of the tower when you're pressed under the tower, Meng.
Little AD: you...
Ming Shiyin: I'll make two wild monsters and upgrade it.
Little AD: Well, you really have (dou) talent (bi)
Draw food
Draw an ellipse instead of the egg effect
public class Food { private int x=0; private int y=0; private GamePanel panel=null; public Food(int x,int y,GamePanel panel){ this.x=x; this.y=y; this.panel=panel; } //draw void draw(Graphics g){ Color oColor = g.getColor(); g.setColor(new Color(252,246,219)); //ellipse //g.drawOval(12+x*20+1, 12+y*20+2, 18, 14); g.fillOval(12+x*20+1, 12+y*20+4, 18, 12); g.setColor(oColor); } }
Create and draw the egg in GamePanel.
private void createFood() { food = new Food(0, 1, this); }
@Override public void paint(Graphics g) { super.paint(g); //curBlock.draw(g); if(snake!=null){ snake.draw(g); } if(food!=null){ food.draw(g); } }
Eat food
First modify the place where the food was created just now to random x and y positions (but judge the position of the snake and its body every time you create it. If so, re random recursion).
//Create physical object private void createFood() { int[][] res = getPos(); int x = res[0][0]; int y = res[0][1]; food = new Food(x, y, this); } //Get random coordinates public int[][] getPos(){ Random random = new Random(); int x = random.nextInt(30); int y = random.nextInt(20); int[][] res = new int[1][2]; if(checkPos(x, y)){//recursion return getPos(); }else { res[0][0]=x; res[0][1]=y; return res; } } //Judge whether the coordinates of the real object overlap with the snake private boolean checkPos(int x,int y){ if(snake!=null){ List blocks = snake.getBlocks(); Block block = null; for (int i = 0; i < blocks.size(); i++) { block = (Block)blocks.get(i); if(block.getX()==x && block.getY()==y){//Overlap with snake position return true; } } } return false; }
When the snake head moves, if the x and y of the snake head are the same as those of the food, it is judged that it has been eaten
//Judge to eat public void eat() { if(head==null) return ; Food food = panel.food; if(head.getX()==food.getX() && head.getY()==food.getY()){//Yes doEat(); } }
Several things to do after eating:
1. Re random location of food
2. Integral plus 10
3. Add a grid to the snake and put it at the end of the set (so first record the x and y coordinates of the last grid at the tail of the snake).
Modify the move method in Snake and record the x and y coordinates of the last grid
//move void move(){ //Snake body movement //Take one of the positions of the latter (in reverse order) Block body = null; Block lastBody = null; for (int i = blocks.size()-1; i >=1; i--) { body = (Block)blocks.get(i); lastBody = (Block)blocks.get(i-1); //Record the moving X\Y coordinates of the last grid if(i==blocks.size()-1){ lastX = body.getX(); lastY = body.getY(); } body.setX(lastBody.getX()); body.setY(lastBody.getY()); } //Snake head moves alone if(head!=null) head.move(); //eat eat(); //Repainting does not need to be invoked in block. panel.repaint(); }
Perform the action of eating
//Perform the action of eating private void doEat() { /* * 1.Food re random location * 2.Integral plus 10 * 3.The snake adds a grid and puts its body at the end of the collection. */ Food food = panel.food; //1. Re random location of food int[][] res = panel.getPos(); int x = res[0][0]; int y = res[0][1]; food.setX(x); food.setY(y); //2. Integral plus 10 panel.curCount+=10; //3. The snake adds a grid and puts its body at the end of the collection. Block block = createClock(lastX,lastY,null); blocks.add(block); }
Run it
Little AD: just hit your face.
Ming Shiyin: Well, yes, don't you like riding an assassin's face?
Little AD: too much.
Ming Shiyin: you can take it as fighting wild monsters. Eat one and upgrade to level 1. Then it will be longer and longer.
Little AD: it's getting longer and longer.
Ming Shiyin: Um... (corners of mouth up)
Boundary treatment
1. If the snake head crosses the boundary, re-enter from the other side. The code is very simple.
2. Call this method in the move method.
//Out of bounds processing private void outside() { if(head==null) return ; //Out of bounds, enter again from the other side if(head.getX()<0){ head.setX(29); }else if(head.getX()>29){ head.setX(0); }else if(head.getY()<0){ head.setY(19); }else if(head.getY()>19){ head.setY(0); } }
Little AD: don't you open a plug-in? You can come back when you get out of the map.
Ming Shiyin: Well, yes, my programmer is so awesome b? Disobedience
Little AD: I won't accept it.
Mingshiyin: if you don't accept it, I can let it bite itself.
Little AD: come on
The snake bit itself
1. Compare the snake head with the snake body. Once x and y are the same, the game is over.
2. Call this method in the move method.
//Bit yourself private void eatSelf() { if(head==null) return ; Block body = null; for (int i = blocks.size()-1; i >=1; i--) { body = (Block)blocks.get(i); if(body.getX() == head.getX() && body.getY() == head.getY()){//The head overlaps the body panel.gameOver(); break; } } }
last
Join time, end of game, restart, etc
Seeing the big guys here, it's better to use the small hands of making a fortune to point out praise + reply + collection. It's better to pay attention to one wave.
If you want code, add wechat or chat with me in private!
Little AD played
Little AD: Wow, brother Ming, it's getting longer and more fun!
Mingshiyin: it's much more fun than standing under the tower!
Little AD: now I feel like the disaster of Python.
Ming Shiyin: how about following brother Ming? You can learn code easily and have fun!
Little AD: but a lot of knowledge needs to be learned. It's a little messy. I don't know how to learn.
Ming Shiyin: so I got the following atlas from CSDN.
In order to help more Xiaobai advance from zero to advanced Java engineers, we got a set of "Atlas of Java engineers' learning and growth knowledge" from CSDN officials, with a size of 870mm x 560mm. After unfolding, it is the size of a desk, which can also be folded into the size of a Book. The original is 129 yuan, and the current price is 29 yuan. First come, first served. Interested partners can learn about it!