@[TOP](Greedy Snake)
Java development Snake games
1, Development ideas
-
Set a certain size and immutable game window
-
Draw the basic panel style of the game on the created window
-
Draw a static snake using the saved material icon in advance
-
Enable the snake to move; In fact, only the snake head coordinates need to move, and each body section covers the body coordinates of the previous section. Set the Timer timer =new Timer(); Monitoring time allows the snake to move
-
Monitor the keyboard operation, so that the user can control the direction of the snake through the keyboard
-
Define a food coordinate and realize the random generation of food with random random number class
-
When the snake eats food, its body length is + 1. In fact, when the snake head coordinates coincide with the food coordinates
-
boolean Defines the judgment of game failure. When the snake head coincides with the coordinates of any body part (or hits the boundary), the game fails. You can set up the integral system and add a certain score for each food you eat
2, Specific development process
1. Draw a static game window
JFrame jFrame = new JFrame("Greedy Snake");//Draw a static window jFrame.setBounds(10,10,900,720);//Set interface size jFrame.setResizable(false);//The window size cannot be changed jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//Set window close event jFrame.setVisible(true);//Window display jFrame.add(new GamePanel());//Add panel to window
2. Import material Icon
public class Data { public static URL headerUrl = Data.class.getResource("/statics/header.png");//Locate picture address public static ImageIcon header =new ImageIcon(headerUrl);//Draw pictures by picture address }
3. Draw the game panel
@Override protected void paintComponent(Graphics g) { //Graphics: Brush super.paintComponent(g);//Clear screen this.setBackground(Color.darkGray);//Set background color Data.header.paintIcon(this,g,25,11);//Draw header billboard g.fillRect(25,75,850,600);//Draw game area
4. Draw a static snake
definition
int length;//Snake length int[] snakeX=new int[600]; int[] snakeY=new int[500];//Snake coordinates String dir;//Head direction boolean isStart=false; boolean isFail for (int j = 1; j < length; j++) { if (snakeX[j]==snakeX[0]&&snakeY[j]==snakeY[0]){ isFail=true; } } repaint();=false;
draw
if (dir.equals("R")) { Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); } else if (dir.equals("L")){ Data.left.paintIcon(this,g,snakeX[0],snakeY[0]); }else if (dir.equals("U")){ Data.up.paintIcon(this,g,snakeX[0],snakeY[0]); }else if (dir.equals("D")){ Data.down.paintIcon(this,g,snakeX[0],snakeY[0]); }//Head (up, down, left and right) for (int i = 1; i < length; i++) { Data.body.paintIcon(this,g,snakeX[i],snakeY[i]); }//Draw body length by looping
5. Let the snake move
① Monitor keyboard input
Implement the Keylistener interface and override the KeyPressed() method (press the keyboard)
public void keyPressed(KeyEvent e) { //Keyboard pressed not released int keyCode = e.getKeyCode(); if(keyCode==KeyEvent.VK_SPACE){//Space bar if (isFail){ isFail=false; init();//Reinitialize }else {//Pause the game isStart=!isStart; } repaint();//Refresh interface } }
② Construct timer listening time
Timer timer =new Timer(50,this);//timer
③ Implement ActionListener interface (event listening)
Override actionPerformed(ActionEvent e) method
@Override public void actionPerformed(ActionEvent e) { if(isStart && isFail==false){//The game is in the start state and the game has not failed for (int i = length-1; i >0; i--) { snakeX[i]=snakeX[i-1]; snakeY[i]=snakeY[i-1];//Body movement } if (dir.equals("R")) { snakeX[0]=snakeX[0]+25;//Head movement } else if (dir.equals("L")){ snakeX[0]=snakeX[0]-25; } else if (dir.equals("U")){ snakeY[0]=snakeY[0]-25; } else if (dir.equals("D")){ snakeY[0]=snakeY[0]+25; } repaint();//Refresh page } timer.start();//Make time start to move }
6. Enable the user to control the direction of the snake through the keyboard
@Override public void keyPressed(KeyEvent e) { if (keyCode==KeyEvent.VK_UP||keyCode==KeyEvent.VK_W){ if (!dir.equals("D")){//So that the little snake can't turn back directly dir="U"; } }else if (keyCode==KeyEvent.VK_DOWN||keyCode==KeyEvent.VK_S){ if (!dir.equals("U")){ dir="D"; } }else if (keyCode==KeyEvent.VK_LEFT||keyCode==KeyEvent.VK_A){ if (!dir.equals("R")){ dir="L"; } }else if (keyCode==KeyEvent.VK_RIGHT||keyCode==KeyEvent.VK_D) { if (!dir.equals("L")) { dir = "R"; } } }
7. Add food and credit system
int foodX;int foodY;//Define food coordinates Random random=new Random();//Random number class //Draw food Data.food.paintIcon(this,g,foodX,foodY); if (snakeX[0]==foodX&&snakeY[0]==foodY){//The coordinates of the head and food coincide length++;//Length + 1 score+=10;//Score + 10 foodX=25+25*random.nextInt(34); foodY=75+25*random.nextInt(24);//Regenerate food }
8. Failure judgment
for (int j = 1; j < length; j++) { if (snakeX[j]==snakeX[0]&&snakeY[j]==snakeY[0]){ isFail=true; }//The coordinates of the snake head coincide with the body } if (snakeX[0]>=850||snakeX[0]<=25||snakeY[0]<=75||snakeY[0]>=650){ isFail=true; }//Failed to set wall collision
3, Effect screenshot
- start
- fail
4, Source code
StartGames.Java
package com.wx.snake; import javax.swing.*; public class StartGames { public static void main(String[] args) { JFrame jFrame = new JFrame("Greedy Snake");//Draw a static window jFrame.setBounds(10,10,900,720);//Set interface size jFrame.setResizable(false);//The window size cannot be changed jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//Set window close event jFrame.setVisible(true);//Window display jFrame.add(new GamePanel());//Add panel to window } }
GamePanel.java
package com.wx.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 {//JPanel: panel container class, which can be added to JFrame int length;//Snake length int[] snakeX=new int[600]; int[] snakeY=new int[500];//Snake coordinates String dir;//Head direction boolean isStart=false; Timer timer =new Timer(50,this);//timer int foodX;int foodY;//Define food coordinates Random random=new Random();//Random number class boolean isFail=false;//Death judgment int score;//Integral system //constructor public GamePanel(){ init(); //Get the listening event of the keyboard this.setFocusable(true);//Focus on the game interface this.addKeyListener(this);//Add listening timer.start();//Make time start to move } //initialization public void init(){ length=3; snakeX[0]=100;snakeY[0]=100;//Head coordinates snakeX[1]=snakeX[0]-25;snakeY[1]=snakeY[0];//Section I body coordinates snakeX[2]=snakeX[0]-50;snakeY[2]=snakeY[0];//Section II body coordinates dir="R"; foodX=25+25*random.nextInt(34); foodY=75+25*random.nextInt(24);//Food random coordinates score=0; } //Drawing board (drawing interface, drawing snake) @Override protected void paintComponent(Graphics g) { //Brushes: Graphics super.paintComponent(g);//Clear screen this.setBackground(Color.darkGray);//Set background color Data.header.paintIcon(this,g,25,11);//Draw header billboard g.fillRect(25,75,850,600);//Draw game area //Draw static snake if (dir.equals("R")) { Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); } else if (dir.equals("L")){ Data.left.paintIcon(this,g,snakeX[0],snakeY[0]); }else if (dir.equals("U")){ Data.up.paintIcon(this,g,snakeX[0],snakeY[0]); }else if (dir.equals("D")){ Data.down.paintIcon(this,g,snakeX[0],snakeY[0]); }//Head (up, down, left and right) for (int i = 1; i < length; i++) { Data.body.paintIcon(this,g,snakeX[i],snakeY[i]); }//Draw body length by looping if(isStart==false){//Game tip: start g.setColor(Color.ORANGE); //Set brush color g.setFont(new Font("Blackbody",Font.BOLD,40));//Set font g.drawString("Press the space to start the game",300,300); //Draw a text } //Draw food Data.food.paintIcon(this,g,foodX,foodY); //Failure reminder if (isFail){ g.setColor(Color.red); //Set brush color g.setFont(new Font("Regular script",Font.BOLD,40));//Set font g.drawString(" Game failure",335,300); //Draw a text g.drawString("Your score "+score,333,350); g.drawString("Press space to restart",310,400); } //integral g.setColor(Color.CYAN); //Set brush color g.setFont(new Font("Founder bold black song simplified Chinese",Font.BOLD,20));//Set font g.drawString("Length:"+length,750,34); //Draw a text g.drawString("fraction:"+score,750,59); } //Receive keyboard input: Monitor @Override public void keyPressed(KeyEvent e) { //Keyboard pressed not released int keyCode = e.getKeyCode(); if(keyCode==KeyEvent.VK_SPACE){//Space bar if (isFail){ isFail=false; init();//Reinitialize }else {//Pause the game isStart=!isStart; } repaint();//Refresh interface } if (keyCode==KeyEvent.VK_UP||keyCode==KeyEvent.VK_W){ if (!dir.equals("D")){ dir="U"; } }else if (keyCode==KeyEvent.VK_DOWN||keyCode==KeyEvent.VK_S){ if (!dir.equals("U")){ dir="D"; } }else if (keyCode==KeyEvent.VK_LEFT||keyCode==KeyEvent.VK_A){ if (!dir.equals("R")){ dir="L"; } }else if (keyCode==KeyEvent.VK_RIGHT||keyCode==KeyEvent.VK_D) { if (!dir.equals("L")) { dir = "R"; } } } //Timer, monitor time, frame: execute timing operation @Override public void actionPerformed(ActionEvent e) { if(isStart && isFail==false){//The game is in the start state and the game has not failed for (int i = length-1; i >0; i--) { snakeX[i]=snakeX[i-1]; snakeY[i]=snakeY[i-1];//Body movement } if (dir.equals("R")) { snakeX[0]=snakeX[0]+25;//Head movement //if (snakeX[0]>850){snakeX[0]=25;}// Boundary judgment } else if (dir.equals("L")){ snakeX[0]=snakeX[0]-25; //if (snakeX[0]<25){snakeX[0]=850;}// Boundary judgment } else if (dir.equals("U")){ snakeY[0]=snakeY[0]-25; // if (snakeY[0]<75){snakeY[0]=650;}// Boundary judgment } else if (dir.equals("D")){ snakeY[0]=snakeY[0]+25; //if (snakeY[0]>650){snakeY[0]=75;}// Boundary judgment } if (snakeX[0]>=850||snakeX[0]<=25||snakeY[0]<=75||snakeY[0]>=650){ isFail=true; }//Failed to set wall collision if (snakeX[0]==foodX&&snakeY[0]==foodY){//The coordinates of the head and food coincide length++;//Length + 1 score+=10; foodX=25+25*random.nextInt(34); foodY=75+25*random.nextInt(24);//Regenerate food } //Failure judgment for (int j = 1; j < length; j++) { if (snakeX[j]==snakeX[0]&&snakeY[j]==snakeY[0]){ isFail=true; } } repaint(); } timer.start();//Make time start to move } @Override public void keyTyped(KeyEvent e) { }//Press and pop up the keyboard @Override public void keyReleased(KeyEvent e) { }//Keyboard release }
Java development Snake games
1, Development ideas
-
Set a certain size and immutable game window
-
Draw the basic panel style of the game on the created window
-
Draw a static snake using the saved material icon in advance
-
Enable the snake to move; In fact, only the snake head coordinates need to move, and each body section covers the body coordinates of the previous section. Set the Timer timer =new Timer(); Monitoring time allows the snake to move
-
Monitor the keyboard operation, so that the user can control the direction of the snake through the keyboard
-
Define a food coordinate and realize the random generation of food with random random number class
-
When the snake eats food, its body length is + 1. In fact, when the snake head coordinates coincide with the food coordinates
-
boolean Defines the judgment of game failure. When the snake head coincides with the coordinates of any body part (or hits the boundary), the game fails. You can set up the integral system and add a certain score for each food you eat
2, Specific development process
1. Draw a static game window
JFrame jFrame = new JFrame("Greedy Snake");//Draw a static window jFrame.setBounds(10,10,900,720);//Set interface size jFrame.setResizable(false);//The window size cannot be changed jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//Set window close event jFrame.setVisible(true);//Window display jFrame.add(new GamePanel());//Add panel to window
2. Import material Icon
public class Data { public static URL headerUrl = Data.class.getResource("/statics/header.png");//Locate picture address public static ImageIcon header =new ImageIcon(headerUrl);//Draw pictures by picture address }
3. Draw the game panel
@Override protected void paintComponent(Graphics g) { //Graphics: Brush super.paintComponent(g);//Clear screen this.setBackground(Color.darkGray);//Set background color Data.header.paintIcon(this,g,25,11);//Draw header billboard g.fillRect(25,75,850,600);//Draw game area
4. Draw a static snake
definition
int length;//Snake length int[] snakeX=new int[600]; int[] snakeY=new int[500];//Snake coordinates String dir;//Head direction boolean isStart=false; boolean isFail for (int j = 1; j < length; j++) { if (snakeX[j]==snakeX[0]&&snakeY[j]==snakeY[0]){ isFail=true; } } repaint();=false;
draw
if (dir.equals("R")) { Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); } else if (dir.equals("L")){ Data.left.paintIcon(this,g,snakeX[0],snakeY[0]); }else if (dir.equals("U")){ Data.up.paintIcon(this,g,snakeX[0],snakeY[0]); }else if (dir.equals("D")){ Data.down.paintIcon(this,g,snakeX[0],snakeY[0]); }//Head (up, down, left and right) for (int i = 1; i < length; i++) { Data.body.paintIcon(this,g,snakeX[i],snakeY[i]); }//Draw body length by looping
5. Let the snake move
① Monitor keyboard input
Implement the Keylistener interface and override the KeyPressed() method (press the keyboard)
public void keyPressed(KeyEvent e) { //Keyboard pressed not released int keyCode = e.getKeyCode(); if(keyCode==KeyEvent.VK_SPACE){//Space bar if (isFail){ isFail=false; init();//Reinitialize }else {//Pause the game isStart=!isStart; } repaint();//Refresh interface } }
② Construct timer listening time
Timer timer =new Timer(50,this);//timer
③ Implement ActionListener interface (event listening)
Override actionPerformed(ActionEvent e) method
@Override public void actionPerformed(ActionEvent e) { if(isStart && isFail==false){//The game is in the start state and the game has not failed for (int i = length-1; i >0; i--) { snakeX[i]=snakeX[i-1]; snakeY[i]=snakeY[i-1];//Body movement } if (dir.equals("R")) { snakeX[0]=snakeX[0]+25;//Head movement } else if (dir.equals("L")){ snakeX[0]=snakeX[0]-25; } else if (dir.equals("U")){ snakeY[0]=snakeY[0]-25; } else if (dir.equals("D")){ snakeY[0]=snakeY[0]+25; } repaint();//Refresh page } timer.start();//Make time start to move }
6. Enable the user to control the direction of the snake through the keyboard
@Override public void keyPressed(KeyEvent e) { if (keyCode==KeyEvent.VK_UP||keyCode==KeyEvent.VK_W){ if (!dir.equals("D")){//So that the little snake can't turn back directly dir="U"; } }else if (keyCode==KeyEvent.VK_DOWN||keyCode==KeyEvent.VK_S){ if (!dir.equals("U")){ dir="D"; } }else if (keyCode==KeyEvent.VK_LEFT||keyCode==KeyEvent.VK_A){ if (!dir.equals("R")){ dir="L"; } }else if (keyCode==KeyEvent.VK_RIGHT||keyCode==KeyEvent.VK_D) { if (!dir.equals("L")) { dir = "R"; } } }
7. Add food and credit system
int foodX;int foodY;//Define food coordinates Random random=new Random();//Random number class //Draw food Data.food.paintIcon(this,g,foodX,foodY); if (snakeX[0]==foodX&&snakeY[0]==foodY){//The coordinates of the head and food coincide length++;//Length + 1 score+=10;//Score + 10 foodX=25+25*random.nextInt(34); foodY=75+25*random.nextInt(24);//Regenerate food }
8. Failure judgment
for (int j = 1; j < length; j++) { if (snakeX[j]==snakeX[0]&&snakeY[j]==snakeY[0]){ isFail=true; }//The coordinates of the snake head coincide with the body } if (snakeX[0]>=850||snakeX[0]<=25||snakeY[0]<=75||snakeY[0]>=650){ isFail=true; }//Failed to set wall collision
3, Effect screenshot
- start
- fail
4, Source code
StartGames.Java
package com.wx.snake; import javax.swing.*; public class StartGames { public static void main(String[] args) { JFrame jFrame = new JFrame("Greedy Snake");//Draw a static window jFrame.setBounds(10,10,900,720);//Set interface size jFrame.setResizable(false);//The window size cannot be changed jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//Set window close event jFrame.setVisible(true);//Window display jFrame.add(new GamePanel());//Add panel to window } }
GamePanel.java
package com.wx.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 {//JPanel: panel container class, which can be added to JFrame int length;//Snake length int[] snakeX=new int[600]; int[] snakeY=new int[500];//Snake coordinates String dir;//Head direction boolean isStart=false; Timer timer =new Timer(50,this);//timer int foodX;int foodY;//Define food coordinates Random random=new Random();//Random number class boolean isFail=false;//Death judgment int score;//Integral system //constructor public GamePanel(){ init(); //Get the listening event of the keyboard this.setFocusable(true);//Focus on the game interface this.addKeyListener(this);//Add listening timer.start();//Make time start to move } //initialization public void init(){ length=3; snakeX[0]=100;snakeY[0]=100;//Head coordinates snakeX[1]=snakeX[0]-25;snakeY[1]=snakeY[0];//Section I body coordinates snakeX[2]=snakeX[0]-50;snakeY[2]=snakeY[0];//Section II body coordinates dir="R"; foodX=25+25*random.nextInt(34); foodY=75+25*random.nextInt(24);//Food random coordinates score=0; } //Drawing board (drawing interface, drawing snake) @Override protected void paintComponent(Graphics g) { //Graphics: Brush super.paintComponent(g);//Clear screen this.setBackground(Color.darkGray);//Set background color Data.header.paintIcon(this,g,25,11);//Draw header billboard g.fillRect(25,75,850,600);//Draw game area //Draw static snake if (dir.equals("R")) { Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); } else if (dir.equals("L")){ Data.left.paintIcon(this,g,snakeX[0],snakeY[0]); }else if (dir.equals("U")){ Data.up.paintIcon(this,g,snakeX[0],snakeY[0]); }else if (dir.equals("D")){ Data.down.paintIcon(this,g,snakeX[0],snakeY[0]); }//Head (up, down, left and right) for (int i = 1; i < length; i++) { Data.body.paintIcon(this,g,snakeX[i],snakeY[i]); }//Draw body length by looping if(isStart==false){//Game tip: start g.setColor(Color.ORANGE); //Set brush color g.setFont(new Font("Blackbody",Font.BOLD,40));//Set font g.drawString("Press the space to start the game",300,300); //Draw a text } //Draw food Data.food.paintIcon(this,g,foodX,foodY); //Failure reminder if (isFail){ g.setColor(Color.red); //Set brush color g.setFont(new Font("Regular script",Font.BOLD,40));//Set font g.drawString(" Game failure",335,300); //Draw a text g.drawString("Your score "+score,333,350); g.drawString("Press space to restart",310,400); } //integral g.setColor(Color.CYAN); //Set brush color g.setFont(new Font("Founder bold black song simplified Chinese",Font.BOLD,20));//Set font g.drawString("Length:"+length,750,34); //Draw a text g.drawString("fraction:"+score,750,59); } //Receive keyboard input: Monitor @Override public void keyPressed(KeyEvent e) { //Keyboard pressed not released int keyCode = e.getKeyCode(); if(keyCode==KeyEvent.VK_SPACE){//Space bar if (isFail){ isFail=false; init();//Reinitialize }else {//Pause the game isStart=!isStart; } repaint();//Refresh interface } if (keyCode==KeyEvent.VK_UP||keyCode==KeyEvent.VK_W){ if (!dir.equals("D")){ dir="U"; } }else if (keyCode==KeyEvent.VK_DOWN||keyCode==KeyEvent.VK_S){ if (!dir.equals("U")){ dir="D"; } }else if (keyCode==KeyEvent.VK_LEFT||keyCode==KeyEvent.VK_A){ if (!dir.equals("R")){ dir="L"; } }else if (keyCode==KeyEvent.VK_RIGHT||keyCode==KeyEvent.VK_D) { if (!dir.equals("L")) { dir = "R"; } } } //Timer, monitor time, frame: execute timing operation @Override public void actionPerformed(ActionEvent e) { if(isStart && isFail==false){//The game is in the start state and the game has not failed for (int i = length-1; i >0; i--) { snakeX[i]=snakeX[i-1]; snakeY[i]=snakeY[i-1];//Body movement } if (dir.equals("R")) { snakeX[0]=snakeX[0]+25;//Head movement //if (snakeX[0]>850){snakeX[0]=25;}// Boundary judgment } else if (dir.equals("L")){ snakeX[0]=snakeX[0]-25; //if (snakeX[0]<25){snakeX[0]=850;}// Boundary judgment } else if (dir.equals("U")){ snakeY[0]=snakeY[0]-25; // if (snakeY[0]<75){snakeY[0]=650;}// Boundary judgment } else if (dir.equals("D")){ snakeY[0]=snakeY[0]+25; //if (snakeY[0]>650){snakeY[0]=75;}// Boundary judgment } if (snakeX[0]>=850||snakeX[0]<=25||snakeY[0]<=75||snakeY[0]>=650){ isFail=true; }//Failed to set wall collision if (snakeX[0]==foodX&&snakeY[0]==foodY){//The coordinates of the head and food coincide length++;//Length + 1 score+=10; foodX=25+25*random.nextInt(34); foodY=75+25*random.nextInt(24);//Regenerate food } //Failure judgment for (int j = 1; j < length; j++) { if (snakeX[j]==snakeX[0]&&snakeY[j]==snakeY[0]){ isFail=true; } } repaint(); } timer.start();//Make time start to move } @Override public void keyTyped(KeyEvent e) { }//Press and pop up the keyboard @Override public void keyReleased(KeyEvent e) { }//Keyboard release }