Java source code analysis

Source: Internet
Author: User

From: http://student.csdn.net/space.php? Uid = 130054 & Do = Blog & id = 21189

/*************************************** ***********************************
* File name: greedsnake. Java
* Author: timer2012

* Key points:
* 1) the main part has been integrated into an object, which can be operated using keyboard control.
**************************************** *********************************/
Import java. AWT .*;
Import java. AWT. event .*;
Import javax. Swing .*;
Import java. util .*;
// ================================================ ========
// Main class
// ================================================ ========
Public class greedsnake implements keylistener
{
Jframe mainframe;
Canvas paintcanvas;
Jlabel labelscore; // card count
Snake Model snkemodel = NULL; // snake
Public static final int canvaswidth = 200;
Public static final int canvasheight = 300;
Public static final int nodewidth = 10;
Public static final int nodeheight = 10;
//----------------------------------------------------------------------
// Greedsnake (): initializes the game interface
//----------------------------------------------------------------------
Public greedsnake ()
{
// Set interface elements
Mainframe = new jframe ('greedsnake ');
Container CP = mainframe. getcontentpane ();
Labelscore = new jlabel ('score :');
CP. Add (labelscore, borderlayout. North );
Paintcanvas = new canvas ();
Paintcanvas. setsize (canvaswidth + 1, canvasheight + 1 );
Paintcanvas. addkeylistener (this );
CP. Add (paintcanvas, borderlayout. center );
Jpanel panelbuttom = new jpanel ();
Panelbuttom. setlayout (New borderlayout ());
Jlabel labelhelp; // help information
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 (this );
Mainframe. Pack ();
Mainframe. setresizable (false );
Mainframe. setdefaclocloseoperation (jframe. exit_on_close );
Mainframe. setvisible (true );
Begin ();
}
//----------------------------------------------------------------------
// Keypressed (): Key Detection
//----------------------------------------------------------------------
Public void keypressed (keyevent E)
{
Int keycode = E. getkeycode ();
If (snkemodel. Running) Switch (keycode)
{
Case keyevent. vk_up:
Snake model. changedirection (Snake model. Up );
Break;
Case keyevent. vk_down:
Snake model. changedirection (Snake model. Down );
Break;
Case keyevent. vk_left:
Snake model. changedirection (Snake model. Left );
Break;
Case keyevent. vk_right:
Snake model. changedirection (Snake model. Right );
Break;
Case keyevent. vk_add:
Case keyevent. vk_page_up:
Snake model. speedup (); // Acceleration
Break;
Case keyevent. vk_subtract:
Case keyevent. vk_page_down:
Snail kemodel. speeddown (); // slow down
Break;
Case keyevent. vk_space:
Case keyevent. vk_p:
Snail kemodel. changepausestate (); // pause or continue
Break;
Default:
}
// Start again
If (keycode = keyevent. vk_r | keycode = keyevent. vk_s
| Keycode = keyevent. vk_enter)
{
Snake model. Running = false;
Begin ();
}
}
//----------------------------------------------------------------------
// Keyreleased (): NULL Function
//----------------------------------------------------------------------
Public void keyreleased (keyevent E)
{
}
//----------------------------------------------------------------------
// Keytyped (): NULL Function
//----------------------------------------------------------------------
Public void keytyped (keyevent E)
{
}
//----------------------------------------------------------------------
// Repaint (): draws the game interface (including snakes and food)
//----------------------------------------------------------------------
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 );
Required list NA = snakmodel. 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 = snake model. Food;
Drawnode (G, N );
Updatescore ();
}
//----------------------------------------------------------------------
// Drawnode (): Draw a node (snake or food)
//----------------------------------------------------------------------
Private void drawnode (Graphics g, node N)
{
G. fillrect (N. x * nodewidth, n. y * nodeheight, nodeWidth-1 );
}
//----------------------------------------------------------------------
// Updatescore (): Change the score card
//----------------------------------------------------------------------
Public void updatescore ()
{
String S = 'score: '+ snake model. Score;
Labelscore. settext (s );
}
//----------------------------------------------------------------------
// Begin (): Start the game and place the snake.
//----------------------------------------------------------------------
Void begin ()
{
If (snail kemodel = NULL |! Snake model. Running)
{
Snapshomodel = new snapshomodel (this, canvaswidth/nodewidth,
This. canvasheight/nodeheight );
(New thread (snail kemodel). Start ();
}
}
//----------------------------------------------------------------------
// Main (): Main Function
//----------------------------------------------------------------------
Public static void main (string [] ARGs)
{
Greedsnake GS = new greedsnake ();
}
}
/*************************************** ***********************************
* File name: Snake model. Java
* Author: C. Jason
* Key points:
* 1) Data Structure: matrix [] [] is used to store information on the map. If nothing is set to false,
* If there is a food or snake, set it to true; nodearray, A sort list, to save each
* Section 1. Food is used to store the location of food, while the node class stores the information of each location.
* 2) important functions:
* Changedirection (INT newdirection) is used to change the forward direction of a snake, and only
* Save the forward direction of the header because positions are used to specify other forward directions. Newdirection
* It must be different from the original direction, so the value in the opposite direction uses the same parity. In the test
* Ction % 2 is used! = Newdirection % 2.
* Moveon () is used to update the position of the Snake. For the current direction, the position of the head is changed accordingly. If it is out of bounds,
* End; otherwise, check whether there is any food (add the head) or body (end); if there is nothing, add the head,
* Remove the tail. The use of the shortlist data structure saves a lot of trouble.
**************************************** *********************************/
Import java. util .*;
Import javax. Swing .*;
//----------------------------------------------------------------------
// Node: node class
//----------------------------------------------------------------------
Class Node
{
Int X;
Int y;
Node (int x, int y)
{
This. x = X;
This. Y = y;
}
}
//----------------------------------------------------------------------
// Snake Model: Snake Model
//----------------------------------------------------------------------
Class snakmodel implements runnable
{
Greedsnake GS;
Boolean [] [] matrix; // The interface data is saved in the array.
Repeated list nodearray = new writable list ();
Node food;
Int Maxx; // The maximum width.
Int Maxy; // The maximum length.
Int direction = 2; // direction
Boolean running = false;
Int timeinterval = 200; // interval (speed)
Double speedchangerate = 0.75; // speed change degree
Boolean paused = false; // game status
Int score = 0;
Int countmove = 0;
// Up and down are even numbers, and right and left are odd numbers.
Public static final int up = 2;
Public static final int down = 4;
Public static final int left = 1;
Public static final int right = 3;
//----------------------------------------------------------------------
// Greedmodel (): initialization Interface
//----------------------------------------------------------------------
Public snkemodel (greedsnake Gs, int Maxx, int Maxy)
{
This. GS = GS;
This. Maxx = Maxx;
This. Maxy = Maxy;
Matrix = new Boolean [Maxx] [];
For (INT I = 0; I <Maxx; ++ I)
{
Matrix [I] = new Boolean [Maxy];
Arrays. Fill (Matrix [I], false); // set false for regions without snakes or food
}
// Initialize the snake
Int initarraylength = Maxx> 20? 10: Maxx/2;
For (INT I = 0; I <initarraylength; ++ I)
{
Int x = Maxx/2 + I;
Int y = Maxy/2;
Nodearray. addlast (new node (x, y ));
Matrix [x] [Y] = true; // true
}
Food = createfood ();
Matrix [food. x] [food. Y] = true; // true for food disposal
}
//----------------------------------------------------------------------
// Changedirection (): changes the direction of motion.
//----------------------------------------------------------------------
Public void changedirection (INT newdirection)
{
If (Direction % 2! = Newdirection % 2) // avoid conflict
{
Direction = newdirection;
}
}
//----------------------------------------------------------------------
// Moveon (): Snake Function
//----------------------------------------------------------------------
Public Boolean moveon ()
{
Node n = (node) nodearray. getfirst ();
Int x = n. X;
Int y = n. y;
Switch (direction)
{
Case up:
Y --;
Break;
Case down:
Y ++;
Break;
Case left:
X --;
Break;
Case right:
X ++;
Break;
}
If (0 <= x & x <Maxx) & (0 <= Y & Y <Maxy ))
{
If (Matrix [x] [Y]) // eat food or hit your body
{
If (x = food. X & Y = food. Y) // eat food
{
Nodearray. addfirst (food); // Add a node to the header
// Scoring rules are related to moving length and speed.
Int scoreget = (10000-200 * countmove)/timeinterval;
Score + = scoreget> 0? Scoreget: 10;
Countmove = 0;
Food = createfood ();
Matrix [food. x] [food. Y] = true;
Return true;
}
Else return false; // hit the body
}
Else // nothing happened
{
Nodearray. addfirst (new node (x, y); // Add the header
Matrix [x] [Y] = true;
N = (node) nodearray. removelast (); // remove the tail
Matrix [n. x] [N. Y] = false;
Countmove ++;
Return true;
}
}
Return false; // cross-border (hitting the wall)
}
//----------------------------------------------------------------------
// Run (): A snake motion thread
//----------------------------------------------------------------------
Public void run ()
{
Running = true;
While (running)
{
Try
{
Thread. Sleep (timeinterval );
} Catch (exception E)
{
Break;
}
If (! Paused)
{
If (moveon () // not completed
{
GS. repaint ();
}
Else // The game is over
{
Joptionpane. showmessagedialog (null, 'game over ',
'Game over', joptionpane. information_message );
Break;
}
}
}
Running = false;
}
//----------------------------------------------------------------------
// Createfood (): generate food and place of place
//----------------------------------------------------------------------
Private node createfood ()
{
Int x = 0;
Int y = 0;
Do
{
Random r = new random ();
X = R. nextint (Maxx );
Y = R. nextint (Maxy );
} While (Matrix [x] [Y]);
Return new node (x, y );
}
//----------------------------------------------------------------------
// Speedup (): speed up snake Movement
//----------------------------------------------------------------------
Public void speedup ()
{
Timeinterval * = speedchangerate;
}
//----------------------------------------------------------------------
// Speeddown (): slow down the speed of snake Movement
//----------------------------------------------------------------------
Public void speeddown ()
{
Timeinterval/= speedchangerate;
}
//----------------------------------------------------------------------
// Changepausestate (): changes the game status (pause or continue)
//----------------------------------------------------------------------
Public void changepausestate ()
{
Paused =! Paused;
}
}

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.