Simple Snake Game

package MySnakeEatEgg;


import java.awt.event.KeyListener;
import javax.swing.JFrame;
import GG.ggh;
public class snackMain extends JFrame{
SnakeYard snac;
    public snackMain() { this.setTitle
    ("Simple Snake Game" );//Title
    this.setSize(SnakeYard.GameWidth+25,SnakeYard.GameHeight+50);//Form size
    snac=new SnakeYard();//Create object SnakeYard, snac is a reference to the object
    this.addKeyListener(snac );//Bind the keyboard event
    this.getContentPane().add(snac);//Add the container to the panel this.setLocation(200,200)
    ;//Location
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Close
    }
public static void main(String[] args) {
     new snackMain().setVisible(true);//The form is visible
}


}

---------------------------------------------------------------------------------------

package MySnakeEatEgg;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class SnakeYard extends JPanel implements KeyListener{
    static final int GameWidth=600,GameHeight=450;//The width and height of the panel
    static boolean startFlag=false;//Start tag
snake sna;//Create object reference
static int foodx,foody;/ /The coordinate position where the food appears randomly public SnakeYard(){ sna = new snake();//Create an object new snake, which is referenced by an object sna points to foodx = (int)(Math.random()*(GameWidth-50) );//Randomly generate the x coordinate of the food foody = (int)(Math.random()*(GameHeight-50));//Randomly generate the y coordinate of the food new Thread(new SnakeYardThread()).start(); //thread






}
public static void main(String[] args) { } public void paint(Graphics g) {//Rewrite the paint() method to draw a rectangular panel, super.paint(g); g.setColor(Color.white); //The brush is white g.fillRect(0, 0, GameWidth, GameHeight);//// Fill a rectangular area with white g.setColor(Color.BLACK);//The brush is black g.drawRect(0, 0, GameWidth, GameHeight);//Stroke a rectangle with black stroke g.setColor(Color.GREEN); g.fillOval(foodx, foody, 15,15);//Green food g.setColor(Color.blue); sna. drawSnake(g);//Blue snake body, call drawSnake() to draw snake } //Thread processing   class SnakeYardThread implements Runnable{ @Override public void run() { while(true) { try { Thread.sleep(100 );//Every 100 milliseconds (0.1 seconds), execute once
 





















repaint();//Call paint(), method, which has the function of refreshing the page
if(startFlag)//startFlag is the start flag, bound in the keyboard event, press the Enter key, startFlag becomes true
sna. snakeMove();//Call snakeMove() method
} catch (InterruptedException e) { e.printStackTrace(); } } }     } @Override public void keyPressed(KeyEvent e) {//Keyboard event switch(e.getKeyCode()) { case KeyEvent.VK_UP: if(snake.direction == 1) break;//Up key                      sna.dire(0);break; case KeyEvent.VK_DOWN: if(snake.direction == 0) break;//Down key                       sna.dire(1);break; case KeyEvent.VK_LEFT: if(snake.direction == 3) break;//left key                       sna.dire(2);break;





   










case KeyEvent.VK_RIGHT: if(snake.direction == 2) break;//右键
                      sna.dire(3);break;
case KeyEvent.VK_SPACE: startFlag = false; break;//空格键
case KeyEvent.VK_ENTER: startFlag = true; break;//回车键
}
}
   
@Override
public void keyReleased(KeyEvent arg0) {}
@Override
public void keyTyped(KeyEvent arg0) {}

}

-----------------------------------------------------------------------

package MySnakeEatEgg;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class snake{
  static final int UP=0,DOWN=1,LEFT=2,RIGHT=3;
  static int size=15;//size 为蛇长
  static int direction=RIGHT;
  boolean eat=false;
  boolean dead=false;
  List<node> list=new ArrayList<node>();//集合用来存每个蛇的坐标
  
  public void drawSnake(Graphics g) {  for (int i=0; i<list.size(); i++) {//画蛇       if(i==0) {   g.setColor(Color.RED);//蛇头用红色画
 

 

   
      g.fillOval(list.get(i).getX(),list.get(i).getY(), size, size);// Fill an oval area with red, which is to draw a snake head, the same below
      }else {   g.setColor(Color.blue);//Blue snake body   g.fillOval(list.get(i).getX(),list.get(i).getY(), size, size);       }  }     }   public snake(){   // The snake is initialized to 5 nodes  node node0 = new node(90,90);//The position of the snake head,  node node1 = new node(75,90);//The object new node is created, and is An object reference node1 points to. The (75,90) at the end means that the constructor of the node class is called immediately after the object is created  node node2 = new node(60,90);  node node3 = new node(45,90);  node node4 = new node(30 ,90);  list.add(node0);//Add the object reference to the collection  list.add(node1);  list.add(node2);  list.add(node3);  list.add(node4);   }
   
   

 



 













  
  public void snakeMove() {  int NewX,NewY;//The two variables save the initial value of the snake head first, because I don't know where to move  NewX = list.get(0).getX();  NewY = list.get(0) .getY();  switch(direction) {//The initial value of direction is 3, which is RIGHT, and the value of direction is changed by keyboard events case UP: NewY = list.get(0).getY()-size; break; //UP is 0 (when the up arrow key is pressed, the value of direction becomes 0), move up, that is, the value of y -size, the value of x remains unchanged, the same as the case DOWN: NewY = list.get( 0).getY()+size; break; case LEFT: NewX = list.get(0).getX()-size; break; case RIGHT: NewX = list.get(0).getX()+size; break ;     }  node NodeHead = new node(NewX,NewY);//New head coordinates, the two variables at this time are the changed values  ​​node newNode = new node();//New tail coordinates       // Math.abs absolute value




 







 


 if(Math.abs(list.get(0).getX()-SnakeYard.foodx)<= size && Math.abs(list.get(0).getY()-SnakeYard.foody)<= size) {
 eat = true;//Eat the mark
 newNode = new node(list.get(list.size()-1).getX(),list.get(list.size()-1).getY());// Save the tail coordinate when you eat food
 while(true) {
 SnakeYard.foodx = (int)(Math.random()*(SnakeYard.GameWidth-50));//Randomly generate the x coordinate of the food
 SnakeYard.foody = (int) (Math.random()*(SnakeYard.GameHeight-50));//Randomly generate the y coordinate of the food
 if(list.get(0).getX() == SnakeYard.foodx && list.get(0).getY ()== SnakeYard.foody) {
 continue;
 }else {
 break;
 }  }  }       //Reference the object of the previous point to the next point  for (int i = list.size()-1;i>0;i- -){ list.set(i, list.get(i-1)); }
 


 





list.set(0, NodeHead);//New head coordinates //Whether it touches the edge  if(list.get(0).getX()+size<=0||list.get(0).getX() +size>=SnakeYard.GameWidth||list.get(0).getY()+size<=0||list.get(0).getY()+size>=SnakeYard.GameHeight){  JOptionPane.showMessageDialog(null , "GAME OVER!!", "Message", JOptionPane.ERROR_MESSAGE); System.exit(-1);  }  //Do you eat yourself  for(int i=1;i<list.size();i++) {  if(list.get(0).getX()==list.get(i).getX() && list.get(0).getY()==list.get(i).getY()) {  JOptionPane .showMessageDialog(null, "GAME OVER!!", "Message", JOptionPane.ERROR_MESSAGE);//Prompt  System.exit(-1);//Exit  }  }  //If you eat food, add a new node, add tail node  if(eat) {  list.add(newNode);  eat=false;
 
















 }   }     //The coordinates of the snake    class node{ int x,y; public node(int x,int y) { this.x=x; this.y=y; } public node() { }         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; }     }    //The movement of the snake Direction, when the keyboard event is triggered, the value of direction is changed   public void dire(int dire) {  this.direction=dire;   }
 



   
   
   
   
   
   
   
   

















}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325993009&siteId=291194637