The greedy snake is a very classic mobile game. It has many algorithms that analyze a relatively excellent algorithm in detail. First introduce the seven classes of the main use:
l Wormmain: The most important class, control all other classes of operation and destruction.
l Wormpit: Process the keyboard input event and instantiate the WORM class and Wormfood class.
l Worm: Abstract the attributes and movements of greed snake
l Wormfood: Abstract food properties and action
l WormScore: Class used to record the score
l Wormlink: Abstract snakes, saved this coordinate, direction, and all states.
l WORMEXCEPTION: Handling an exception class
Basic concept introduction
Festival: A snake can see a "small latcher" with many squares, I call it as a section. The day is the smallest unit on the snake.
Segment: When many festivals are connected to a straight line, I call it as a paragraph. There is only one piece of greed snake above, and it becomes two paragraphs if it turns.
Link list: The element unit of the linked list is the segment. And the last element of the linked list indicates the head segment of the snake.
Coordinate system: The coordinates in the MIDP are (0, 0) in the upper left corner, and incremented to the right, and the Y is incremented down.
WORM class
A complete greed snake is made up of a section. The first element saved in the list is the tail section of the snake, and the last element is the head section of the snake. When the snake moves, its head segment is increased and the end is reduced. If it eats food, the tail segment does not reduce the section. That is, the snake is from the beginning of the head.
The following code segments show various properties saved by the WORM class:
/ * Crescent snake may move the direction * / public final static byte down = 2; public final static byte left = 4; public final static byte right = 6; public final static byte Up = 8; // Currently eating the snake Direction Private Byte CurrentDirection; // Save the list of greed for each section of the snake Price Worm = New Vector (5, 2); // Do you need to update status private bolean needupdate; // Is it in motion boolean moveonnextUpdate; // Eat food private boolean haseten; // Eat the initial position, length and direction of the snake, Private Final Static int init_x = 3; private final static int init_yle = 8; private final static int init_len = 8; private final static botty init_dir = right ;
The following focuses on several methods in the WORM class:
l public void setdirection (byte direction)
This method is used to change the direction of greed snake movement, only 90 degrees. Look at the implementation code below:
IF ((Direction! = CurrentDirection) &&! needupdate) {// Remove the last element in the list (the head of the snake) WORM.lastelement (); int x = sl.Getendx (); int x = sl.getendx () y = sl.geetendy (); // Different motion direction coordinates are also different Switch (Direction) {case up: // When this is moved up, IF (CurrentDirection! = Down) {y -; Needupdate = true;} Break; case down: // When this is moved down, if (currentdirection! = up) {y ; needupdate = true;} Break; case left: // When this is moved to the left (CurrentDirection! = Right) {x-; Needupdate = true;} Break; Case Right: // When this is moved to right, if (currentdirection! = left) { x ; needupdate = true;} Break;} // When the change needs to update if (NeewUpdate == True) {Worm.Addelement (New Wormlink (X, Y, 0, Direction); CurrentDirection = Direction;}} L Public void Update (Graphics G)
This function is updated to eat snake status. Each update increases the head, and the tail is reduced. If it eats the food tail segment, it will not be reduced. It seems like a whole snake.
// Increase the head = (Wormlink) Worm.lastelement (); Head.IncReaseLength (); // If you don't eat food, the tail is reduced by the tail if (! Haseten) {WORMLINK TAIL; tail = (); Int tailx = tail.getx (); int taily = tail.gety (); // If the tail length is 0, it deletes tail.Decreaseledth (); if (tail.getlength () == 0) {WORM.RemoveElement (Tail);} // Tail reduction is g.SetColor; DrawLink (G, Tailx, TAILY, TAILX, TAILY, 1);} else {// If you eat If you go to food, you don't delete the tail haseten = false;} Needupdate = false; // Confirm whether IF in the boundary (! Wormpit.InBoundx (head.getendx (), head.getendy ())) {// If not, die Throw new WORMEXCEPTION ("over the edge");} headx = (byte) Head.Getendx (); heady = (byte) Head.Getendy (); // The head of the greedy snake Add a G.SetColor (WormPit.draw_COLOUR Drawlink (G, Headx, Heady, Headx, Heady, 1); // Judgment whether it eats itself (INT i = 0; I This function is used to draw a section of the snake, a complete snake is a one-piece. // Convert the length into a pixel length len * = Wormpit.cell_size; // (x1 == x2) Description This section is vertical if (x1 == x2) {// Put X1 into pixel length x1 * = WormPIT. Cell_size; // (Y2 Draw a complete greedy snake Wormlink sl; INT X1, X2, Y1, Y2; INT LEN; for (int i = 0; i Wormlink class The greedy snake is made up of a section. Because it often has some of the section a line forming section, this is a relatively effective way to save the entire snake. [X, y] indicates the coordinates of the section head, and then the head of the segment begins to follow the sections in the direction. (The head of the head and the tail of the snake is not a concept) The following code segment is the segment attribute in Wormlink: // segment head coordinate private int x, y; // segment length private int LEN; // Mobile direction private byte DIR; The following focuses on several important functions: l Public void DecreaseLength () This is a decrease from the head of the segment. // The total length of the first segment is reduced by 1LEN-; Switch (Dir) {// Different directions are different from Case Worm.Left: X -; Break; Case Worm.right: x ; Break; Case Worm .UP: Y ---; Break; Case Worm.Down: y ; Break;} public Void Paint (Graphics G) Draw a complete greedy snake Wormlink sl; INT X1, X2, Y1, Y2; INT LEN; for (int i = 0; i Wormlink class The greedy snake is made up of a section. Because it often has some of the section a line forming section, this is a relatively effective way to save the entire snake. [X, y] indicates the coordinates of the section head, and then the head of the segment begins to follow the sections in the direction. (The head of the head and the tail of the snake is not a concept) The following code segment is the segment attribute in Wormlink: // segment head coordinate private int x, y; // segment length private int LEN; // Mobile direction private byte DIR; The following focuses on several important functions: l Public void DecreaseLength () This is a decrease from the head of the segment. // The total length of the first segment is reduced by 1LEN-; Switch (Dir) {// Different directions are different from Case Worm.Left: X -; Break; Case Worm.right: x ; Break; Case Worm .UP: Y ---; Break; Case Worm.Down: y ; Break; l Public Boolean Contains (int x, int y) Determine the coordinate [X, Y] is included in the segment Switch (Dir) {// Different Directional Judgment Methods are also different case Worm.Left: return ((y == this.y) && ((x <= this.x) && (x> = getEndx ()) ))); Case Worm.right: Return (Y == THIS.Y) && ((x> = this.x) && (x <= getEndx ()))); Case Worm.Up: Return ((x = = this.x) && (y <= this.y) && (y> = getendy ()))))))))); Case Worm.Down: Return ((x == this.x) && ((Y> = this. Y) && (y <= getendy ())))))))))))))))); The tail X coordinate of this section (the last coordinate of the first grid pointing in the direction), when this paragraph is the head segment of the snake, the first coordinate of the head is the first coordinate. // Different direction judgment method is not the same if (DIR == Worm.Left) Return X-LEN; if (Dir == Worm.right) Return X Len; Return X; Wormpit class Worm and Wormfood include Worm and Wormfood. The greedy snake will move in the picture to find food. If it eats food it will be a long. If it encounters a border or eats yourself. Here are several important functions: l Private int Round (int val) Ask the closest pixel number that can be kept removed by the lattice width (Cell_Size). INT delta = (VAL- (start_pos * 2))% Cell_Size; Return (Val - Delta); l Public void keypressed (int Keycode) Process the keyboard event. When controlling the movement of the snake and changing the direction. // Corresponding to the game key Switch (getGameAction (keycode)) {Case canvas.up: myworm.setdirection (Worm); Break; Case Canvas.down: MyWorm.SetDirection (Worm.Down); Break; Case Canvas.Left : MyWorm.Setdirection (Worm.Left); Break; Case Canvas.right: myworm.setdirection (Worm.right); Break;} l Private Void PaintPitContents (Graphics G) Redraw all the elements on the screen / / Update the state of the greedy Snake MYWORM.UPDATE (G); / / The position of the head and the food of the food will eat food IF (myfood.isat (myWorm.getx (), myworm.gety ())) { MyWorm.eat (); score = level; foodeaten ; if (Foodeaten> (Level << 1)) {/ * Add game difficulty * / forcerendraw = true; foodeaten = 0; Level ; if (TonePlayer! = null) { Try {TonePlayer.SetMediatime (0); TonePlayer.Start ();} Catch (MediaException me) {}}} else {}}} else {}}} else {}}} else {}}} else {}}} else {=}}} else {(audioplayer! = null) {Try {Manager.Playtone (69, 50, 100); // Play Audio} catch (MediaException me) {}}} G.SetColor (WormPit.rase_COLOUR); // Pack Long Square (Width of Three Western) G.fillRect ((Width - (Score_Char_WIDTH * 3)) - Start_pos, Height-start_pos, (Score_Char_Width * 3), Score_Char_HEight); g .SETCOLOR (WormPit.draw_COLOUR); // Displays a new score g.drawString (" score, width - (score_char_width * 3) - start_pos, height - start_pos, graphics.top | graphics.left; // Regeneration Food myfood.Regenerate (); int x = Myfood.getx (); int y = myfood.gety (); while (myworm.contains (x, y)) {// If the food and greedy snake are repeated, regenerate myfood.Regenerate (); x = myfood .GETX (); y = myfood.gety ();}} // Draw food myfood.paint (g);} catch (wormexception se) {gameover = true;} l public void Paint (Graphics G) Picture of the entire screen (overloaded the Paint function)