Algorithm Analysis of Greed Snake (1)
James @ www.chenshen.com
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:
/ * Greedy snake may move the direction * /
Public final static botty down = 2;
Public final static byte left = 4;
Public final static byte right = 6;
Public final static byte Up = 8;
// Current direction of the snake
PRIVATE BYTE CURRENTDIRECTION;
/ / Save the list of each paragraph of the snake
Private Vector Worm = New Vector (5, 2);
/ / Do you need an update status?
Private Boolean Needupdate;
/ / Whether it is in sports
Private Boolean MoveonNextUpdate;
/ / Do you eat food?
Private boolean haseten;
// Eat the initial position, length and direction of snake
PRIVATE FINAL static int init_x = 3;
PRIVATE FINAL INT INT_Y = 8;
PRIVATE FINAL INT init_len = 8;
PRIVATE FINAL = Right;
About the Author: Shen Chen, senior programmer, SCJPwww.chenshen.comJinaShen @ BenQ.com
August 10, 2003