<p> Class control code: </p><p>import Java.awt.event.keyevent;</p>import Java.awt.event.KeyListener; public class Control implements KeyListener {//monitor the keyboard Snakemodel snake=null;public Control (Snakemodel snake) {This.snak E=snake;} @Overridepublic void keypressed (KeyEvent e) {if (E.getkeycode () ==keyevent.vk_up) {snake.changedirection ( SNAKEMODEL.UP);} if (E.getkeycode () ==keyevent.vk_down) {//Listen button ↓, Move Down Snake.changedirection (Snakemodel.down);} if (E.getkeycode () ==keyevent.vk_left) {//Listen button ←, move left snake.changedirection (snakemodel.left);} if (E.getkeycode () ==keyevent.vk_right) {//Listen button ↑, move up snake.changedirection (snakemodel.right);} if (E.getkeycode () ==keyevent.vk_right) {//Listen button →, move right snake.changedirection (snakemodel.right);} if (E.getkeycode () ==keyevent.vk_r) {//Listen button R, reset Snake.restart ();}} @Overridepublic void keytyped (KeyEvent e) {} @Overridepublic void keyreleased (KeyEvent e) {}}
class Snakemodel Code:
<pre name= "code" class= "java" >import java.awt.canvas;import java.awt.color;import Java.awt.graphics;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.util.random;import Javax.swing.Timer; Import cn.hncu.xh.snake.snakepoint.point;/* * Idea: Using the dynamic number to assemble the snake model, the snake's point is only followed by the snake head (i.e.: the first element of the array), * every repaint () once, the dynamic array inside the snake all the numbers out 。 * Each time you eat a food, add it to the head of the snake, the head of the snake moves backwards, and then the snake moves along. * Note: When snakes eat food, avoid bundling!!! */public class Snakemodel extends Canvas implements ActionListener {private snakepoint[] snakepoint; The array of loaded snakes private static timer timer; Timer private static int score = 0; Fractional private int Dx, dy;//snake Head coordinates private int Px, Py; Food coordinates static final int left = 1;static final int up = 2;static final int down = 4;static final int right = 3;int Directio n = 4; The initial direction is moved down by Boolean isfrist = true; Controls the position of the first food Boolean isone = true; Control each time a snake can only press once keyboard Boolean food; Control not to eat a food to go to refresh the food coordinates public snakemodel (int delay) {//Construction Snake Model This.snakepoint = new snakepoint[300]; Used to install the snake head snakepoint[1] = new Snakepoint (100, 100);//Draw the snake Head//using timer timer = new Timer (delay, this); Timer.start ();} public static int Getscore () {//Get score return score;} Class Snakepoint {//Snake body (each snake consists of many snakes) int x, y;public snakepoint (int x, int y) {this.x = X;this.y = y;} Snakepoint (Snakepoint p) {this.x = P.x;this.y = P.y;}} @Overridepublic void Paint (Graphics g) {//Food creatfood ();//Let the array automatically move once per walk if (score! = 0) {for (int i = score + 2; i > 1 ; i--) {Snakepoint[i] = new Snakepoint (snakepoint[i-1]);}} switch (direction) {//To determine the direction of the snake head case up:snakepoint[1].y-= 10;break;case Down:snakepoint[1].y + = 10;break;case Left: snakepoint[1].x-= 10;break;case right:snakepoint[1].x + = 10;break;} Eat food//to consider the coordinates of the food can not coincide with the snake head coordinates if (snakepoint[1].x <= Px + 7 && snakepoint[1].x >= px-5&& snakepoint[ 1].y <= Py + 7 && snakepoint[1].y >= Py-5) {score++;//score plus one food = true;//Refresh Foods snakemain.re ();//Refresh score Tim Er.setdelay ((Timer.getdelay ()-4) <=0? 20:timer.getdelay ()-4); The speed at which the snake moves is accelerated/System.out.println (Timer.getdelay ()) after each meal, and/or after eating a food, add a length for (int j = score + 1; j > 1; j--) in the head of the snake. {SNA KEPOINT[J] = new Snakepoint (snakepoint[j-1]);} Let the snake head move in a step. switch (direction) {//To determine the direction of the snake head case up:snakepoint[1].y-= 10;break;case down:snakepoint[1].y + = 10;break; Case left:snakepoint[1].x-= 10;break;case right:snakepoint[1].x + = 10;break;}} G.setcolor (color.red);//food is red g.fillrect (Px, Py, 10, 10);//Painting Food g.setcolor (color.black);//Snake is black//Draw snake, draw the snake out of the array for (int i = 1; I <= score + 1; i++) {g.fillrect (snakepoint[i].x, SNAKEPOINT[I].Y, 10, 10);}} private void Creatfood () {if (isfrist) {Px = legal (380);//obtain a valid x value, Py = legal (330);//obtain a valid Y value, i.e., after synthesizing food coordinates with the X group not on the snake isfrist = FA Lse;return;} The next food coordinate if (foods) {Px = legal (380);//Ibid. = Legal (+); food = false;} System.out.println (Px);//System.out.println (Py);} private int legal (int i) {random r = new Random (); Generate random number if (i = = 380) {//Generate food's Y coordinate while (true) {int n = (R.nextint (PNS) + 1) * 10;for(int j = 1; J <= score + 1; j + +) {//each time to match the body to avoid food appearing on the snake; if (snakepoint[j].x! = N && j = = (score + 1)) {return n;}}} if (i = = 330) {//generates the x-coordinate of the food while (true) {int n = (R.nextint (+ 1)) * 10;FOR (int j = 1; J <= score + 1; k + +) {if (SN Akepoint[j].y! = N && j = = (score + 1)) {return n;}}} return 0;} @Overridepublic void actionperformed (ActionEvent e) {isover ();//Determine whether to end the game repaint (); isone = true;//System.out.println ( snakepoint[1].x+ "" +snakepoint[1].y);} private void Isover () {if (Iscondition ()) {///Iscondition ()//Determines whether all conditions for the end are placed inside the timer.stop (); Snakemain.gameover (); Game over, Popup dialog}}private Boolean iscondition () {//game end condition//out of bounds (wall) if (snakepoint[1].x <= 0 | | snakepoint[1].x >= 380| | Snakepoint[1].y <= 0 | | Snakepoint[1].y >=) {return true;} Snake head eats snake body for (int i = 2; I <= score + 1; i++) {if (snakepoint[1].x = = snakepoint[i].x&& Snakepoint[1].y = = Snak EPOINT[I].Y) {return true;}} return false;} public void changedirection (int newdirection) {//change direction if (direction% 2 = newdirection% 2 && isone) {//change direction cannot be the same as the original direction or opposite direction = Newdirection;isone = False ;}} public static void Stop () {timer.stop ();} public static void Start () {Timer.start ();} Reset all data public void ReStart () {score=0;direction = 4;isfrist = True;isone = True;food=false;//snakepoint=null; Snakepoint[1].x=100;snakepoint[1].y=100;creatfood (); Timer.start ();}}
Class Snakemain Code:
<pre name= "code" class= "java" >import java.awt.event.actionevent;import Java.awt.event.actionlistener;import Javax.swing.jbutton;import Javax.swing.jframe;import Javax.swing.jlabel;import Javax.swing.JOptionPane;import Javax.swing.jpanel;import Javax.swing.jtextfield;public class Snakemain extends JFrame implements ActionListener { private static JTextField scorefield;private JButton stop,start;public static void Main (string[] args) {new Snakemain ();} Public Snakemain () {Super ("snake"); This.setbounds (+, +, +); this.setdefaultcloseoperation (Exit_on_close); This.setresizable (FALSE); JPanel p = new JPanel (), This.getcontentpane (). Add (P, "North");p. Add (New JLabel ("Score:")); Scorefield = new JTextField (" 0 ", 5); scorefield.seteditable (false); stop = new JButton (" Stop "); start = new JButton (" Start ");// Let these components lose focus scorefield.setfocusable (false); stop.setfocusable (false); start.setfocusable (false); Add component to Panel Pp.add (Scorefield);p. Add (Stop);p. Add (start); Snakemodel snake = new Snakemodel (400);//500 is the Refresh Time This.getcontentpane (). Add (snake); Add the snake to the panel (the snake's operating range: 0<=x<=380//0<=y<=330) Control control = new Control (snake); Control snake//monitor stop.addactionlistener (this), Start.addactionlistener (this); This.addkeylistener (control);// Display this.setvisible (true);} public static void Re () {//Refresh score Box Scorefield.settext ("" + Snakemodel.getscore ());} public static void Gameover () {//game end Joptionpane.showmessagedialog (null, "Game over!!!");} @Overridepublic void actionperformed (ActionEvent e) {if (e.getsource () = = stop) {snakemodel.stop ();} if (e.getsource () = = start) {Snakemodel.start ();}}}
Snake Java applet