Snake game program (C language)

Snake game program (C language)

"This is the third day I participated in the Gengwen Challenge. For details of the event, please see: Gengwen Challenge"

This time I will share a small snake game program (C language) written by me

Recently, I started to write some small games and small game programs in C language without incident in the summer vacation. Of course, this greedy snake is a classic in the classics, so I started writing first. 

File references

#include<redio.h>//input and output #include<time.h>//Used to get random numbers #include<windows.h>//Control the DOS interface #include<stdlib.h>//Defines some macros and general utility functions #include<conio.h>//Receive keyboard input and output Copy code

Function declaration

/**************************Function declaration********************* ******/ void gotoxy(int x,int y);//Set the cursor position int color(int c);//change text color void printsnake();//Character painting--snake void welcome();//Start interface void createMap();//Draw a map void scoreandtips();//Points and tips on the right side of the game interface void initsnake();//Initialize snake body, flower snake body void createfood();//Create and randomly appear food int biteself();//Judging whether to bite yourself void cantcrosswall();//Set the situation that the snake hits the wall void speedup();//speed up void speeddown();//Decelerate void snakemove();//Control the direction of the snake void keyjianpan();//Control keyboard keys void Lostdraw();//Game over interface void endgame();//Game over void choose();//The choice after the game fails void File_out();//Read the highest score in the file void File_in();//Store the highest score file void explation();//Game description Copy code

Game welcome interface

/********************Game welcome interface***********************/ int color(int c)//color function { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),c);//Change the text color return 0; } void gotoxy(int x,int y)//Set the cursor position { COORD c; cX=x; cY=y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c); } void printsnake() { int i,j=10; gotoxy(37,21); color(14); printf("Zhang Yang is greedy to eat snakes\n welcome you!"); gotoxy(19-1,9); color(12); printf("Zhang Yang"); gotoxy(23-1,9); color(12); printf("Zhang Yang"); gotoxy(27-1,9); color(12); printf("Zhang Yang"); gotoxy(27-1,11); color(12); printf("Zhang Yang"); gotoxy(19-1,13); color(12); printf("Zhang Yang"); gotoxy(23-1,13); color(12); printf("Zhang Yang"); gotoxy(27-1,13); color(12); printf("Zhang Yang"); for(i=20;i<28;i++) { gotoxy(i+10,j); color(j-10); printf("Zhang Yang"); j++; } for(i=30;i<38;i++) { gotoxy(i+10,j); color(j-10); printf("Zhang Yang"); j--; } for(i=40;i<48;i++) { gotoxy(i+10,j); color(j-10); printf("Zhang Yang"); j++; } for(i=50;i<58;i++) { gotoxy(i+10,j); color(j-10); printf("Zhang Yang"); j--; } for(i=60;i<68;i++) { gotoxy(i+10,j); color(j-10); printf("Zhang Yang"); j++; } for(i=70;i<77;i++) { gotoxy(i+10,j); color(j-10); printf("Zhang Yang"); j--; } gotoxy(87,11); color(11); printf("Zhang Yang"); gotoxy(91,11); color(11); printf("Zhang Yang"); gotoxy(95,11); color(11); printf("Zhang Yang"); gotoxy(99,11); color(11); printf("Zhang Yang"); } /*************************Main function ************************ ********************/ int main() { system("mode con cols=140 lines=40");//Set the width and height of the console printsnake();//Draw character snake return 0; } Copy code

Welcome Screen

/********** Everyone can design a different welcome interface according to their own creativity. **********************//********************** Start interface** *********************************/

void welcome() { int n; int i,j=1; color(14); for (i=24;i<=30;i++) { for (j=35;j<=82;j++) { gotoxy(j,i); if(i==24||i==30) { printf("-"); } else if(j==35||j==82) { printf("|"); } } } color(12); gotoxy(45,26); printf("1. Start the game"); gotoxy(65,26); printf("2. Game description"); gotoxy(45,28); printf("3. Exit the game"); gotoxy(48,32); color(3); printf("Please select [1 2 3]:[ ]\b\b"); color(14); scanf("%d",&n); switch(n) { case 1: system("cls");//Clear the screen break; case 2: break; case 3: exit(0); break; default: color(12); gotoxy(40,38); printf("Please enter a number between 1-3!"); getch();//Enter any key system("cls");//Clear the screen printsnake(); welcome(); } } int main() { system("mode con cols=140 lines=40");//Set the width and height of the console printsnake();//Draw character snake welcome(); return 0; } Copy code

Combine the two together to form the main interface at the beginning

Game main form design

/****************************Game main form design**************** *****************/ void createMap()//Create a map { int i,j; for (i=0;i<58;i+=2) { gotoxy(i,0); color(5); printf(" "); gotoxy(i,26); printf(" "); } for (i=1;i<26;i++) { gotoxy(0,i); printf(" "); gotoxy(56,i); printf(" "); } for (i=2;i<56;i+=2) { for (j=1;j<26;j++) { gotoxy(i,j); color(3); printf("/n\n"); } } } /*********************Scores and tips on the right side of the game *****************/ void scoreandtips() { int i; File_out();//Call File_out() to read the contents of the file gotoxy(74,4); color(11); printf(" Highest record :%d",HighScore);//Print the highest score of the game gotoxy(74,8); color(14); printf("Score: %d ",score); color(13); gotoxy(83,11); printf("Tips"); gotoxy(70,13); color(6); printf(" "); for (i=15;i<25;i=i+2) { gotoxy(70,i); printf(" "); } for (i=15;i<25;i=i+2) { gotoxy(103,i); printf(" "); } gotoxy(70,25); printf(" "); color(3); gotoxy(74,14); printf("Each thing score: %d points", add); gotoxy(74,16); printf("Can't go through the wall, can't bite yourself"); gotoxy(74,18); printf("Use to control the movement of the snake separately"); gotoxy(74,20); printf("F1 accelerates, F2 decelerates"); gotoxy(74,22); printf("space:Pause the game"); gotoxy(74,24); printf("ESC:Exit the game"); } /***************Read the highest score in the file*******************/ void File_out() { FALSE *fp; fp=fopen("save.txt","a+");//Open the file save.txt fscanf(fp,"%d",&HighScore); fclose(fp); } /*****************Main function****************************/ int main() { system("mode con cols=120 lines=40");//Set the width and height of the console printsnake();//Draw character snake welcome();//Welcome interface File_out(); return 0; } Copy code

You must learn to call and save files in C language before they can be used flexibly here.

Draw snake body and snake food

/******************* Draw the body of the snake************************/ void initsnake() { snake *tail; int i; tail=(snake*)malloc(sizeof(snake));//From the tail of the snake, the head is inserted, and the starting position is set by X, Y tail->x=24;//The initial position of the snake (24, 5) tail->y=5; tail->next=NULL; for (i=1;i<=4;i++)//The initial length is 5 { head=(snake*)malloc(sizeof(snake));//initialize the snake head head->next=tail;//The next digit of the snake head is the snake tail head->x=24+2*i;//Set the position of the snake head head->y=5; tail=head;//Snake head becomes snake tail, and then repeat the cycle } while (tail!=NULL)//From beginning to end, output the snake body { gotoxy(tail->x,tail->y); color(14); printf(" ");//output snake body tail=tail->next;//Snake head output is completed, output the next bit of the snake head, and output to the snake tail } } /*************Drawing food******************************/ void createfood() { snake *food_1; srand((unsigned)time(NULL));//Initialize random number food_1=(snake*)malloc(sizeof(snake));//initialize food_1 //Ensure it is an even number so that the food can be aligned with the snake head, and then the food will appear on the grid line while ((food_1->x%2)!=0) { food_1->x=rand()%52+2;//Set the X coordinate of the food to appear randomly, and the X coordinate of the food is 2-53 } food_1->y=rand()%24+1;//The Y coordinate of the food is 1-24 q=head; while (q->next==NULL) { if (q->x==food_1->x&&q->y==food_1->y)//Determine whether the snake body overlaps the food { free(food_1);//If the food coincides with the snake body, then release the food pointer createfood ();//recreate food } q=q->next; } gotoxy(food_1->x,food_1->y);//Set food location food=food_1; color(12); printf(" ");//Output food } Copy code

At this point, the game interface of Snake is almost ready, and the rest is the logic needed for the game;

Game logic

/**********************************Game logic************* *********************/ /*********************Judging whether to bite yourself*****************/ int biteself() { snake *self;//Define self as a node on the snake self=head->next;//self is the node on the snake body other than the snake head while(self!=NULL) { if (self->x==head->x&&self->y==head->y)//If self and the node on the snake head coincide { return 1;//return 1 } self=self->next;//Every node on the loop snake } return 0; } /************ Determine if the snake hits the wall ********************/ void cantcrosswall() { if (head->x==0||head->x==56||head->y==0||head->y==26)//If the snake head hits the wall { endgamestatus=1;//return to the first situation } } /*******************Set the snake to accelerate forward**********/ void speedup() { if (sleeptime>=50)//If the time interval is greater than or equal to 50 { sleeptime=sleeptime-10;//time interval minus 10 add=add+2;//Add 2 to the score for each food eaten if(sleeptime==320) { add=2;//Prevent errors in adding back after subtracting to 1 } } } /*******************Set the snake to slow down and move forward************/ void speeddown() { if (sleeptime<350)//If the time interval is less than 350 { sleeptime=sleeptime+30;//time interval plus 30 add=add-2;//The score for not eating food is reduced by 2 if (sleeptime==350) { add=1;//Guaranteed a minimum score of 1 } } } /******************control direction*************************/ void snakemove() { snake *nexthead; cantcrosswall(); nexthead=(snake*)malloc(sizeof(snake));//Open up space for the next step if (status==W) { nexthead->x=head->x;//When going up, the x coordinate is unchanged, and the y coordinate is -1 nexthead->y=head->y-1; nexthead->next=head; q=head;//The pointer q points to the snake head //If the next one has food, the coordinates of the next position are the same as the coordinates of the food if (nexthead->x==food->x&&nexthead->y==food->y) { while (q!=NULL) { gotoxy(q->x,q->y); color(14); printf(" ");//The original position of the food, changed from to q=q->next;//The next bit of the snake body pointed to by the pointer q also performs the operation in the loop } score=score+add;//Eat a food, add the food score to the total score speedup(); createfood();//Create food } else { while (q->next->next!=NULL) { gotoxy(q->x,q->y); color(14); printf(" ");//The snake walks forward normally, outputting the snake body at the current position q=q->next;//Continue to output the entire snake body } //After the above cycle, q points to the tail of the snake, and the next bit of the tail is the position where the snake walked. gotoxy(q->next->x,q->next->y); color(3); printf(" "); free(q->next);//After output , release the pointer to the next bit q->next=NULL;//The next bit of the pointer points to null } } /// if (status==S) { nexthead->x=head->x;//When going up, the x coordinate is unchanged, and the y coordinate is +1 nexthead->y=head->y+1; nexthead->next=head; q=head;//The pointer q points to the snake head //If the next one has food, the coordinates of the next position are the same as the coordinates of the food if (nexthead->x==food->x&&nexthead->y==food->y) { while (q!=NULL) { gotoxy(q->x,q->y); color(14); printf(" ");//The original position of the food, changed from to q=q->next;//The next bit of the snake body pointed to by the pointer q also performs the operation in the loop } score=score+add;//Eat a food, add the food score to the total score speedup(); createfood();//Create food } else { while (q->next->next!=NULL) { gotoxy(q->x,q->y); color(14); printf(" ");//The snake walks forward normally, outputting the snake body at the current position q=q->next;//Continue to output the entire snake body } //After the above cycle, q points to the tail of the snake, and the next bit of the tail is the position where the snake walked. gotoxy(q->next->x,q->next->y); color(3); printf(" "); free(q->next);//After output , release the pointer to the next bit q->next=NULL;//The next bit of the pointer points to null } } / if (status==A) { nexthead->x=head->x-2;//When moving to the left, the x coordinate moves to the left by -2, and the y coordinate does not change nexthead->y=head->y; nexthead->next=head; q=head;//The pointer q points to the snake head //If the next one has food, the coordinates of the next position are the same as the coordinates of the food if (nexthead->x==food->x&&nexthead->y==food->y) { while (q!=NULL) { gotoxy(q->x,q->y); color(14); printf(" ");//The original position of the food, changed from to q=q->next;//The next bit of the snake body pointed to by the pointer q also performs the operation in the loop } score=score+add;//Eat a food, add the food score to the total score speedup(); createfood();//Create food } else { while (q->next->next!=NULL) { gotoxy(q->x,q->y); color(14); printf(" ");//The snake walks forward normally, outputting the snake body at the current position q=q->next;//Continue to output the entire snake body } //After the above cycle, q points to the tail of the snake, and the next bit of the tail is the position where the snake walked. gotoxy(q->next->x,q->next->y); color(3); printf(" "); free(q->next);//After output , release the pointer to the next bit q->next=NULL;//The next bit of the pointer points to null } } / if (status==D) { nexthead->x=head->x+2;//When moving to the right, the x coordinate moves to the left +2, and the y coordinate does not change nexthead->y=head->y; nexthead->next=head; q=head;//The pointer q points to the snake head //If the next one has food, the coordinates of the next position are the same as the coordinates of the food if (nexthead->x==food->x&&nexthead->y==food->y) { while (q!=NULL) { gotoxy(q->x,q->y); color(14); printf(" ");//The original position of the food, changed from to q=q->next;//The next bit of the snake body pointed to by the pointer q also performs the operation in the loop } score=score+add;//Eat a food, add the food score to the total score speedup(); createfood();//Create food } else { while (q->next->next!=NULL) { gotoxy(q->x,q->y); color(14); printf(" ");//The snake walks forward normally, outputting the snake body at the current position q=q->next;//Continue to output the entire snake body } //After the above cycle, q points to the tail of the snake, and the next bit of the tail is the position where the snake walked. gotoxy(q->next->x,q->next->y); color(3); printf(" "); free(q->next);//After output , release the pointer to the next bit q->next=NULL;//The next bit of the pointer points to null } } if (biteself()==1)//Judge whether you will bite yourself { endgamestatus=2; } } /******************************* Keyboard***************** *******************/ void key() { status=R;//The initial snake moves to the right while (1) { scoreandtips();//Score and small reminders on the right side of the game interface //GetAsyncKeyState function is used to determine the state of the specified virtual key when the function is called if (GetAsyncKeyState(VK_UP)&&status!=S) { status=W;//If the snake is not moving downwards, press the up key to perform the upward forwarding operation } else if (GetAsyncKeyState(VK_DOWN)&&status!=W) { status=S;//If the snake is not moving upwards, press the down key to perform downward forwarding operations } else if (GetAsyncKeyState(VK_LEFT)&&status!=D) { status=A;//If the snake is not advancing to the right, press the left key to perform the operation of advancing to the left } else if (GetAsyncKeyState(VK_RIGHT)&&status!=A) { status=D;//If the snake is not advancing to the left, press the right button to perform the operation of advancing to the right } if (GetAsyncKeyState(VK_SPACE))//Press the pause button to execute the pause function { while (1) { //Sleep() function, header file #include <unistd.h> The other process is suspended until the time for setting parameters is reached Sleep(300); if (GetAsyncKeyState(VK_SPACE))//Press the space bar to pause { break; } } } else if (GetAsyncKeyState(VK_ESCAPE)) { endgamestatus=3;//Press ESC to go directly to the end interface break; } else if (GetAsyncKeyState(VK_F1))//Press F1 to accelerate { speedup(); } else if (GetAsyncKeyState(VK_F2))//Press F2 to slow down { if (sleeptime<350)//If the time interval is less than 350 { sleeptime=sleeptime+30;//time interval plus 30 add=add-2;//The score for not eating food is reduced by 2 if (sleeptime==350) { add=1;//Guaranteed a minimum score of 1 } } } Sleep(sleeptime);//When no key is pressed, the snake keeps moving forward snakemove(); } } /*****************Main function****************************/ int main() { system("mode con cols=120 lines=40");//Set the width and height of the console printsnake();//Draw character snake welcome();//Welcome interface File_out(); key(); return 0; } Copy code

Game failure interface

/************************Failure interface*********************/ void Lostdraw() { int k; system("cls"); gotoxy(50,2); printf(" Game Results"); gotoxy(17,5); color(11); printf(" "); printf(" "); for (k=7;k<=18;k++)//Vertical border { gotoxy(17,k); printf(" "); gotoxy(82,k); printf(" "); } gotoxy(17,20); printf(" "); printf(" "); } /****************************End Game*****************/ void endgame() { system("cls"); if (endgamestatus==1)//If the snake hits the wall { Lostdraw(); gotoxy(35,9); color(12); printf("Sorry, your head won't break the wall. The game is over"); } else if (endgamestatus==2)//If the snake bites itself { Lostdraw(); gotoxy(35,9); color(12); printf("Sorry, you bit yourself, the game is over!"); } else if (endgamestatus==3)//If you press the ESC key to exit { Lostdraw(); gotoxy(40,9); color(12); printf("You have finished the game!"); } gotoxy(43,12); color(13); printf("Your score is %d",score); if (score>=HighScore) { color(10); gotoxy(40,16); printf("Awesome, a record!"); File_in();//Write the highest score into the file } else//If lower than the highest score { color(10); gotoxy(35,16); printf("Keep working hard, you are still far from the highest score: %d",HighScore-score); } choose();//Branch options below the border } /********************Branch options below the border************/ void choose() { int m; gotoxy(25,23); color(12); printf("I want to play again -------- 1"); gotoxy(52,23); printf("Stop playing, exit -------- 2"); gotoxy(46,25); color(11); printf("Select: "); scanf("%d",&m); switch(m) { case 1: system("cls");//Clear the screen score=0;//return the score to zero sleeptime=200;//Set the initial speed add=10;//Set add to the initial value, eat a food for ten, and then accumulate printsnake();//Return to the welcome interface welcome(); break; case 2: exit(0);//Exit the game break; default://Enter a number other than 1 or 2 gotoxy(35,27); color(12); printf("Don't enter blindly, please enter again"); system("pause>nul");//Press any key endgame(); choose();//Branch statement below the border break; } } /*****************Main function****************************/ int main() { system("mode con cols=120 lines=40");//Set the width and height of the console printsnake();//Draw character snake welcome();//Welcome interface File_out();//Read file information keyjianpan();//Control keyboard keys endgame();//Game over return 0; } Copy code

Note: At this time, remember to add endgame() to the different failure functions of the previous snake;

game instructions

/*********************game instructions************************/ void explation() { int i,j=1; system("cls"); color(13); gotoxy(52,3); printf("Game Description"); color(2); for (i=6;i<=22;i++)//Output the upper and lower borders { for (j=20;j<=75;j++) { gotoxy(j+10,i); if (i==6||i==22) { printf("||"); } } } color(3); gotoxy(40,8); printf("One: can't go through the wall, can't bite yourself"); color(10); gotoxy(40,11); printf("Two: Use to control the movement of the snake separately"); color(14); gotoxy(40,14); printf("Three: F1 accelerates, F2 decelerates"); color(11); gotoxy(40,17); printf("Four: Pause with the space bar, then press the space bar to continue"); color(4); gotoxy(40,20); printf("Five: ESC: exit the game, space: pause the game"); getch();//Press any key to return to the main interface system("cls"); printsnake(); welcome(); } Copy code

At this point, a fun snake game is ready, you can try it yourself, it is helpful to understand the related applications of C language

You can pay attention before leaving. . . . . .

If you don t want to spend time learning on your own, you can directly ask me for the complete code