C language realizes the snake's structure chain list

Source: Internet
Author: User

The previous two blogs have restricted the use of C-language knowledge to a general array, but if you have a complete understanding of the C language, using structures and lists will make the structure of the program clearer and more logical. This blog will show you how to improve your previous programs with structures and lists.

First, we define a structure for the snake's node:

struct node{    COORD cor;     struct node *next;} node;

Coord structure I have already introduced in the previous article, here to borrow directly.

3,5*head;

Food is also defined accordingly by Coord and defines the head pointer. The next step is to change the previous code.

The main function is maintained as is, and then the functions appearing in the main function are changed from one to the other.

The Init_game function makes the following changes:

voidInit_game (void) {Head= (node *)malloc(sizeof(node)); Initialize the head of the snakehead->cor. X =3; Head->cor. Y =8; Head->next =NULL; intI, J;  for(i =0; i< -; i++) {         for(j =0; j< -; J + +) {            if(i = =0|| i = = -|| j = =0|| j = = -) Putchar ('#'); Else if(i = =5&&j = =3) Putchar ('*'); Else if(i = = food.) Y&&j = =Food . X) Putchar ('!'); ElsePutchar (' '); } Putchar ('\ n'); }}

The 3 and 8 in the function are the initial coordinates of the snake's head, so the readability of the program is reduced and the modification is inconvenient, and the corresponding macro definition can be improved before the function.

The next function that needs to be changed is the Move_snake function. It's easy to see that we need to do a lot of comparison coordinates, we simply write it as a function:

int cor_cmp (COORD pt1, COORD pt2) {    return (pt1. X = = Pt2. X&&pt1. Y = = pt2. Y);}

The Gotoxy function and the Generate_food function also make some changes:

voidGotoxy (COORD pt) {HANDLE hout; Hout=GetStdHandle (Std_output_handle); SetConsoleCursorPosition (Hout, PT);} COORD Generate_food (void) {COORD food_; Node*p=NULL; It is a good habit to initialize the defined pointer to null.intIn_snake =0; Srand ((unsignedint) Time (NULL));  Do{food_. X= rand ()% -; Food_. Y= rand ()% -;  for(p = head; P! = NULL; p = p->next)if(COR_CMP (food_,p->cor)) In_snake=1; }  while(Food_. X = =0|| Food_. X = = -|| Food_. Y = =0|| Food_. Y = = -||in_snake); returnFood_;}

Well, with these improved functions, we can write the Move_snake function. One of the questions we need to consider is how we can use the list to store the snake's coordinates. One of the advantages of a linked list is that it is dynamic, and its number of cells is not written like an array at the beginning of the death. It is natural to think that when a snake eats food, it appends a cell to the tail of the list. As for how to update the coordinates of the snake, there are two ways, the first is like the previous array method, from the beginning of the head of the snake to pass the coordinates, its code is as follows:

voidMove_snake (intdir) {Node*p =NULL; COORD Last=head->Cor, current; intGrow =0; Switch(dir) { CaseUp:head->cor. y--;  Break;  CaseDown:head->cor. y++;  Break;  CaseLeft:head->cor. x--;  Break;  CaseRight:head->cor. X + +;  Break; }    if(COR_CMP (head->Cor,food)) {Grow=1; Food=Generate_food (); }     for(p = head->next; p! = NULL; p = p->next) { Current= p->cor; P->cor =Last ; Last=Current ; } gotoxy (Head-cor); Putchar ('*'); if(grow) { for(p = head; P->next! = NULL; p = p->next)//Find the tail of the snake; P->next = (node *)malloc(sizeof(node)); Append node P->next->cor =Last ; P->next->next =NULL; Len++;        Gotoxy (food); Putchar ('!'); }    Else{gotoxy (last); Putchar (' '); }}

Because the methods of updating and arrays are almost identical, I won't start explaining them.

Another way to update the coordinates is to request a new memory space each time you move to store the moved snake head coordinates and let the head pointer to it, if the snake does not long section of the release of the tail of the memory space, in common is to add head to the tail. The code is as follows:

voidMove_snake (intdir) {Node*p,*t =NULL; Node*NEWH =NULL; NEWH= (node *)malloc(sizeof(node)); Open up memory space for new head NEWH->cor = head->cor; Assign the coordinates of the old head to the new head NEWH->next =Head; Point the new head's next pointer to the old head=NEWH; Point the head pointer to the newly opened memory spaceintGrow =0; Switch(dir) { CaseUp:head->cor. y--;  Break;  CaseDown:head->cor. y++;  Break;  CaseLeft:head->cor. x--;  Break;  CaseRight:head->cor. X + +;  Break; }    if(COR_CMP (head->Cor,food)) {Grow=1; Food=Generate_food (); } gotoxy (Head-cor); Putchar ('*'); if(Grow) {//If the long section no longer operates on the linked list Len++;        Gotoxy (food); Putchar ('!'); }    Else {         for(p = head; P->next->next! = NULL; p = p->next); Find the penultimate section T= p->Next; Record the address of the last section P->next =NULL; The next pointer of the penultimate section is assigned a value of 0 gotoxy (t-cor); Putchar (' ');  Free(t); Release the memory space of the tail of the Snake}}

The above is how to use the linked list to complete the coordinate update of two ways, and finally at the end of the game do not forget to release the requested memory space.

void free_node (node *h) {    *p,*q;      for (p = h; p! = NULL; p = q)        {= p->next        ;  Free (P);}    }

After printf ("GAME over"), add Free_node (head) to finish the finishing touches.

Oh, almost forgot to give the modified version of the IsAlive function, paste the code:

intIsAlivevoid){    intSelf_eat =0; Node*p =NULL;  for(p = head->next; p! = NULL; p = p->next)if(COR_CMP (P->cor, head->cor)) Self_eat=1; return(Head->cor. X = =0|| Head->cor. X = = -|| Head->cor. Y = =0|| Head->cor. Y >= -|| self_eat)?0:1;}

To this moment, the basic function of the snake has been realized for us to be a breeze. After the blog I will write some additional interesting features. You are welcome to study and discuss together.

C language realizes the snake's structure chain list

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.