Greedy Snake Games ~

Source: Internet
Author: User
Tags date now dateformat int size stub

First look at the effect ~ this is able to wear the wall, the interface of God's horse does not beautify to provoke ~



Directly on the code:

Package com.snake;
Import Java.awt.Color;
Import Java.awt.Container;
Import Java.awt.Font;
Import Java.awt.Graphics;
Import Java.awt.Insets;
Import Java.awt.Toolkit;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import java.awt.event.KeyEvent;
Import Java.awt.event.KeyListener;
Import Java.awt.image.BufferedImage;
Import Java.math.BigDecimal;
Import Java.text.DateFormat;
Import Java.util.Date;

Import Java.util.Random;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JOptionPane;

Import Javax.swing.JPanel;
	public class Snakewindow extends JFrame {//Get screen Resolution int width = Toolkit.getdefaulttoolkit (). Getscreensize (). width;
	int height = Toolkit.getdefaulttoolkit (). Getscreensize (). Height;
	Array, which is used to save snakes, where 1 indicates that there is a snake body, and 0 means there is no static int[][] snake = new int[31][31];
	Whether to start Boolean isstarted = false;
	Mark the direction of the snake moving at this time (1: Left 2: Right 3: Top 4: Next) int direction = 1;
	Mark Snake head position int headx, heady;
	Mark Snake tail position int tailx, taily; Temporary location int[] tempx = new int[200];
	int[] Tempy = new int[200];
	int size = 0;
	Food position static int foodx = 0;
	static int foody = 0;
	Whether the food is eaten boolean iseated = true;
	Fractional String score = "0";
	Rank String level = "1";
	
	Snake's moving speed int speed = 100;
	JButton start = new JButton ("Start Game");
	JButton end = new JButton ("Ending Game");

	JButton about = new JButton ("about");
		Public Snakewindow () {this.settitle ("greedy snake");
		This.setsize (450, 400);
		This.setlocation ((width-450)/2, (height-400)/2);
		This.setresizable (FALSE);
		This.setvisible (TRUE);
		This.setdefaultcloseoperation (Exit_on_close);
		This.setlayout (NULL);
		Container C = This.getcontentpane ();
		Mypanel JP = new Mypanel ();
		Jp.setlayout (NULL);
		Jp.setsize (450, 400);
		
		JLabel sore = new JLabel ();
		Start.setfont (New Font ("Song Body", 15, 15));
		Start.setmargin (New Insets (0, 0, 0, 0));
		Start.setbounds (345, 30, 80, 30);
		End.setfont (New Font ("Song Body", 15, 15));
		End.setmargin (New Insets (0, 0, 0, 0));
		End.setbounds (345, 300, 80, 30); About.setfont (New Font ("SongBody ", 15, 15));
		About.setmargin (New Insets (0, 0, 0, 0));
		About.setbounds (345, 250, 80, 30);
		Jp.add (start);
		Jp.add (end);
		Jp.add (about);
		C.add (JP);  
New Thread (New Threadupadte ()). Start ();
Snakewindow.run ();
This.repaint ();
Start.requestfocus ();
End.requestfocus ();
		This.requestfocus (); Start.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO Auto-genera
				Ted Method Stub SnakeWindow.this.requestFocus ();
				Initsnake ();
				IsStarted = true;
				Start.setenabled (FALSE);
			Repaint ();
		
		}
		}); About.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO Auto-genera
					Ted Method Stub if (isstarted!= false) {isstarted = false;
					Repaint (); Joptionpane.showmessagedialog (NULL, "This game by the mouse brother production, welcome to mouse Brother bedroom exchange and learning."
					");
					SnakeWindow.this.requestFocus ();
				IsStarted = true; else {Joptionpane.showmessagedialog (null, "This game by rat BrotherBrother Production, Welcome to the mouse Brother bedroom exchange and learning.
				");
		
		}
				
			}
		}); End.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {//TODO auto-generate
			D method Stub system.exit (exit_on_close);
		
		}
		});
				This.addkeylistener (New KeyListener () {public void keypressed (KeyEvent e) {//TODO auto-generated method stub
				int key = E.getkeycode ();
							if (key = = e.vk_up) {if (Direction!= 4 && Direction!= 3) {try {direction = 3;
						Thread.Sleep (speed);
						catch (Interruptedexception E1) {//TODO auto-generated catch block E1.printstacktrace (); else if (key = = E.vk_down) {if (Direction!= 3 && Direction!= 4) {try
							{direction = 4;
						Thread.Sleep (speed);
						catch (Interruptedexception E1) {//TODO auto-generated catch block E1.printstacktrace ();
					}} else if (key = = E.vk_left) {if (Direction!= 2 && Direction!= 1) {try {direction = 1;
						Thread.Sleep (speed);
						catch (Interruptedexception E1) {//TODO auto-generated catch block E1.printstacktrace (); else if (key = = E.vk_right) {if (Direction!= 1 && Direction!= 2) {try {di
							Rection = 2;
						Thread.Sleep (speed);
						catch (Interruptedexception E1) {//TODO auto-generated catch block E1.printstacktrace ();

			public void keytyped (KeyEvent e) {//TODO auto-generated Method stub}}}}
	public void keyreleased (KeyEvent e) {//TODO auto-generated Method stub}}); public class Mypanel extends JPanel {public void paintcomponent (Graphics scr) {bufferedimage bi = new Buf
			Feredimage (450, BUFFEREDIMAGE.TYPE_INT_ARGB);
			
			Graphics g = bi.creategraphics ();
			G.setcolor (Color.Black); G.drawline (30, 30, 330, 30);
			G.drawline (30, 330, 330, 330);
			G.drawline (30, 30, 30, 330);
			
			G.drawline (330, 30, 330, 330);
			Time Date now = new Date (System.currenttimemillis ()); DateFormat d = dateformat.getdatetimeinstance (Dateformat.medium,dateformat.medium);
			Display date, time (exact to sub) String str = D.format (now);
			
			g.DrawString (str, 330, 360);
			G.setfont (New Font ("bold", 20, 20));
			g.DrawString ("Current score:", 345, 100);
			G.setfont (New Font ("bold", 40, 40));
			
			g.DrawString (score, 355, 140);
			G.setfont (New Font ("bold", 20, 20));
			g.DrawString ("Current rank:", 345, 170);
			G.setfont (New Font ("bold", 40, 40));
			
			
			
			
			g.DrawString ("LV:" +level, 355, 210); if (true) {for (int i = 0; i < i++) {for (int j = 0; J < + j) {if (snake[i][j] = 1 | | snake[i
							][J] = = 2) {int x = i * 10 + 30;
							int y = J * 10 + 30;
							SYSTEM.OUT.PRINTLN (x + "---" + y);
							G.setcolor (Color.White);
							G.fillrect (x, Y, 10, 10);
							G.setcolor (Color.Black); G.DrawRect (x, Y, 10, 10);
		}} scr.drawimage (bi, 0, 0, this);  } public void Initsnake () {for (int i = 0; i < i++) {for (int j = 0; J < + j) {if (= = 14 | | i = = 15 | | i = = 16 | |
				i = = &&) {Snake[i][j] = 1;
				else {Snake[i][j] = 0;
		}} direction = 1;
		HEADX = 14;
		heady = 14;
		TAILX = 17;
		taily = 14;
		Tempx[0] = 15;
		Tempy[0] = 14;
		TEMPX[1] = 16;
		TEMPY[1] = 14;
		TEMPX[2] = 17;
		TEMPY[2] = 14;
		size = 2;
		Score = "0";
		Level = "1";
		Speed = 100;
	Iseated = true; Class Threadupadte implements Runnable {public void run () {//TODO auto-generated a stub while (true)
{//System.out.println ("");
				
				Boolean bl = isstarted;
						try {if (isstarted = = True) {Thread.Sleep (speed);
						System.out.println ("111");
							if (direction = = 1) {int t = headX-1;
							if (T < 0) T = 29; if (snake[t][hEadY] = = 2) {size++;
								
								Eatandup ();
								Tempx[size] = TAILX;
								Tempy[size] = taily;
								headx--;
								if (HEADX < 0) HEADX = 29;
								Iseated = true;
								Snake[headx][heady] = 1; 
								Direction = 1;
								Score = Add (Score, "5");
								Up ();
							Repaint ();
	else if (snake[t][heady] = = 1) {//System.out.println ("t---" + t);
	SYSTEM.OUT.PRINTLN ("Heady---" + heady);
								System.out.println ("tempx[0]---" + tempx[0]); Joptionpane.showmessagedialog (null, "Snake bites itself, hang up ~ Game end ...")
								"); int i = Joptionpane.showconfirmdialog (null, "Start the game again.")
								");
									if (i = = 0) {direction = 1;
									Initsnake ();
								Iseated = true;
									else {//system.exit (exit_on_close);
									IsStarted = false;
									Init ();
									Start.setenabled (TRUE);
								Start.requestfocus ();
						} else {snake[tailx][taily] = 0;		Eatandup ();
								headx--;
								if (HEADX < 0) HEADX = 29;
								Snake[headx][heady] = 1; 
								Direction = 1;
							Repaint ();
							} if (direction = 2) {//system.out.println ("right");
							int t = HEADX + 1;
							if (T >) t = 0;
								if (snake[t][heady] = = 2) {size++;
								
								Eatandup ();
								Tempx[size] = TAILX;
								Tempy[size] = taily;
								headx++;
								if (Headx >) HEADX = 0;
								Iseated = true; 
								Direction = 2;
								Snake[headx][heady] = 1;
								Score = Add (Score, "5");
								Up ();
							Repaint ();
	else if (snake[t][heady] = = 1) {//System.out.println ("t---" + t);
	SYSTEM.OUT.PRINTLN ("Heady---" + heady);
								System.out.println ("tempx[0]---" + tempx[0]); Joptionpane.showmessagedialog (null, "Snake bites itself, hang up ~ Game end ...")
								"); int i = Joptionpane.showconfirmdialog (null, "Start the game again.")
								");
			if (i = = 0) {						Direction = 1;
									Initsnake ();
								Iseated = true;
									else {//system.exit (exit_on_close);
									IsStarted = false;
									Init ();
									Start.setenabled (TRUE);
								Start.requestfocus ();
								} else {snake[tailx][taily] = 0;
								Eatandup ();
								headx++;
								if (HEADX >29) HEADX = 0; 
								Direction = 2;
								Snake[headx][heady] = 1;
							Repaint ();
							} if (direction = = 3) {int t = headY-1;
							if (T < 0) T = 29;
								if (snake[headx][t] = = 2) {size++;
								
								Eatandup ();
								Tempx[size] = TAILX;
								Tempy[size] = taily;
								heady--;
								if (Heady < 0) heady = 29;
								Iseated = true;
								Snake[headx][heady] = 1;
								Score = Add (Score, "5");
								Up ();
							Repaint ();
	else if (snake[headx][t] = = 1) {//System.out.println ("t---" + t);	//						System.out.println ("HEADX---" + headx);
								System.out.println ("tempy[0]---" + tempy[0]); Joptionpane.showmessagedialog (null, "Snake bites itself, hang up ~ Game end ...")
								"); int i = Joptionpane.showconfirmdialog (null, "Start the game again.")
								");
									if (i = = 0) {direction = 1;
									Initsnake ();
								Iseated = true;
									else {//system.exit (exit_on_close);
									IsStarted = false;
									Init ();
									Start.setenabled (TRUE);
								Start.requestfocus ();
								} else {snake[tailx][taily] = 0;
								Eatandup ();
								heady--;
								if (Heady < 0) heady = 29;
								Snake[headx][heady] = 1; 
								Direction = 3;
							Repaint ();
							} if (direction = 4) {//system.out.println ("bottom");
							int t = heady + 1;
							if (T >) t = 0;
								if (snake[headx][t] = = 2) {size++;
								
								Eatandup ();
								Tempx[size] = TAILX; Tempy[size] = taily;
								heady++;
								if (heady >) heady = 0;
								Iseated = true;
								Snake[headx][heady] = 1; 
								Direction = 4;
								Score = Add (Score, "5");
								Up ();
							Repaint ();
	else if (snake[headx][t] = = 1) {//System.out.println ("t---" + t);
	System.out.println ("HEADX---" + headx);
								System.out.println ("tempy[0]---" + tempy[0]); Joptionpane.showmessagedialog (null, "Snake bites itself, hang up ~ Game end ...")
								"); int i = Joptionpane.showconfirmdialog (null, "Start the game again.")
								");
									if (i = = 0) {direction = 1;
									Initsnake ();
								Iseated = true;
									else {//system.exit (exit_on_close);
									IsStarted = false;
									Init ();
									Start.setenabled (TRUE);
								Start.requestfocus ();
								} else {snake[tailx][taily] = 0;
								Eatandup ();
								heady++;
								if (heady >) heady = 0;
	Snake[headx][heady] = 1;							Direction = 4;
							Repaint ();
							} if (iseated && isstarted) {//new Getfood ();
							Random Random = new Random ();
								do {Foodx = random.nextint (29);
	Foody = random.nextint (29);
							System.out.println (Foodx + "" + foody);
							
							}while (Snake[foodx][foody] = = 1);
							Snake[foodx][foody] = 2;
						iseated = false;
				} repaint ();
				catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
			public void Eatandup ()}}} (int i = size; I >= 1; i--) {tempx[i] = tempx[i-1];
		Tempy[i] = tempy[i-1];
		} tempx[0] = HEADX;
		
		Tempy[0] = heady;
		TAILX = Tempx[size];
	taily = Tempy[size];
			public void Init () {for (int i = 0; i < i++) {for (int j = 0; J < + j) {Snake[i][j] = 0;
		} score = "0";
		Level = "1";
		Speed = 100;
	Iseated = true; } public static String Add (string s1, string s2) {BigDecimal B1 = new BigDecimal (S1);
		BigDecimal b2 = new BigDecimal (s2);
		
	Return B1.add (B2). toString ();
			public void up () {if (Score.compareto (") = = 0) {level = ' 2";
		Speed-= 10;
			if (score.compareto) = = 0) {level = "3";
		Speed-= 10;
			if (Score.compareto (") = = 0) {level =" 4 ";
		Speed-= 10;
			if (Score.compareto ("a") = = 0) {level = "5";
		Speed-= 10;
			if (Score.compareto ("a") = = 0) {level = "6";
		Speed-= 10;
			if (score.compareto) = = 0) {level = "7";
		Speed-= 10;
			if (Score.compareto ("") = = 0) {level = "8";
		Speed-= 10;
			if (Score.compareto ("the") = = 0) {level = "9";
		Speed-= 5;
			} if (score.compareto) = = 0) {repaint ();
			Joptionpane.showmessagedialog (NULL, "Congratulations, Customs Clearance ~"); int i = Joptionpane.showconfirmdialog (null, "Start the game again.")
			");
				if (i = = 0) {direction = 1;
				Initsnake ();
			Iseated = true; else {//system.exiT (Exit_on_close);
				IsStarted = false;
				Init ();
				Start.setenabled (TRUE);
			Start.requestfocus ();
		} repaint ();
		
	} public static void Main (string[] args) {//TODO auto-generated method Stub new Snakewindow ();


 }
}
Beginners, may be more than the code redundancy ~ more Forgive ~ There are some of the logic of the problem, feeling a lot better, just like that .... I am mainly using a two-bit array to simulate ... Well, the simulations were long, uh huh.



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.