Home>

This article recommends a classic small game implemented by java:Snake, I believe everyone has played,How to achieve it?

Not much nonsense,Send the code directly:

1,

public class greedsnake {
  public static void main (string [] args) {
    snakemodel model=new snakemodel (20,30);
    snakecontrol control=new snakecontrol (model);
    snakeview view=new snakeview (model, control);
    //Add an observer,Make the view an observer of the model
    model.addobserver (view);
    (new thread (model)). start ();
  }
}

2,

package mvctest;
//snakecontrol.java
import java.awt.event.keyevent;
import java.awt.event.keylistener;
public class snakecontrol implements keylistener {
  snakemodel model;
  public snakecontrol (snakemodel model) {
    this.model=model;
  }
  public void keypressed (keyevent e) {
    int keycode=e.getkeycode ();
    if (model.running) {//In the running state,Processed keys
      switch (keycode) {
        case keyevent.vk_up:
          model.changedirection (snakemodel.up);
          break;
        case keyevent.vk_down:
          model.changedirection (snakemodel.down);
          break;
        case keyevent.vk_left:
          model.changedirection (snakemodel.left);
          break;
        case keyevent.vk_right:
          model.changedirection (snakemodel.right);
          break;
        case keyevent.vk_add:
        case keyevent.vk_page_up:
          model.speedup ();
          break;
        case keyevent.vk_subtract:
        case keyevent.vk_page_down:
          model.speeddown ();
          break;
        case keyevent.vk_space:
        case keyevent.vk_p:
          model.changepausestate ();
          break;
        default:
      }
    }
    //keystrokes processed under any circumstances,Keystroke Restarts Game
    if (keycode == keyevent.vk_r ||
        keycode == keyevent.vk_s ||
        keycode == keyevent.vk_enter) {
      model.reset ();
    }
  }
  public void keyreleased (keyevent e) {
  }
  public void keytyped (keyevent e) {
  }
}

3.

package mvctest;
//snakemodel.java
import javax.swing. *;
import java.util.arrays;
import java.util.linkedlist;
import java.util.observable;
import java.util.random;
class snakemodel extends observable implements runnable {
  boolean [] [] matrix;//indicate if there is snake body or food
  linkedlist nodearray=new linkedlist ();//snake body
  node food;
  int maxx;
  int maxy;
  int direction=2;//direction of the snake
  boolean running=false;//running status
  int timeinterval=200;//time interval,millisecond
  double speedchangerate=0.75;//get speed change rate each time
  boolean paused=false;//pause flag
  int score=0;//score
  int countmove=0;//number of moves before eating food
  //up and down should be even
  //right and left should be odd
  public static final int up=2;
  public static final int down=4;
  public static final int left=1;
  public static final int right=3;
  public snakemodel (int maxx, int maxy) {
    this.maxx=maxx;
    this.maxy=maxy;
    reset ();
  }
  public void reset () {
    direction=snakemodel.up;//direction of snake
    timeinterval=200;//time interval,millisecond
    paused=false;//pause flag
    score=0;//score
    countmove=0;//number of moves before eating food
    //initial matirx, clear all 0
    matrix=new boolean [maxx] [];
    for (int i=0;i<maxx;++ i) {
      matrix [i]=new boolean [maxy];
      arrays.fill (matrix [i], false);
    }
    //initial the snake
    //Initialize the snake body,If there are more than 20 horizontal positions, the length is 10, otherwise it is half of the horizontal position
    int initarraylength=maxx>20?10:maxx/2;
    nodearray.clear ();
    for (int i=0;i<initarraylength;++ i) {
      int x=maxx/2 + i;//maxx is initialized to 20
      int y=maxy/2;//maxy is initialized to 30
      //nodearray [x, y]:[10,15]-[11,15]-[12,15] ~~ [20,15]
      //The default running direction is up,So at the beginning of the game nodearray becomes:
      //[10,14]-[10,15]-[11,15]-[12,15] ~~ [19,15]
      nodearray.addlast (new node (x, y));
      matrix [x] [y]=true;
    }
    //create food
    food=createfood ();
    matrix [food.x] [food.y]=true;
  }
  public void changedirection (int newdirection) {
    //The direction of change cannot be the same or opposite to the original direction
    if (direction%2!=newdirection%2) {
      direction=newdirection;
    }
  }
  public boolean moveon () {
    node n=(node) nodearray.getfirst ();
    int x=n.x;
    int y=n.y;
    //Increase or decrease the coordinate value according to the direction
    switch (direction) {
      case up:
        y--;
        break;
      case down:
        y ++;
        break;
      case left:
        x--;
        break;
      case right:
        x ++;
        break;
    }
    //If the new coordinates fall within the valid range,Processing
    if ((0<= x&&x&maxx)&&(0<= y&&y&maxy)) {
      if (matrix [x] [y]) {//if there is something (snake or food) at the new coordinate point
        if (x == food.x && y == food.y) {//Eat food,success
          nodearray.addfirst (food);//donate length from snake
          //score rules,It is related to the number of times and speed of moving the change
          int scoreget=(10000-200 * countmove)/timeinterval;
          score +=scoreget>0?scoreget:10;
          countmove=0;
          food=createfood ();//create new food
          matrix [food.x] [food.y]=true;//set the food location
          return true;
        } else //Eat the snake itself,failure
          return false;
      } else {//If there is nothing (snake body) at the new coordinate point, move the snake body
        nodearray.addfirst (new node (x, y));
        matrix [x] [y]=true;
        n=(node) nodearray.removelast ();
        matrix [n.x] [n.y]=false;
        countmove ++;
        return true;
      }
    }
    return false;//touch the edge,failure
  }
  public void run () {
    running=true;
    while (running) {
      try {
        thread.sleep (timeinterval);
      } catch (exception e) {
        break;
      }
      if (! paused) {
        if (moveon ()) {
          setchanged ();//model notifies view that data has been updated
          notifyobservers ();
        } else {
          joptionpane.showmessagedialog (null,              "you failed",              "game over",              joptionpane.information_message);
          break;
        }
      }
    }
    running=false;
  }
  private node createfood () {
    int x=0;
    int y=0;
    //Randomly get a position in a valid area that does not overlap with the snake body and food
    do {
      random r=new random ();
      x=r.nextint (maxx);
      y=r.nextint (maxy);
    } while (matrix [x] [y]);
    return new node (x, y);
  }
  public void speedup () {
    timeinterval *=speedchangerate;
  }
  public void speeddown () {
    timeinterval/= speedchangerate;
  }
  public void changepausestate () {
    paused =! paused;
  }
  public string tostring () {
    string result="";
    for (int i=0;i<nodearray.size ();++ i) {
      node n=(node) nodearray.get (i);
      result +="[" + n.x + "," + n.y + "]";
    }
    return result;
  }
}
class node {
  int x;
  int y;
  node (int x, int y) {
    this.x=x;
    this.y=y;
  }
}

4.

package mvctest;
//snakeview.java
import javax.swing. *;
import java.awt. *;
import java.util.iterator;
import java.util.linkedlist;
import java.util.observable;
import java.util.observer;
public class snakeview implements observer {
  snakecontrol control=null;
  snakemodel model=null;
  jframe mainframe;
  canvas paintcanvas;
  jlabel labelscore;
  public static final int canvaswidth=200;
  public static final int canvasheight=300;
  public static final int nodewidth=10;
  public static final int nodeheight=10;
  public snakeview (snakemodel model, snakecontrol control) {
    this.model=model;
    this.control=control;
    mainframe=new jframe ("greedsnake");
    container cp=mainframe.getcontentpane ();
    //create the top score display
    labelscore=new jlabel ("score:");
    cp.add (labelscore, borderlayout.north);
    //Create the middle game display area
    paintcanvas=new canvas ();
    paintcanvas.setsize (canvaswidth + 1, canvasheight + 1);
    paintcanvas.addkeylistener (control);
    cp.add (paintcanvas, borderlayout.center);
    //create the bottom help bar
    jpanel panelbuttom=new jpanel ();
    panelbuttom.setlayout (new borderlayout ());
    jlabel labelhelp;
    labelhelp=new jlabel ("pageup, pagedown for speed;", jlabel.center);
    panelbuttom.add (labelhelp, borderlayout.north);
    labelhelp=new jlabel ("enter or r or s for start;", jlabel.center);
    panelbuttom.add (labelhelp, borderlayout.center);
    labelhelp=new jlabel ("space or p for pause", jlabel.center);
    panelbuttom.add (labelhelp, borderlayout.south);
    cp.add (panelbuttom, borderlayout.south);
    mainframe.addkeylistener (control);
    mainframe.pack ();
    mainframe.setresizable (false);
    mainframe.setdefaultcloseoperation (jframe.exit_on_close);
    mainframe.setvisible (true);
  }
  void repaint () {
    graphics g=paintcanvas.getgraphics ();
    //draw background
    g.setcolor (color.white);
    g.fillrect (0, 0, canvaswidth, canvasheight);
    //draw the snake
    g.setcolor (color.black);
    linkedlist na=model.nodearray;
    iterator it=na.iterator ();
    while (it.hasnext ()) {
      node n=(node) it.next ();
      drawnode (g, n);
    }
    //draw the food
    g.setcolor (color.red);
    node n=model.food;
    drawnode (g, n);
    updatescore ();
  }
  private void drawnode (graphics g, node n) {
    g.fillrect (n.x * nodewidth,        n.y * nodeheight,        nodewidth-1,        nodeheight-1);
  }
  public void updatescore () {
    string s="score:" + model.score;
    labelscore.settext (s);
  }
  public void update (observable o, object arg) {
    repaint ();
  }
}

The purpose of this article is to remind everyone of the classics,But the main purpose is to help everyone learn good java programming.

  • Previous Android to make a beautiful and adaptive layout keyboard
  • Next Python from entry to the master (DAY 1)
  • Trends