C language realization of the whole of the snake by the array of articles

Source: Internet
Author: User
Tags abs

Snake Game design idea is very simple, I believe there are some programming experience students are not helpless, but I just touch programming, this little snake game but let me take a lot of brains, now learning programming has been almost a year, the previous few days and looked again K&r, Plan to write a few snake procedures to consolidate knowledge. I intend to write a number of snake blog, from the simple rough start, and constantly improve, hoping to give beginners C language students a little reference.

Not much to say, we start now, first we tidy up the idea. First of all, we must be clear, since the snake game theoretically can continue indefinitely, then the game subject must be a cycle. The movement of the snake is done in this cycle. If it is a beginner programming, it may be curious how to let the snake move, where we are by constantly changing the coordinates of the snake, and then constantly refresh the screen according to the coordinates of the snake to visually form the movement of the snake. Let's start by looking at the main function:

1 intMain ()2 {3     intDir=Up ; The initial direction defaults to up, and up is a macro4      while(1){5 Print_game (); Print Games6Dir=Get_dir (dir); Get Directions7 Move_snake (dir); Moving the snake body8         if(!IsAlive ())//Judge the life state of a snake9              Break;Ten     } Oneprintf"Game over\n"); A}

The overall idea of the game is relatively simple. With the framework we come to the concrete implementation, first consider the use of the data structure, as the blog name shows, this time I only use arrays, not using linked lists and structs. Then we use a two-dimensional array char map[17][17] to represent the map, using a one-dimensional array unsigned char snake[15] to represent the snake's coordinates. Char is used here because of the principle of saving the province, we are a small game of 17*17 size, char enough.

#include <stdio.h>#include<conio.h>#include<stdlib.h>#include<windows.h>
#include <time.h>#defineUp 72//72,80,75,77 is the key value corresponding to the arrow key#defineDown 80#defineLeft 75#defineRight 77#defineSNAKE 1#defineFood 2#defineBAR 3Charmap[ -][ -] = {0 }; Initialize map unsignedCharsnake[ the] = { the }; Initialize the snake head coordinatesunsigned charFood = 68; Initializing food coordinatesCharLen =1; Snake length

Only use the array to do the snake, in the snake coordinates and food coordinates of the storage will be more troublesome, after all, our game coordinates are two-dimensional, here I take the method of bitwise operation, a unsigned char type of variable eight bits, the first four records x coordinate, the last four bits of the Y coordinate, four bits, the maximum value is 15, So I set the size of the 17*17, (15+ boundary) * (15+ boundary). If you think the map is too small, it is possible to use int or long. Since we often do the conversion of numbers with X, Y, we write it as a function.

void Char Char Char *y) {    4;     Char 4 4      ; Note that there must be a mandatory type conversion}

When the called function needs to return more than two parameters, the value to be returned is written as a pointer parameter, as in the above function.

Next, let's fill in the function one by one called in the main function.

voidPrint_game (void){    intI, J;  for(i =0; i< -; i++) {//Draw the game according to the situation on each point on the map for(j =0; j< -; J + +) {            if(Map[i][j] = =0) Putchar (' '); Else if(Map[i][j] = =SNAKE) Putchar ('*'); Else if(Map[i][j] = =BAR) Putchar ('#'); Else if(map[i][j]==Food ) Putchar ('!'); } Putchar ('\ n'); } Sleep ( -); The Hibernate function, which suspends a process or thread 100ms, is included in the Window.h system ("CLS"); Clear screen function, included in Stdlib.h}

Get directions for a function note consider the snake body over a section of the snake can not turn back the problem, the code is as follows:

 int  get_dir (int   Old_dir) { int  new_dir = Old_dir;  if   (_kbhit ()) {//Kbhit () and Getch ()        Combination to implement keyboard response _getch ();    New_dir  = _getch (); The Getch () function uses two times  if  (len > 1  &A mp;& (ABS (new_dir-old_dir) = = 2  | | ABS (NEW_DIR-OLD_DIR) = = 8   = Old_dir;  return   New_dir;}  

The Getch () function takes two times because the first return value indicates the character of the key extension, and the second call returns the actual key code. ABS is the absolute value function, the reason is to compare the absolute function with the 2,8 is a macro definition of the direction of the law observed. The underscore in front of Getch () and Kbhit () is more secure because some functions need to use an underlined version in the VS environment.

Next is the function of moving the snake body (most of the game's contents are in it):

voidMove_snake (intdir) {    intLast = snake[0],current; Last and current updates to the snake coordinates afterintI, J; intgrow=0; Determine if you want to grow your body unsignedCharx, Y,fx,fy; Snake coordinates and food coordinates tran (foods,&AMP;FX, &FY); Tran (snake[0], &x, &y); Switch(dir) {//update the snake head coordinates Caseup:y--;  Break;  Casedown:y++;  Break;  Caseleft:x--;  Break;  Caseright:x++;  Break; } snake[0] = ((x ^0) <<4) ^y; Swap x, y back to one numberif(snake[0] ==Food ) {Grow=1; Food=Generate_food (); Produce new Food} for(i =0; i<len; i++{//Snake movement key, by assigning the original coordinates of the snake head to the second section, the original second section is assigned to the third section, go down, complete the snake coordinate updateif(i = =0)//If there are only headers, skip, because the snake head coordinates have been updated beforeContinue; Current=Snake[i]; Stores the current operation's snake-node coordinates in SNAKE[I]=Last ; Complete the current operation update of the snake node coordinates last=Current ; Last record is the coordinates of the previous operation of the Snake festival, this operation has ended, so the current is assigned toif(Grow) {Snake[len]=Last ; Len++; }     for(i =0; I < -; i++)//Add borders and food to the map for(j =0; J < -; J + +)            if(i = =0|| i = = -|| j = =0|| j = = -) Map[i][j]=BAR; Else if(i = = Fy&&j = =FX) Map[i][j]=Food ; ElseMap[i][j]=0;  for(i =0; i < Len; i++) {//Add the snake to the map to Tran (Snake[i],&x, &y); if(Snake[i] >0) Map[y][x]=1; }}

There is a function for producing food, Generate_food (), which uses the random number generation function to generate food coordinates, the code is as follows:

UnsignedCharGenerate_food (void) {unsignedCharFood_,fx,fy; intIn_snake=0, I; Srand ((unsignedint) Time (NULL));  Do{food_= rand ()%255; Tran (Food_,&AMP;FX, &FY);  for(i =0; i < Len; i++)            if(Food_ = =Snake[i]) In_snake=1; }  while(FX = =0|| FX = = -|| FY = =0|| FY = = -||in_snake); returnFood_;}

The random number generation function, which is generally composed of the Srand () and Rand () functions, which provide the seed for the rand () function to generate a more random number in the current time parameter. Here a filter is made using the Do and statement, and the food that ends up within the boundary and no longer snakes.

It is best to have a function to judge the fate of a snake, directly on the code:

intIsAlivevoid){        intSelf_eat =0, I; unsignedCharx, temp, y; Tran (snake[0], &x, &y);  for(i =1; i < Len; i++)        if(snake[0] ==Snake[i]) self_eat=1; return(x = =0|| x = = -|| y = =0|| Y >= -|| self_eat)?0:1;}

Determine if the snake hit the border or self-feeding.

Well, with these functions, assembling them becomes our simple snake game. The game screen is as follows:

Although quite humble, because of the use of full-screen Refresh method, splash screen is more serious, but also is a little perfectly formed, the function has also, the code is only about 150 lines. In the next blog I will continue to toss the game until it looks more pleasing to the eye. Because I am still a novice, this is also a novice to the tutorial, what questions Welcome to point out.

C language realization of the whole of the snake by the array of articles

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.