Java Simple snake

Source: Internet
Author: User
Tags gety

said the simple version of the snake ...

Enumerate variables in 3 + directions (originally wanted to write the greedy snake to walk. Imagine that my snake is a rectangle with an unsightly slant and no writing.

Left and right key control move space pause

Snackclient class

Package Com.xynu.snaker;import Java.awt.color;import Java.awt.font;import java.awt.graphics;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.awt.event.keyadapter;import Java.awt.event.keyevent;import Java.io.ioexception;import Java.util.arraylist;import Java.util.Random;import Javax.swing.jframe;import Javax.swing.jmenu;import Javax.swing.jmenubar;import Javax.swing.JMenuItem;import Javax.swing.jpanel;public class Snackclient extends JFrame {private static, snackclient sc;private snackbody snackfood;//  Current game state Private Boolean gamestate = True;private mycomponent mc;//Game Private Boolean pause = False;private JMenu menu;private JMenuBar menubar;//Low Level private JMenuItem lowspeeditem;//level private JMenuItem midspeeditem;//High level private JMenuItem heightspeeditem;//re-start private jmenuitem restartitem;public int speed = 15;static int score = 0;private Maxscore ms;//snake body ar raylist<snackbody> Snackbodys = new arraylist<snackbody> ();//Snake head static snackbody snackhead;pRivate static final Long serialversionuid = 1l;public snackclient () {//Initialize menu bar Initmenu (); mc = new MyComponent (); mc.setback Ground (Color.Black); add (MC); Settitle ("snake"); setSize (+); Setlocationrelativeto (null); Setdefaultcloseoperation (Jframe.exit_on_close); setvisible (true); setresizable (false); snackhead = new SnackBody (100 (int i = 0; i < 2; i++) {Snackbodys.add (new Snackbody ( -100, -100, this));} ms = new Maxscore (); Showsnackfood (); Addkeylistener (new Mykeylistener ()); new Paintthread (). Start (); private void Initmenu () {//TODO auto-generated Method Stubmenu = new JMenu ("parameter setting"); Lowspeeditem = new JMenuItem ("low Grade"); mi Dspeeditem = new JMenuItem ("middle class"), Heightspeeditem = new JMenuItem ("High Level"); Restartitem=new jmenuitem ("restart"); Lowspeeditem.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO Auto-generated method stubspeed = 15;}}); Midspeeditem.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO AutO-generated method stubspeed = 17;}}); Heightspeeditem.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO Auto-generated method stubspeed = 20;}}); Restartitem.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO auto-generated Method Stubdispose (); sc=new snackclient ();}}); Menu.add (Lowspeeditem); Menu.add (Midspeeditem); Menu.add (Heightspeeditem); Menu.add (restartitem); menubar = new JMenuBar (); Menubar.add (menu); Setjmenubar (menubar);} public Boolean ispause () {return pause;} public void Setpause (Boolean pause) {this.pause = pause;} public static void Main (string[] args) {//TODO auto-generated Method stubsc = new Snackclient ();} public class MyComponent extends JPanel {/** * */private static final long serialversionuid = 1l;protected void Paintcomp  Onent (Graphics g) {//TODO auto-generated method Stubsuper.paintcomponent (g); if (!gamestate) {font font = new Font ("Microsoft Ya Black", Font.Bold, G.setfont (font); G.setcolor (COLOR.RED); g.DrawString ("GAME over!!", this.getwidth ()/2-150,this.getheight ()/2); return;} If a snake hits a snake or crashes the game ends if (snackhead.hitwall () | | | snackhead.hitsnackbody (SNACKBODYS)) {gamestate = false;} If the snake head eats food if (snackhead.hitsnackbody (Snackfood)) {Snackbodys.add (snackfood); score++;//refreshes food Showsnackfood ();} Draw Food Snackfood.draw (g);//Draw Snake if (gamestate) {for (Snackbody Sb:snackbodys) {Sb.draw (g);}} Draw the snake head if (gamestate) {Snackhead.draw (g);} try {g.drawstring ("Current score:" + score * 100 + "game Highest score:" + ms.getmaxscore (), 0, 10);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} Randomly appearing food public void Showsnackfood () {Random r = new Random (); Boolean exit = True;while (exit) {int x = R.nextint (mc.getwid Th ()-snackhead.getwidth ()), int y = R.nextint (Mc.getheight ()-snackhead.getheight ()), Snackfood = new Snackbody (x, Y, SC) ; if (Snackfood.hitsnackbody (snackhead) | | snackfood.hitsnackbody (SNACKBODYS)) {continue;} Exit = FALSE;}} Keyboard events public class Mykeylistener extends Keyadapter {@Overridepublic void keypressed (KeyEvent e) {//TODO auto-generated method Stubsnackhead.keypress (e);} @Overridepublic void keyreleased (KeyEvent e) {//TODO auto-generated method Stubsnackhead.keyrelease (e);}} Game refresh public class Paintthread extends Thread {public void run () {//TODO auto-generated method Stubwhile (True) {if (!pau SE) {repaint (); try {thread.sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}}}

Packaged Snake body Snackbody class

Package Com.xynu.snaker;import Java.awt.color;import Java.awt.graphics;import java.awt.graphics2d;import Java.awt.rectangle;import Java.awt.event.keyevent;import Java.awt.geom.rectangle2d;import java.util.ArrayList; public class Snackbody {private int x;private int y;private int speed = 15;private int width = 15;private int height = 15; Private Boolean left, right, up, down;private Direction dir = direction.d, CurDir = direction.d;private snackclient sc;pub Lic Snackbody () {super ();//TODO auto-generated constructor stub}public snackbody (int x, int y, snackclient SC) {super (); t his.x = X;this.y = Y;this.sc = SC;} 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;} public int getwidth () {return width;} public void setwidth (int width) {this.width = width;} public int getheight () {return height;} public void setheight (int height) {this.height = height;} Public Direction Getdir () {return dir;} public void Draw (Graphics g) {graphics2d g2 = (graphics2d) g; rectangle2d r2 = new Rectangle2d.double (x, y, width, height);//Snake as Yellow g2.setcolor (Color.yellow);//Snake head is red if (this = = Snackclient.snackhead) G2.setcolor (color.red); G2.fill (R2); if (this = = Snackclient.snackhead) {this.speed = Sc.speed; Move ();}} Keyboard event public void KeyPress (KeyEvent e) {switch (E.getkeycode ()) {Case KeyEvent.VK_RIGHT:right = true;break;case keyevent . Vk_left:left = true;break;case KeyEvent.VK_UP:up = true;break;case KeyEvent.VK_DOWN:down = true;break;case keyevent.vk_ SPACE:sc.setPause (!sc.ispause ()); break;} Judgedir ();}  Judging the direction if you want to move in eight directions is also the same as private void Judgedir () {//TODO auto-generated method stubif (left &&!right &&!up &&!down) CurDir = direction.l;if (!left && right &&!up &&!down) CurDir = direction.r;if (!left &&!right && up &&!down) CurDir = direction.u;if (!left &&!right &&!up &A mp;& down) CurDir = DIRECTION.D;} */* The movement of the snake body moves according to the body of the snake * The first snake body equals the position of the snake head before moving.* The second section of the Snake body equals the position of the first snake before moving. * And so */private void Move () {if (dir = = Direction.l && CurDir = = DIRECTION.R) CurDir = dir;if (dir = = Direction.r && CurDir = = direction.l) CurDir = dir;if (dir = = direction.u && CurDir = = DIRECTION.D  ) CurDir = dir;if (dir = = direction.d && CurDir = = direction.u) CurDir = dir;if (dir! = curdir) dir = Curdir;int PreX = X;int PreY = y;if (dir = = DIRECTION.L) {x-= Speed;prex + = 1;} if (dir = = DIRECTION.R) {x + = Speed;prex-= 1;} if (dir = = direction.u) {y-= Speed;prey + = 1;} if (dir = = direction.d) {y + = speed;prey-= 1;} int tempx, tempy;for (Snackbody body:sc.snackBodys) {tempx = Body.getx (); tempy = Body.gety (); Body.setx (PreX); Body.sety ( PreY);p rex = Tempx;prey = Tempy;}} public void Keyrelease (KeyEvent e) {switch (E.getkeycode ()) {Case KeyEvent.VK_RIGHT:right = false;break;case KEYEVENT.VK _left:left = false;break;case KeyEvent.VK_UP:up = false;break;case KeyEvent.VK_DOWN:down = false;break;}} Return to the snake body rectangle public Rectangle Getrec () {return new ReCtangle (x, y, width, height);} The collision event of the snake head and the Snake Body public boolean hitsnackbody (Snackbody sb) {if (the This = SB) return false;if (This.getrec (). intersects ( Sb.getrec ())) {return true;} return false;} public boolean hitsnackbody (arraylist<snackbody> Snackbodys) {in (Snackbody Snackbody:snackbodys) {if (This! = SN Ackbody) {if (Hitsnackbody (snackbody)) {return true;}}} return false;} public Boolean Hitwall () {if (x <= 0 | | y <= 0 | | x >= sc.getwidth ()-width| | y >= sc.getheight ()-height) { return true;} return false;}}
Highest score Maxscore class

Package Com.xynu.snaker;import Java.io.bufferedreader;import Java.io.bufferedwriter;import java.io.File;import Java.io.filereader;import Java.io.filewriter;import Java.io.ioexception;public class MaxScore {public int getMaxScore () throws Ioexception{file file=new File ("MaxScore.txt"), if (!file.exists ()) {file.createnewfile ();} BufferedReader br=new BufferedReader (new FileReader (file)); String s=br.readline (); int max=0;if (! "". Equals (s) &&s!=null) {max=integer.parseint (s);} else{max=0;} if (Snackclient.score*100>max) {max=snackclient.score*100; BufferedWriter bw=new BufferedWriter (new FileWriter (file)), Bw.write (max+ ""); Bw.close ();} Br.close (); return Max;}}
Run results



Java Simple snake

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.