Current location - Education and Training Encyclopedia - University rankings - C language curriculum design, what should a snake do?
C language curriculum design, what should a snake do?
2. 1 program function introduction

Snake game is a classic little game. A snake is in a closed wall, and a food appears randomly in the wall. By pressing the four cursor keys on the keyboard, the snake is controlled to move up and down, left and right. The snakehead knocks down the food, the food is eaten, and the snake grows 10 points. Then, food will appear, waiting for the snake to eat. If the snake hits the wall or passes through the body during the movement, the game is over.

2.2 Program overall design description

A game should have a starting part, a running part and an ending part (in fact, the starting part and the running part are integrated).

2.2. 1 design ideas

The key of this program is to show the shape of the snake and its movement. A small rectangle is used to represent a part of a snake. For each part of the body, add a rectangular block, and the snake head is represented by two parts. When moving, it must start from the head of the snake, so the snake can't move in the opposite direction, that is, it can't turn the tail of the snake into the head of the snake. If you don't press any key, the snake will go in the current direction by itself. When the player presses the effective direction key, the snake head will move in the specified direction, one body at a time. So after pressing the effective direction key, the position of the snakehead will be determined first, and then the snake body will move with the snakehead. The realization of the figure is to draw the snake from the new position of the snake head. At this time, due to the lack of clearing, the position of the original snake differs from that of the new snake by one unit, so it looks different. The appearance and disappearance of food is also drawing and covering rectangular blocks.

2.2.2 Data structure design and instructions for use?

Beginning part:

The game is running in graphical mode, so the first step must be to initialize the graphical mode, and then there must be a startup interface. Just like a book with a cover, I set the title screen of the game. In addition to the title screen of the game, I also set the welcome screen. After the title screen, you need to initialize the running part of the game, including drawing the running background of the game and initializing some important variables of the game.

Running parts:

As the core part of the game, there are many functions here, that is, there are many modules. First, let's simulate the snake's game mode: a snake suddenly appears in a certain world. It is short in stature and abnormal in motor nerves, and it can't stop its ADHD. In its world, there is only food, and it is hungry and greedy; Similarly, for some reason, food fell from the sky, but unfortunately it did not fall into the mouth; Hungry heroes, whether poisonous or not, don't ask the origin of food, and climb straight to food; It has eaten food, and its unimaginable assimilation ability makes food soon become a part of its own body and its body becomes longer. When it ate the first food, God didn't give it a second one, so it ate the second one and became longer, so there was a third one ... Its body kept getting longer, and it kept eating, regardless of the trouble caused by its long body-it was not convenient to turn around, and now it just opened its mouth wide so that the food could have a green passage. But one afternoon, it bit itself, and it remembered that it was a poisonous snake, so it fainted (not poisoned); Or when it rushed to the food, it lost control and hit the wall.

The first cycle: the first step, food appears; Step 2, the snake continues to move; Step 3, check whether the snake hits itself or the wall; Starting from the fourth step, the game has two branches (A and B):

Answer: Step four, the snake does not touch itself or the wall, and the snake moves on and draws the snake's movements. Step five, judge whether the snake has eaten food. If a snake eats food, its body will become longer and the original food will disappear. Step 6, let the player input a control command to make the snake change its moving direction in the second step of the next cycle; Seventh, the first step of the second cycle, repeat the first step;

B: Step four, the snake touches itself or the wall to stop the game.

At the end:

It is an established rule to display "Game over" at the end of the game, and my game is no exception. In addition to the game end screen, I also set up a game exit screen, "Start well, end well".

With the above general division, I divided the whole program into (13+2) modules (actually functions).

Program structure (flow chart)

Figure 2. 1 Flowchart

According to the task requirements to be processed, the input data and output results are planned, and the data structure of the stored data is determined.

The data structure of C language focuses on data types, so when programming in C language, variables, arrays, pointers, etc. The types used in the procedure should be planned as a whole. This is very important. If inappropriate variables or arrays are selected during this period, it will be very difficult to modify them later.

Now analyze the elements in the snake game, and then get their corresponding descriptions in the program:

Snake:

Basic description: length, color and position.

Corresponding data and data type: length-although it can be expressed in coordinates, in this case, the amount of operation will be large, so it is converted into a larger unit-the number of segments, which is described by the fixed length of each segment; Coordinates-integers; Color-integer; Position -x, y coordinates.

Supplementary note: the moving direction of the snake, the life of the snake.

Corresponding data and data types: These descriptions are designed to be associated with the key input part of the program and the judgment end part of the game. There are only four directions: up, down, left and right. You can set four corresponding integers: 3, 4, 2, 1. There are only two situations in life: death or life, corresponding to 0 or 1.

Food:

Basic description: color, position.

Corresponding data and data type: Since the color is set to be fixed, it will not be discussed any more. Position -x, y coordinates.

Supplementary note: the existence of food.

Corresponding data and data type: this is set to avoid food duplication and is related to the function of drawing food. There are only two values: 0 or 1 (no food or food).

Other elements: wall, because it exists in the display as a background, so there is nothing to say. The actual wall is a boundary composed of four straight lines, which is described by coordinates.

Variables are also needed: key values entered by the keyboard (as global variables, integers); Frequently used loop variables; Custom fill pattern; An array of characters describing the text; The score of the game; The speed of the game (the speed of the snake).

Fig. 2.2 Flow chart of key algorithm for snake's non-stop movement.

2.2.4 Description of functions and procedures of each module

The realization idea and algorithm flow chart of the main modules are expounded:

Key point -Snakemove ():

The snake keeps moving, that is, the position of the next section of the snake replaces the previous section. In the computer, the position coordinates of the next section of the snake become the position coordinates of the previous section. Above, the position coordinates of the snake have been defined as array type, and a set of coordinates corresponds to the position of a part. Suppose there is an i+ 1 segment, from 0 to I, the I-segment coordinate takes the i- 1 segment coordinate, and the i- 1 segment coordinate takes the i-2 segment coordinate ... until the first section 1. The coordinates of the 0 th segment, that is, the coordinates of the snake head, will change in a certain direction with the length of each segment of the snake. The coordinate rotation of the snake needs a loop statement to continue. ?

Program result

Run the program and get the following initial interface diagram:

Figure 2.3 Program Result Diagram

A small rectangle is used to represent a part of a snake. For each part of the body, add a rectangular block, and the snake head is represented by two parts:

Figure 2.4 Program Result Diagram

The snake didn't touch itself or the wall. It moved on:

Figure 2.5 Program Result Diagram

At the end of the game, "Game over" is displayed.

Figure 2.6 Program Result Diagram

2.3 program source code and comments

# define N 200

# include & ltgraphics.h & gt

# include & ltstdlib.h & gt

# include & ltdos.h & gt

# Define left 0x4b00

# Define right 0x4d00

# Define 0x5000 downward

# Define up to 0x4800

# Define ESC 0x0 1 1b

int i,key

Int score = 0; /* Score */

Int gamespeed = 50000/* Adjust the game speed by yourself */

Structured food

int x; /* food abscissa */

int y; /* The ordinate of food */

Int yes/* Judge whether the variable of food will appear */

} food; /* The structure of food */

Structural snake {

int x[N];

int y[N];

Int node; /* The number of knots of a snake */

Int direction; /* The moving direction of the snake */

Int life/* Snake's life, 0 is alive, 1 is dead */

} snake;

void Init(void); /* Graphics driver */

Void Close (invalid); /* End of chart */

Void DrawK (invalid); /* Start screen */

void game over(void); /* End the game */

Void play (Void); /* The specific process of playing the game */

void PrScore(void); /* Output results */

/* Main function */

Invalid primary (invalid) {

init(); /* Graphics driver */

DrawK(); /* Start screen */

Playfulness (); /* The specific process of playing the game */

close(); /* End of graph */}

/* Graphics driver */

void Init(void){

int gd=DETECT,GM;

registerbgidriver(EGA VGA _ driver);

init graph(& amp; gd,& ampgm," c:\ \ program files \ \ winyes \ \ tc20h \ \ bgi ");

clear device(); }

/* Start the screen with (50,40) in the upper left corner and (6/kloc-0,460 */

void DrawK(void){

/*setbkcolor (light green); */

set color( 1 1);

setlinestyle(SOLID_LINE,0,THICK _ WIDTH); /* Set the line type */

for(I = 50; I & lt=600; I+= 10)/* Draw a fence */? {

Rectangular (I, 40, i+ 10, 49); /* higher than */

Rectangular (I, 45 1, I i+ 10/0,460); /* Below */? }

for(I = 40; I & lt=450; i+= 10)? {

Rectangular (50, I, 59, I+10); /* Left */

Rectangular (60 1, I, 6 10, I+10); /* Right */}}

/* The specific process of playing the game */

Invalid game (invalid) {

randomize(); /* Random number generator */

food . yes = 1; /* 1 means that new food needs to appear, and 0 means that food already exists */

snake . life = 0; /* alive */

snake . direction = 1; /* Right direction */

snake . x[0]= 100; snake . y[0]= 100; /* snakehead */

snake . x[ 1]= 1 10; snake . y[ 1]= 100;

snake . node = 2; /* Number of sections */

PrScore(); /* Output score */

And (1)/* You can play the game repeatedly and press ESC to end */? {

And (! Khit ())/* The snake moves by itself without pressing the button */? {

If(food.yes== 1)/* Need new food */{

food . x = rand()% 400+60;

food . y = rand()% 350+60;

And (food.x% 10! =0)/* After the food appears randomly, the food must be in the whole grid before the snake can eat */

food . x++;

And (food.y% 10! =0)

food . y++;

food . yes = 0; /* There is food on the screen */}

If(food.yes==0)/* If there is food on the screen, */{will be displayed.

Setcolor (green);

Rectangular (food.x, food.y, food.x+ 10, food.y-10); }

for(I = snake . node- 1; I>0; I-)/* Every link of the snake moves forward, which is the key algorithm of the snake */{

snake . x[I]= snake . x[I- 1];

snake . y[I]= snake . y[I- 1]; }

/* 1, 2, 3, 4 means right, left, up and down, and this judgment can move the snake head */

Switch (serpentine direction)

case 1:snake . x[0]+= 10; Break;

Case 2: snake.x [0]-=10; Break;

Case 3: snake.y [0]-=10; Break;

Case 4: snake.y [0]+=10; Break; }

for(I = 3; I < snake. node; I++)/* Judge whether you hit yourself from the fourth quarter of the snake, because the snake head has two sections, and it is impossible to turn around in the third quarter */{

if(snake . x[I]= = snake . x[0]& amp; & ampsnake.y[i]==snake.y[0]) {

game over(); /* Display failed */

snake . life = 1;

Break; } }

if(snake . x[0]& lt; 55 | | snake . x[0]& gt; 595 | | snake . y[0]& lt; 55||

snake . y[0]& gt; 455)/* Did the snake hit the wall */{

game over(); /* This game is over */

snake . life = 1; /* The snake is dead */}

If(snake.life== 1)/* After the above two judgments, if the snake dies, jump out of the inner loop and start again */

Break;

if(snake . x[0]= = food . x & amp; & snake.y [0] = = food.y)/* After dinner */{

set color(0); /* Remove food from the picture */

Rectangular (food.x, food.y, food.x+ 10, food.y-10);

snake . x[snake . node]=-20; snake . y[snake . node]=-20;

/* Put the new paragraph out of sight first, and take the position of the previous paragraph in the next cycle */

snake . node++; /* The snake's body has a long section */

food . yes = 1; /* New food needs to appear on the screen */

Score+=10;

PrScore(); /* Output new score */}

set color(4); /* Draw a snake */

for(I = 0; I < snake. node; i++)

Rectangular (snake.x[i], snake.y[i], snake.x[i]+ 10,

snake . y[I]- 10);

Game speed;

set color(0); /* Remove the last paragraph of the snake in black */

Rectangular (snake.x[snake.node- 1], snake.y[snake.node- 1],

snake . x[snake . node- 1]+ 10,snake . y[snake . node- 1]- 10); } ? /*endwhile(! kbhit)*/

If(snake.life== 1)/* If the snake dies, jump out of the loop */

Break;

key = BIOS key(0); /* Receive button */

If(key==ESC)/* Press ESC to exit */

Break;

other

if(key = = UP & amp; & Snake, direction! =4)

/* Judge whether to move in the opposite direction */

snake . direction = 3;

other

if(key = = RIGHT & amp; & Snake, direction! =2)

snake . direction = 1;

other

if(key = = LEFT & amp; & Snake, direction! = 1)

snake . direction = 2;

other

if(key = = DOWN & amp; & Snake, direction! =3)

snake . direction = 4;

}/*endwhile( 1)*/}

/* Game over */

void GameOver(void){

clear device(); ?

PrScore();

Setcolor (red);

settextstyle(0,0,4);

Outtextxy (200,200, "Game over");

getch(); }

/* Output results */

void PrScore(void){

char str[ 10];

Setfillstyle(SOLID_FILL, yellow);

Ba (50,15,220,35);

set color(6);

settextstyle(0,0,2);

sprintf(str," score:%d ",score);

outtextxy(55,20,str); }

/* End of chart */

To close (void) {

getch();

closegraph();

}