Java Greedy snake speed version _java

Source: Internet
Author: User

This article for everyone recommended a classic Java implementation of the game: greedy Snake, I believe we have played, how to achieve the NA?

Effect Chart:

Don't say much nonsense, directly to the code:

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, let view become Model observer
    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) {//Run state, handle the key switch (keycode) {case KeyEvent.VK_UP:model.changeDire
          Ction (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:}///Under any circumstances, the key causes the restart of the game if (keycode = Keyevent.vk_r | |
        KeyCode = = keyevent.vk_s | |
    KeyCode = = Keyevent.vk_enter) {model.reset ();

 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;  Indicates that there are no snakes or food linkedlist nodearray = new LinkedList ();
  Food Node of snake body;
  int MaxX;
  int Maxy;             int direction = 2;          Snake runs in the direction of Boolean running = false;           Running state int timeinterval = 200;       Time interval, milliseconds double speedchangerate = 0.75;           The rate of change at each time is Boolean paused = false;               Pause Sign int score = 0;             Score int countmove = 0;
  The number of moves before eating food//up and down should is even//right and left should is 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;           Snake runs in the direction timeinterval = 200;             Time interval, millisecond paused = false;               Pause sign score = 0;             Score Countmove = 0;
    The number of times to move before eating//initial Matirx, all clear 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//init snake body, if the transverse position is over 20, the length is 10, otherwise the transverse position of half 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 int y = MAXY/2;    Maxy is initialized to//nodearray[x,y]: [10,15]-[11,15]-[12,15]~~[20,15]//The default running direction is up, so the first nodearray of the game 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) {//change direction cannot be in the same direction as the original or reverse if (direction% 2!= newdirection% 2) {di
    Rection = newdirection;
    } public boolean moveOn () {Node n = (node) nodearray.getfirst ();
    int x = n.x;

    int y = N.Y;
        According to the direction or decrease the coordinate value switch (direction) {case up:y--;
      Break
        Case down:y++;
      Break
        Case left:x--;
      Break
        Case right:x++;
    Break
    
      ///If the new coordinates fall within a valid range, process if ((0 <= x && x < MaxX) && (0 <= y && y < Maxy)) {
          if (Matrix[x][y]) {//If there is something on the point of the new coordinate (snake or food) if (x = = Food.x && y = = food.y) {//Eat food, success      Nodearray.addfirst (food);
          From the snake head to give a long//fractional rule, with the number of changes in direction and speed of two elements related to int scoreget = (10000-200 * countmove)/timeinterval; Score + = scoreget > 0?
          Scoreget:10;

          Countmove = 0;    Food = Createfood ();    Create a new food matrix[food.x][food.y] = true;
        Set food location return true;
        
      else//Eat the snake itself, failure return false;
        else {//If there is nothing on the point of the new coordinate (snake body), move the snake 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 Edge, failed} public void run () {running = true;
      while (running) {try {thread.sleep (timeinterval);
      catch (Exception e) {break;      } if (!paused) {if (MoveOn ()) {setchanged ();
        Model Notice View 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 acquiring a position within a valid region 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 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 ("spaces 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, Nodewid
  Th-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 bring you a memorable classic, but the main purpose is to help you learn Java programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.