“This is the third day of my participation in the Gwen Challenge.

This time to share a snake I wrote a small game program (C language)

Recently summer vacation without matter began to use C language to write some small games small game procedures, the snake is of course the classic in the classic, so I began to write.

File reference

H >// Input output #include<time.h>// used to get random numbers #include<windows.h>// Control DOS interface #include<stdlib.h>// defines some macros and general-purpose utility functions #include<conio.h> // receive keyboard input outputCopy the code

Function declaration

/ * * * * * * * * * * * * * * * * * * * * * * * * * * function declarations * * * * * * * * * * * * * * * * * * * * * * * * * * * / void gotoxy (int x, int y); // set cursor position int color(int c); // Change the text color void printsnake(); Void welcome(); // Start void createMap(); // Draw a map void scoreandTips (); Void initSnake (); // Initialize snake body void createFood (); // Create and randomly appear food int biteself(); Void cantCrosswall (); Void speedup(); // speed up void speeddown(); // Decelerate void snakemove(); Void keyjianpan(); Void Lostdraw(); Void endGame (); // Void choose(); // Void File_out(); Void File_in(); // Save explation(); // Game instructionsCopy the code

Game welcome screen

/ * * * * * * * * * * * * * * * * * * * * welcome screen game * * * * * * * * * * * * * * * * * * * * * * * / int color (int) c / / color function { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),c); Return 0; } void gotoxy(int x,int y) {COORD c; c.X=x; c.Y=y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c); } void printsnake() { int i,j=10; Gotoxy (37, 21); color(14); Printf (" Zhang Yang snake \n Welcome!" ); Gotoxy (19-1, 9); color(12); Printf (" even "); Gotoxy (23-1, 9); color(12); Printf (" even "); Gotoxy (27-1, 9); color(12); Printf (" even "); Gotoxy (27-1, 11); color(12); Printf (" even "); Gotoxy (19-1, 13); color(12); Printf (" even "); Gotoxy (23-1, 13); color(12); Printf (" even "); Gotoxy (27-1, 13); color(12); Printf (" even "); for(i=20; i<28; i++) { gotoxy(i+10,j); color(j-10); Printf (" even "); j++; } for(i=30; i<38; i++) { gotoxy(i+10,j); color(j-10); Printf (" even "); j--; } for(i=40; i<48; i++) { gotoxy(i+10,j); color(j-10); Printf (" even "); j++; } for(i=50; i<58; i++) { gotoxy(i+10,j); color(j-10); Printf (" even "); j--; } for(i=60; i<68; i++) { gotoxy(i+10,j); color(j-10); Printf (" even "); j++; } for(i=70; i<77; i++) { gotoxy(i+10,j); color(j-10); Printf (" even "); j--; } gotoxy (87, 11); color(11); Printf (" even "); Gotoxy (91, 11); color(11); Printf (" even "); Gotoxy (95, 11); color(11); Printf (" even "); Gotoxy (99, 11); color(11); Printf (" even "); } / * * * * * * * * * * * * * * * * * * * * * * * * * the main function * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / int main () {system (" mode con cols = 140 lines=40"); // Set the width and height of the console printsnake(); // Draw the character snake return 0; }Copy the code

The welcome screen

/********** Each person can design different welcome interface according to his/her 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 p); Printf ("3. Exit the game "); Aiaa gotoxy (48); color(3); Printf (" please select [1 2 3]:[]\b\b"); color(14); scanf("%d",&n); switch(n) { case 1 : system("cls"); / / clear screen break; case 2: break; case 3: exit(0); break; default: color(12); Gotoxy (40, 42); Printf (" Please enter numbers between 1 and 3!" ); getch(); // Enter any key system(" CLS "); / / screen clearing printsnake (); welcome(); } } int main() { system("mode con cols=140 lines=40"); // Set the width and height of the console printsnake(); // Draw the character snake welcome(); return 0; }Copy the code

Together, the two form the main interface at the beginning

Game main form design

/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * game main form design * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / void createMap () {int I, j; / / to create a map 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 (" s \ n \ n "); }}} / * * * * * * * * * * * * * * * * * * * * * game scores and tips on the right side of the * * * * * * * * * * * * * * * * * * / void scoreandtips () {int I; File_out(); // call File_out() to read the contents of the file gotoxy(74,4); color(11); Printf (" Friend :%d",HighScore) (" friend ▅ highest record ▃ Friend :%d",HighScore); // print the highest score gotoxy(74,8); color(14); Printf (" score: %d ",score); color(13); Gotoxy (83, 11); Printf (" little token "); 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); Printf (" ┗ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ┛ "); color(3); Gotoxy (74, 14); Printf (" everything score :%d score ",add); Gotoxy (74); Printf (" Do not go through the wall, do not bite yourself "); Gotoxy (74); Printf (" Use ↑↓←→ control the movement of snakes respectively "); Gotoxy (74); Printf ("F1 accelerate, F2 decelerate "); Gotoxy (74, 2); Printf ("space: pause the game "); Gotoxy (74, 24); Printf ("ESC: exit the game "); } / * * * * * * * * * * * * * * * in the file read high * * * * * * * * * * * * * * * * * * * / void File_out () {FALSE * fp; fp=fopen("save.txt","a+"); // open save.txt fscanf(fp,"%d",&HighScore); fclose(fp); } / * * * * * * * * * * * * * * * * * the main function of * * * * * * * * * * * * * * * * * * * * * * * * * * * * / int main () {system (" mode con cols = = 120 lines 40 "); // Set the width and height of the console printsnake(); // Draw the character snake welcome(); // Welcome interface File_out(); return 0; }Copy the code

In C language file call, save must learn well, in order to use here flexibly.

Draw snake body and snake food

/ * * * * * * * * * * * * * * * * * * * draw snakes body * * * * * * * * * * * * * * * * * * * * * * * * / void initsnake () {snake * tail; int i; tail=(snake*)malloc(sizeof(snake)); Tail -> X =24; tail-> X =24; // tail->y=5; tail->next=NULL; for (i=1; i<=4; I++) // initial length is 5 {head=(snake*)malloc(sizeof(snake)); Head ->next=tail; // head->x=24+2* I; // set head->y=5; tail=head; } while (tail! Gotoxy (tail->x,tail->y); color(14); Printf (" radius "); Tail =tail->next; / / the snake output, output the next head of the snake, has been exported to a serpent}} / * * * * * * * * * * * * * draw food * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / void createfood () {snake * food_1; srand((unsigned)time(NULL)); // Initialize the random number food_1=(snake*)malloc(sizeof(snake)); // Initialize food_1 // make sure it is even so that the food is aligned with the snake's head, then the food appears on the grid while ((food_1->x%2)! =0) { food_1->x=rand()%52+2; } food_1->y=rand()%24+1; food_1->y=rand()%24+1; Q =head; While (q - > next = = NULL) {if (q - > x = = food_1 - > - > y = x && q = food_1 - > y) / / whether the snake body with food {free (food_1); // Release the food pointer createFood () if the food overlapses with the snake; } q=q->next; } gotoxy(food_1->x,food_1->y); // Set food location food=food_1; color(12); Printf (" ▼ "); // Output food}Copy the code

At this point the snake game interface has been roughly done, the rest of the game needs logic, etc.;

The game logic

 /**********************************游戏逻辑**********************************/
    
    /*********************判断是否咬到自己*****************/
    int biteself()
    {
    	snake *self;								//定义self为蛇身上的一个节点
    	self=head->next;							//self是蛇头之外的蛇身上的节点
    	while(self!=NULL)
    	{
    		if (self->x==head->x&&self->y==head->y)   //如果self和蛇头上的节点重合
    		{
    			return 1;    						  //返回1
    		}
    		self=self->next;    					 //循环蛇上的每一个节点
    	}
    	return 0;
    }
    /************判断蛇是否撞到墙******************/
    void cantcrosswall()
    {
    	if (head->x==0||head->x==56||head->y==0||head->y==26)//如果蛇头碰到了墙壁
    	{
    		endgamestatus=1;    					  //返回第一种情况
    	}
    }
    /*******************设置蛇加速前进**********/
    void speedup()
    {
    	if (sleeptime>=50)  						 //如果时间间隔大于等于50
    	{
    		sleeptime=sleeptime-10;  				 //时间间隔减10
		     add=add+2;                               //每吃一次食物的得分加2
    		if(sleeptime==320)
    		{
    			add=2;                                //防止减到1之后再加回来有错
    		}
    	}
    }
    /*******************设置蛇减速前进************/
    void speeddown()
    {
    	if (sleeptime<350)              		 	//如果时间间隔小于350
    	{
    		sleeptime=sleeptime+30;     		 	 //时间间隔加上30
    		add=add-2;                				 //没吃一次食物的得分减2
    		if (sleeptime==350)
    		{
    			add=1;               				  //保证最低分为1
    		}
    	}
    }
    /******************控制方向*************************/
void  snakemove()
{
	snake *nexthead;
	cantcrosswall();
	nexthead=(snake*)malloc(sizeof(snake));  //为下一步开辟空间
	if (status==W)
	{
		nexthead->x=head->x;    //向上前进时,x坐标不变,y坐标-1
		nexthead->y=head->y-1;
		nexthead->next=head;
		q=head;                //指针q指向蛇头
		//如果下一个有食物,下一个位置的坐标和食物的坐标相同
		if (nexthead->x==food->x&&nexthead->y==food->y)
		{
			while (q!=NULL)
			{
				gotoxy(q->x,q->y);
				color(14);
				printf("⊕");    //原来食物的位置,从▼变成⊕
				q=q->next;       //指针q指向的蛇身的下一位也执行循环里的操作
			}
			score=score+add;      //吃了一个食物,在总分上加上食物的分
			speedup();
			createfood();         //创建食物
		}
		else
		{
			while (q->next->next!=NULL)
			{
				gotoxy(q->x,q->y);
				color(14);
				printf("⊕");    //蛇正常往前走,输出当前位置的蛇身
				q=q->next;       //继续输出整个蛇身
				
			}
			//经过上面的循环,q指向蛇尾,蛇尾的下一位,就是蛇走过去的位置
			gotoxy(q->next->x,q->next->y);
			color(3);
			printf("■");
			free(q->next);     //进行输出▼之后,释放指向下一位的指针
			q->next=NULL;     //指针下一位指向空
		}
	}
	///
	if (status==S)                 
	{
		nexthead->x=head->x;    //向上前进时,x坐标不变,y坐标+1
		nexthead->y=head->y+1;
		nexthead->next=head;
		q=head;                //指针q指向蛇头
		//如果下一个有食物,下一个位置的坐标和食物的坐标相同
		if (nexthead->x==food->x&&nexthead->y==food->y)
		{
			while (q!=NULL)
			{
				gotoxy(q->x,q->y);
				color(14);
				printf("⊕");    //原来食物的位置,从▼变成⊕
				q=q->next;       //指针q指向的蛇身的下一位也执行循环里的操作
			}
			score=score+add;      //吃了一个食物,在总分上加上食物的分
			speedup();
			createfood();         //创建食物
		}
		else
		{
			while (q->next->next!=NULL)
			{
				gotoxy(q->x,q->y);
				color(14);
				printf("⊕");    //蛇正常往前走,输出当前位置的蛇身
				q=q->next;       //继续输出整个蛇身
				
			}
			//经过上面的循环,q指向蛇尾,蛇尾的下一位,就是蛇走过去的位置
			gotoxy(q->next->x,q->next->y);
			color(3);
			printf("■");
			free(q->next);     //进行输出▼之后,释放指向下一位的指针
			q->next=NULL;     //指针下一位指向空
		}
	}
	/
	if (status==A)
	{
		nexthead->x=head->x-2;    //向左前进时,x坐标向左移动-2,y坐标不变
		nexthead->y=head->y;
		nexthead->next=head;
		q=head;                //指针q指向蛇头
		//如果下一个有食物,下一个位置的坐标和食物的坐标相同
		if (nexthead->x==food->x&&nexthead->y==food->y)
		{
			while (q!=NULL)
			{
				gotoxy(q->x,q->y);
				color(14);
				printf("⊕");    //原来食物的位置,从▼变成⊕
				q=q->next;       //指针q指向的蛇身的下一位也执行循环里的操作
			}
			score=score+add;      //吃了一个食物,在总分上加上食物的分
			speedup();
			createfood();         //创建食物
		}
		else
		{
			while (q->next->next!=NULL)
			{
				gotoxy(q->x,q->y);
				color(14);
				printf("⊕");    //蛇正常往前走,输出当前位置的蛇身
				q=q->next;       //继续输出整个蛇身
				
			}
			//经过上面的循环,q指向蛇尾,蛇尾的下一位,就是蛇走过去的位置
			gotoxy(q->next->x,q->next->y);
			color(3);
			printf("■");
			free(q->next);     //进行输出▼之后,释放指向下一位的指针
			q->next=NULL;     //指针下一位指向空
		}
	}
	/
	if (status==D)
	{
		nexthead->x=head->x+2;    //向右前进时,x坐标向左移动+2,y坐标不变
		nexthead->y=head->y;
		nexthead->next=head;
		q=head;                //指针q指向蛇头
		//如果下一个有食物,下一个位置的坐标和食物的坐标相同
		if (nexthead->x==food->x&&nexthead->y==food->y)
		{
			while (q!=NULL)
			{
				gotoxy(q->x,q->y);
				color(14);
				printf("⊕");    //原来食物的位置,从▼变成⊕
				q=q->next;       //指针q指向的蛇身的下一位也执行循环里的操作
			}
			score=score+add;      //吃了一个食物,在总分上加上食物的分
			speedup();
			createfood();         //创建食物
		}
		else
		{
			while (q->next->next!=NULL)
			{
				gotoxy(q->x,q->y);
				color(14);
				printf("⊕");    //蛇正常往前走,输出当前位置的蛇身
				q=q->next;       //继续输出整个蛇身
				
			}
			//经过上面的循环,q指向蛇尾,蛇尾的下一位,就是蛇走过去的位置
			gotoxy(q->next->x,q->next->y);
			color(3);
			printf("■");
			free(q->next);     //进行输出▼之后,释放指向下一位的指针
			q->next=NULL;     //指针下一位指向空
		}
	}
	if (biteself()==1)			//判断是否会咬到自己
	{
		endgamestatus=2;
	}
}
/******************************* 键盘 ************************************/
void key()
{
	status=R;					//初始蛇向右移动 
	while (1)
	{
		scoreandtips();           //游戏界面右侧的得分和小提醒
//GetAsyncKeyState函数 用来判断函数调用时指定虚拟键的状态
		if (GetAsyncKeyState(VK_UP)&&status!=S)
		{
			status=W;      //如果蛇不是向下前进的时候,按向上键,执行向上前进操作
		}
		else if (GetAsyncKeyState(VK_DOWN)&&status!=W)
		{
			status=S;      //如果蛇不是向上前进的时候,按向下键,执行向下前进操作
		}
		else if (GetAsyncKeyState(VK_LEFT)&&status!=D)
		{
			status=A;      //如果蛇不是向右前进的时候,按向左键,执行向左前进操作
		}
		else if (GetAsyncKeyState(VK_RIGHT)&&status!=A)
		{
			status=D;      //如果蛇不是向左前进的时候,按向右键,执行向右前进操作
		}
		if (GetAsyncKeyState(VK_SPACE))     //按下暂停键,执行pause暂停函数
		{
			while (1)
			{
	//Sleep()函数,头文件#include <unistd.h>另进程暂停,直到达到里面设定参数的时间
				Sleep(300);
				if (GetAsyncKeyState(VK_SPACE))  //按下空格键暂停
				{
					break;
				}
			}
		}
		else if (GetAsyncKeyState(VK_ESCAPE))
		{
			endgamestatus=3;   //按ESC,直接到结束界面
			break;
		}
		else if (GetAsyncKeyState(VK_F1))   //按F1,加速
		{
			speedup();
		}
		else if (GetAsyncKeyState(VK_F2))   //按F2,减速
		{
			if (sleeptime<350)            //如果时间间隔小于350
			{
				sleeptime=sleeptime+30;  //时间间隔加上30
				add=add-2;                //没吃一次食物的得分减2
				if (sleeptime==350)
				{
					add=1;                //保证最低分为1
				}
			}
		}
		Sleep(sleeptime);                 //不按键时,蛇保持前行
		snakemove();
	}
}
/*****************主函数****************************/
int main()
{
	system("mode con cols=120 lines=40");	//设置控制台的宽高
	printsnake();							//绘制字符蛇
	welcome();								//欢迎界面
	File_out();
	key();
	return 0;
}
Copy the code

Game failure interface

/ * * * * * * * * * * * * * * * * * * * * * * * * failure interface * * * * * * * * * * * * * * * * * * * * * / void Lostdraw () {int k; system("cls"); Gotoxy (50, 2); Printf ("∑ game result "); Gotoxy (17, 5); color(11); Printf (" ┏ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ "); Printf (" ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ┓ "); for (k=7; k<=18; K ++) {gotoxy(17,k); Printf (" ┃ "); gotoxy(82,k); Printf (" ┃ "); } gotoxy (17, 20); Printf (" ┗ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ "); Printf (" ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ━ ┛ "); } / * * * * * * * * * * * * * * * * * * * * * * * * * * * * end of the game * * * * * * * * * * * * * * * * * / void endgame () {system (" CLS "); If (endGamestatus ==1) // If the snake hits the wall {Lostdraw(); Gotoxy (35, 9); color(12); Printf (" Sorry, you can't knock your head off a wall. Game over "); } else if (endgamestatus==2) {Lostdraw(); Gotoxy (35, 9); color(12); Printf (" Sorry, you bit yourself, game over!" ); } else if (endGamestatus ==3) {Lostdraw(); Gotoxy (40, 9); color(12); Printf (" You've finished the game!" ); } gotoxy (43, 12); color(13); Printf (" your score is %d",score); if (score>=HighScore) { color(10); Gotoxy (40 16th); Printf (" Awesome, record! !" ); File_in(); } else {color(10); Gotoxy (35 16th); Printf (" Keep up the good work, you are not close to the highest score: %d", highscore-score); } choose(); / / frame the following branch options} / * * * * * * * * * * * * * * * * * * * * borders the following branch options * * * * * * * * * * * * / void choose () {int m; Gotoxy (25, 23); color(12); Printf (" I'm going to play again -------- 1"); Gotoxy (52, 23); Printf (" quit playing, quit -------- 2"); Gotoxy (46, 25); color(11); Printf (" select: "); scanf("%d",&m); switch(m) { case 1: system("cls"); / / screen clearing score = 0; Sleeptime =200; // Set initial speed add=10; Printsnake (); // Set add to the initial value, 10 for eating a food, and then add printsnake(); // Return to 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 (" Do not type blind, please retype "); system("pause>nul"); // Press any key endgame(); choose(); // Break the branch statement below the border; }} / * * * * * * * * * * * * * * * * * the main function of * * * * * * * * * * * * * * * * * * * * * * * * * * * * / int main () {system (" mode con cols = = 120 lines 40 "); // Set the width and height of the console printsnake(); // Draw the character snake welcome(); // Welcome interface File_out(); Keyjianpan (); // Control keyboard keys endgame(); // Game over return 0; }Copy the code

Note: Also remember to add endgame () to the different failure functions in the previous snake;

Game shows

/ * * * * * * * * * * * * * * * * * * * * * game shows * * * * * * * * * * * * * * * * * * * * * * * * / void explation () {int I, j = 1; system("cls"); color(13); Gotoxy (52, 3); Printf (" game description "); color(2); for (i=6; i<=22; I++) {for (j=20; j<=75; j++) { gotoxy(j+10,i); if (i==6||i==22) { printf("||"); } } } color(3); Gotoxy (40, 8); Printf (" One: do not go through the wall, do not bite yourself "); color(10); Gotoxy (40, 11); Printf (" Ii: Use ↑↓←→ control the movement of snakes respectively "); color(14); Gotoxy (40, 14); Printf (" three: F1 acceleration, F2 deceleration "); color(11); Gotoxy 40 (12); Printf (" four: pause space, press space to continue "); color(4); Gotoxy (40, 20); Printf (" five: ESC: exit game, space: pause game "); getch(); // Press any key to return to the main screen system(" CLS "); printsnake(); welcome(); }Copy the code

At this time a fun snake game is done, you can try it yourself, is conducive to understanding the relevant use of C language

You can keep an eye on it…

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