C language Snake course design experiment report (including Snake project source code)

At the end of the article, there is an overview of Snake’s code, and the code has very detailed comments!!! At the end of the article, there is an overview of Snake’s code, and the code has very detailed
comments!!!
comment!!!

Code text is not easy, give a free little star and a free like, and follow it (⑅•͈ᴗ•͈).:*♡ 

Don't be a whore for nothing (⁍̥̥̥᷄д⁍̥̥̥᷅ ू ) sad

Table of contents

1 Subject analysis 

1.1 Research background and current situation

1.2 Research significance and research steps

2 Design overview

2.1 Specific content of the project

2.2 System Block Diagram

2.2.1 Program Structure Diagram

2.2.2 Game flow chart

2.2.3 View the flow chart of the rule interface

2. System module division

3 Detailed Design Description

3.1 Description of main menu interface design

3.1.1 Design Description

3.1.2 Function display

3.2 View the design description of the rule interface

3.2.1 Design Description

3.2.2 Function display

3.3 Start Game Interface Design Instructions

3.3.1 Design Description

3.3.2 Function display

4 Conclusion


Curriculum Design Task Book

Design title: Snake Fight

Design content and requirements:

design content:

Use C programming language to design the snake game function. The project is mainly divided into three interfaces, namely the menu interface, the rules interface and the main game interface.

Innovation points: Change the single color of the snake body into a rainbow color that changes with the game progress, modify the speed mechanism and score reward mechanism, and add a mouse interactive menu to enhance the game experience.

Design requirements:

Consolidate C language knowledge through game design , write functions in a reasonable standard and call them correctly. Use easyx to add expansive content and understand the methods of the functions used.

When encountering an error in the design, debug and analyze it in time, consult the data, and compare and use the same function in multiple ways to ensure that the code is correct and running normally.

mentor:

year month day

1 Subject analysis 


1.1 Research background and current situation

With the rapid development of the computer industry, many popular programming languages ​​have emerged. As a widely used high-level programming language, C language program development and learning is particularly important. It has the characteristics of strong drawing ability, portability, and powerful data processing ability. , suitable for writing system software, graphics and animation.

Today's games have become a popular way of pastime. Snake is a game that fits the public's psychology and adapts to a wide range of people. It is highly entertaining and interactive, and can enrich people's entertainment time.

As a small game, Snake is simple to operate and easy to use. The game mechanism is highly stimulating, fascinating and addictive. Compared with the long-term consumption of large-scale games, Snake is more reasonable for fragmented entertainment time , can be simple and easy to meet people's needs.

The main purpose of this article is to research and design the game of Snake in C language, use the free drawing library of EasyX Graphics Library to realize the game screen, function design and call, formulate the game rules and operation mechanism, and output the screen on the Windows console host to realize the game operation.

1.2 Research significance and research steps

Significance:

In a fast-paced society, people’s time is more compact, and the time for entertainment and leisure is also very tight. In the case of large-scale games with a wide audience, light games and fast games are more closely related to appetite, allowing users to be more satisfied in fragmented time fast-paced entertainment experience.

Through the Snake mini-game, people can not only entertain in their leisure time, but also record their scores in the game and improve themselves in challenges. line to be successful. At the same time, studying the C language course design and writing the Snake game can exercise thinking and be familiar with the use of code, which is conducive to accumulating experience for future project development and developing in an all-round way.

Research steps:

(1) Design: The most important part of the game is the interface display design, which should consider the size of the game window and text content prompts, so that users can have a good running experience when opening the game, and clarify the role of each function and game operation. The second is to design smooth and good keyboard and mouse operations, so that players can have better interactive feedback.

(2) Game program testing is a key step. Every time a game function is added, it must be tested with an example to ensure that there is no error in the code, the running process of Snake is correct, and the game interface has no bad output. And in the keyboard and mouse interaction to ensure its fluency and stability, to provide users with a good gaming experience.

2 Design overview


2.1 Specific content of the project

The project uses the C programming language and the EasyX Graphics Library to design a snake game program. The project is mainly divided into three interfaces, namely the main menu interface, the rules interface and the game start interface.

Through the main menu interface, we can enter the game start interface, and click the button through mouse interaction to start the game, and the game can be scored in real time. In the view rules interface, you can see the Snake game rule settings, and check the highest score in the game history. If you want to exit the game, you can select the exit button in the main menu to end the program.

2.2 System Block Diagram

2.2.1 Program Structure Diagram

The Snake game program is mainly composed of the main menu interface, the game interface, the rules interface and the exit game interface, as shown in Figure 2-1.

Figure 2-1 Program Structure Diagram

2.2.2 Game flow chart

The main body of the game is composed of several functions, namely the game initialization function, the screen display function, the score reading and writing function, and the interaction function. The following is the flow chart of the game operation, as shown in Figure 2-2:

Figure 2-2 Game flow chart 

2.2.3 View the flow chart of the rule interface

The view rule interface is implemented by reading the highest score, interface text output, and mouse button interaction. Define the structure mouse and judge its behavior. If you do not click the button, you will be in the rule interface without any operations, as shown in Figure 2-3:

Figure 2-3 Rule interface flow chart

2. System module division

In the course project design, the Snake game is mainly divided into three interfaces, namely the menu interface, the rules interface and the main game interface. The modules are divided into main menu module, game initialization, screen display, snake movement module, update related to keyboard input (that is, the keyboard controls the moving direction of the snake), update unrelated to input (moving speed control), reward mechanism, and score module

In the design of the main menu interface, we use the easyx graphics library to design the button options, and color the interface, and judge the button option selected by the user by monitoring the behavior of the left mouse button and the mouse click position, so as to realize the interaction and complete interface jump

When the "Start Game" option is selected, enter the game start function to initialize the game and read the highest score, initialize the snake and the screen, and then enter the loop. When the failure conditions of the game are not met, the interface will always update the drawing. Keep the game going

Among them, the speed mechanism and reward mechanism of the Snake game have been improved respectively. The speed can satisfy the need to press and hold the arrow keys to accelerate forward at the same time, and the more food you eat, the faster the speed; the score reward mechanism meets a certain threshold limit. When the food eaten reaches a certain level, the score will increase in multiples, increasing the bonus points.

In the game failure settlement interface, we have added a score display to see the user's score in this game more intuitively. In the score module, the txt file will be read and written. If the player's score is greater than the highest score, the score of this game will be Cover the highest score.

3 Detailed Design Description


3.1 Description of main menu interface design

3.1.1 Design Description

The main menu interface uses the drawing function of the graphics library to draw a button rectangle, and output a prompt text on the button to let the player understand its function, and monitor the mouse message through the while function at all times. When the left mouse button is clicked, then the if judgment is performed. statement, when it matches the click position of one of the buttons, it will enter the function in the if statement to realize the jump function

3.1.2 Function display

The main menu interface is shown in Figure 3-1.

Figure 3-1 Main menu interface

3.2 View the design description of the rule interface

3.2.1 Design Description

View rule interface function: In the view rule interface, players can understand the rules and key operations involved in the game. At the same time, the highest score is displayed on this interface, so that the player has a game goal. After understanding the relevant rules, the player can click the button to return From the main menu, select Start Game or Exit Game. 

Specific implementation: The realized interface display is consistent with the main menu. To read the highest score, use the written score reading and writing function to read and display the score in the txt file on the interface.

3.2.2 Function display

The interface for viewing rules is shown in Figure 3-2.

Figure 3-2 View rule interface

3.3 Start Game Interface Design Instructions

3.3.1 Design Description

Start the game interface function: realize the main body of the game, draw snakes, food and game interface, keyboard operation greedy snake moves to eat food, the interface displays the highest score, and records the score in real time as the process progresses, and when the game ends, the settlement screen pops up typeface

Specific implementation: Determine the interface by setting the size of the canvas, and draw horizontal and vertical lines to divide the canvas into small squares, calculate fixed pixel values, and map each rectangular square to the square array one by one. When the game is initialized, the array is traversed to draw the snake and the food. After that, every time the screen is updated, the array is traversed to refresh the length of the snake and the position of the food.

Real-time record scores define an int variable, increase the corresponding value according to the score mechanism, then convert it into a char type and store it in a character array, and then output it to the screen.

The game settlement interface judges the position of the snake head, changes the value of the global variable, jumps out of the game loop, and outputs the corresponding text.

3.3.2 Function display

The game interface is shown in Figure 3-3 and Figure 3-4.

Figure 3-3 Game interface

 Figure 3-4 Game settlement interface

4 Conclusion


Through a semester of C language course study, my team members and I have a deeper understanding of C language. I didn't know anything from the beginning, and I slowly explored it by myself. I found that what I learned in books is still not enough, and there are still many things that need extracurricular learning. For Snake, I know its realization principle, and learned the simple analysis of program module design and data structure design. And through the source code analysis, the implementation method of each module is described. Part of the graphics functions are infiltrated in the implementation of several modules. Through the writing process of this article, the following knowledge points have been mastered:

1. Initialization and shutdown of the graphics system

2. Use of various drawing functions

3. Definition of structure

5. Function nesting and calling

6. Keyboard operation

In general, programming is still a job that requires patience, especially when there are bugs that cannot be found, I especially need to calm down and study hard. Many times I have no patience to change it. This study has greatly sharpened the patience of our group, and we have gained a lot. In this course design, we have consolidated the knowledge of C language, learned to write functions in a reasonable way and call them correctly, and can use easyx to increase and expand Sexual content, the most important thing is to discover your own shortcomings.

We will make persistent efforts in the future, continue to practice, constantly break through ourselves, and strive to make better works.

appendix:

The Snake program is as follows:

#include <graphics.h>
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <cstdio>

#define	Width 40		//宽40格
#define Height 30		//高30格
#define Size 20			//格子大小:20

int blocks[Width][Height] = {0};		//用以表示所有方格
char moveDir;			//表示运动方向
char oldmove;			//旧的移动方向
int fx, fy;				//food食物坐标
int addspeed = 15;		//控制初始速度
int failure = 0;		//用以判断游戏是否失败,失败赋值为 1
int score = 0;			//记录分数
int max = 0;			//记录最高分
int k = 1;				//奖励机制初始值
char num[20];			//输出分数数组
char best[20];			//最高分数组	

void initGame();
void show();			//图像绘制更新显示函数
void WithInput();		//与输入有关的更新
void WithoutInput();	//与输入无关的更新
void movesnake();		//蛇的移动函数
void readscore();		//读取分数
void writescore();		//写入分数
void ShowWord();		//界面文字
void drawmenu();		//主菜单
void gamestart();		//开始游戏
void seerule();			//查看规则
void back();			//退出游戏

int main() {				
	drawmenu();
	return 0;
}	  

void initGame() {		
	int i;
	initgraph(1000, 600);		//①初始化绘图窗口,格子个数乘格子大小即为长度
	setbkcolor(CYAN);		//设置背景颜色
	BeginBatchDraw();		//easyx中实现批绘图功能的函数,可以消除图像闪烁
	cleardevice();			//使用当前背景色清空绘图设备
	setlinecolor(WHITE);	//划线颜色为白色

	for (i = Size; i < Width * Size+1; i += Size) {		//用for循环绘制多条线
		line(i, 0, i, Height * Size);				//竖线坐标从x1(i,0)-> y1(i,Height * Size)
	}
	for (i = Size; i < Height * Size; i += Size) {
		line(0, i, Width * Size, i);				//横线坐标从x2(0,i) -> y2(Width * Size, i)
	}

	moveDir = oldmove = 'd';			//初始化默认蛇行进方向朝右

	blocks[Width / 2][Height / 2] = 1;				/*正中间画蛇头,蛇为赋值的方格
													0则为空白区域*/
	for (i = 1; i < 4; i++) {
		blocks[Width / 2 - i][Height / 2] = i + 1;	//y坐标不变,更改x坐标,在蛇头后方画蛇身
	}

	srand(time(0));									//srand函数产生一个时间种子,从而达到真正的随机效果
	fx = rand() % (Width - 1) + 1;					//随机数除39取余并+1,则为食物所生成的格子x坐标
	fy = rand() % (Height - 1) + 1;					//随机数除取余并+1,则为食物所生成的格子y坐标
}	   

void show() {			
	cleardevice();
	for (int i = 0; i < Width; i++) {				//遍历所有方格,更新蛇的颜色
		for (int j = 1; j < Height; j++) {
			if (blocks[i][j] != 0) {
				setfillcolor(HSVtoRGB(blocks[i][j] * 10, 0.9, 1));	//HSV转RGB颜色,色调H 0°->360°,此处设置每长一个蛇身,提升10°色调,饱和度0.9,明度1
			}else{
				setfillcolor(CYAN);					//否则更新为正常背景颜色
			}
			fillrectangle(i * Size, j * Size, (i + 1) * Size, (j + 1) * Size);		//填充,(参数为左上角和右下角坐标)
		}
	}
	setfillcolor(LIGHTGREEN);						//食物颜色
	fillrectangle(fx * Size, fy * Size, (fx + 1) * Size, (fy + 1) * Size);

	ShowWord();

	FlushBatchDraw();				/*BeginBatchDraw执行后,任何绘图操作都将暂时不输出到绘图窗口上
								直到执行 FlushBatchDraw 或 EndBatchDraw 才将之前的绘图输出。*/
}

void ShowWord() {
	if (failure) {
		settextcolor(LIGHTRED);						//设置字体颜色
		settextstyle(80, 0, _T("宋体"));				//设置字体样式
		setbkmode(TRANSPARENT);
		outtextxy(240, 220, "游戏失败");
		settextstyle(40, 0, _T("宋体"));
		sprintf(num, "%d", score);						//将int转换为char并存入num中
		outtextxy(260, 360, "分数:");					//显示的字体及坐标
		outtextxy(380, 360, num);
	}
	else {												//②
		settextcolor(BLACK);							//设置分数颜色
		settextstyle(25, 0, _T("隶书"));				//设置字体样式
		setbkmode(TRANSPARENT);							//设置当前设备图案填充和文字输出时的背景模式,THANSPARENT为透明背景
		sprintf(num, "%d", score);						//将int转换为char并存入num中
		outtextxy(860, 40, "分数:");					//显示的字体及坐标
		outtextxy(940, 42, num);
		outtextxy(845, 73, "最高分:");
		sprintf(best, "%d", max);
		outtextxy(940, 75, best);
	}
}
void readscore() {										//③
	FILE* fpread = fopen("score.txt", "r");				//以只读的方式打开文件
	if (fpread == NULL) {
		return;
	}
	fscanf(fpread, "%d", &max);
	fclose(fpread);
}

void writescore() {
	FILE* fpWrite = fopen("score.txt", "w");			//"w"打开并写入文本文件.(若不存在则新建,反之,则从头写,覆盖原内容)
	if (fpWrite == NULL) {
		return ;
	}
	fprintf(fpWrite, "%d", score);
	fclose(fpWrite);				
}

void WithInput() {
	if (_kbhit() && failure == 0) {
		//键盘输入控制蛇的方向
		char input = _getch();

		if (input == 'a' || input == 's' || input == 'd' || input == 'w') {
			moveDir = input;
			//设定规则:当向某一方向行动时,按下反向键不起作用(防止误触导致判断为咬到蛇身游戏失败),强制将按下的反向键变为当前运动方向
			if (moveDir == 'a' && oldmove == 'd') {
				moveDir = 'd';
			}
			else if (moveDir == 's' && oldmove == 'w') {
				moveDir = 'w';
			}
			else if (moveDir == 'd' && oldmove == 'a') {
				moveDir = 'a';
			}
			else if (moveDir == 'w' && oldmove == 's') {
				moveDir = 's';
			}
			else {
				oldmove = input;
			}
			movesnake();
		}
	}
}

void WithoutInput() {
	
	if (failure) {				//先判断是否失败,失败则返回
		return;
	}
	//Sleep(100);				//更新速度控制蛇的移动速度,但使用sleep会产生键盘控制与画面的延迟,所以不使用
	//movesnake();
	static int speed = 1;		//设置一个静态变量speed,利用循环特定次数来触发movesnake函数
	speed++;
	if (speed == addspeed) {	//每15帧移动一次,同时实现长按方向键加快蛇的移动速度
		movesnake();
		speed = 1;
	}
}

void movesnake() {
	int i, j;
	//对蛇进行更新,蛇每个格数值都+1,以便后面预备一个数值为1的新蛇头,当吃到食物时,新蛇头改变颜色加入蛇身中
	for (i = 0; i < Width; i++) {
		for (j = 0; j < Height; j++) {
			if (blocks[i][j] != 0) {
				blocks[i][j]++;
			}
		}
	}

	int oldhx, oldhy, oldtx, oldty;			//旧蛇头和旧蛇尾的坐标
	int tailblock = 0;
	for (i = 0; i < Width; i++) {
		for (j = 0; j < Height; j++) {
			if (tailblock < blocks[i][j]) {
				tailblock = blocks[i][j];	//遍历找出最大值即为蛇尾
				oldtx = i;
				oldty = j;
			}
			if (blocks[i][j]==2) {			//寻找旧蛇头
				oldhx = i;
				oldhy = j;
			}
		}
	}
	//根据蛇的运动方向来赋值新蛇头的xy坐标
	int newhx = oldhx, newhy = oldhy;		//定义新蛇头
	switch (moveDir) {
	case'a':
		newhx -= 1;
		break;
	case's':
		newhy += 1;
		break;
	case'd':
		newhx += 1;
		break;
	case'w':
		newhy -= 1;
		break;
	}
	//判断游戏是否失败
	if (newhx >= Width || newhx < 0 || newhy >= Height || newhy < 0 || blocks[newhx][newhy] != 0) {
		failure = 1;
		return;
	}
	//令蛇头方格值为1
	blocks[newhx][newhy] = 1;
	//对吃到食物以及蛇尾的处理				⑤
	if (newhx == fx && newhy == fy) {		//吃到食物,重新随机数生成新食物坐标
		score = score + k;					//吃到食物分数+k
		if (score % 2 == 0) {				//通过判断吃食物的数量来叠加奖励分
			k = k + 1;
		}

		if (score > max) {					//与最高分判断,条件成立才能覆盖最高分
			writescore();					//写入最高分
		}
											//④
		if (score) {						//“加速”判断,通过判断分数增大的取值,加快蛇的运动速度,score不为0时进入该判断语句
			if (score % 2 == 0) {			//便于测试结果明显,设置每吃2个食物,蛇速度加快1帧
				addspeed--;
			}
		}
		fx = rand() % (Width - 1) + 1;		
		fy = rand() % (Height - 1) + 1;
	}else{									//未吃到食物
		blocks[oldtx][oldty] = 0;
	}


}

void drawmenu() {
	MOUSEMSG m;					//定义结构体鼠标m
	initgraph(600, 600);		//定义画布大小
	setbkcolor(CYAN);			//设置背景颜色
	cleardevice();				//使用当前背景色清空绘图设备,类似system(cls)的刷新
	setfillcolor(WHITE);	//方框颜色

	fillrectangle(140, 50, 460, 170);			//矩形左上角xy坐标和右下角xy坐标
	fillrectangle(120, 220, 480, 350);			//矩形左上角xy坐标和右下角xy坐标
	fillrectangle(100, 400, 500, 540);			//矩形左上角xy坐标和右下角xy坐标

	settextcolor(BLACK);						//设置字体颜色
	settextstyle(50, 0, _T("楷体"));			//设置字体格式
	setbkmode(TRANSPARENT);						//去除文字背景

	outtextxy(200, 85, "开始游戏");				//文字输出位置的xy坐标
	outtextxy(200, 260, "查看规则");
	outtextxy(200, 445, "退出游戏");

	while (1) {
		m = GetMouseMsg();						//获取一个鼠标消息
		if (m.x >= 140 && m.x <= 460 && m.y >= 50 && m.y <= 170) {		//判断鼠标点击的位置
			if (m.uMsg == WM_LBUTTONDOWN) {		//当鼠标按下左键
				gamestart();					//开始游戏
			}
		}
		else if (m.x >= 120 && m.x <= 480 && m.y >= 220 && m.y <= 350) {
			if (m.uMsg == WM_LBUTTONDOWN) {		//当鼠标按下左键
				seerule();					//查看规则
			}
		}
		else if (m.x >= 100 && m.x <= 500 && m.y >= 400 && m.y <= 540) {
			if (m.uMsg == WM_LBUTTONDOWN) {		//当鼠标按下左键
				back();					//关闭菜单退出游戏
			}
		}
	}
}

void gamestart() {
	readscore();		//读取最高分
	initGame();			//游戏初始化
	while (1) {			//循环进行界面实时刷新,直至游戏判定失败
		show();			//界面显示
		WithoutInput();	//先调用与输入无关的更新
		WithInput();	
	}
}

void seerule() {
	MOUSEMSG m;					//定义结构体鼠标m

	readscore();				//读取历史最高分

	initgraph(600, 600);		//定义画布大小
	setbkcolor(CYAN);			//设置背景颜色
	cleardevice();				//使用当前背景色清空绘图设备,类似system(cls)的刷新
	setfillcolor(WHITE);	//方框颜色

	fillrectangle(100, 400, 500, 540);			//矩形左上角xy坐标和右下角xy坐标

	settextcolor(BLACK);						//设置字体颜色
	settextstyle(50, 0, _T("楷体"));			//设置字体格式
	setbkmode(TRANSPARENT);						//去除文字背景
	outtextxy(200, 445, "返回菜单");

	settextcolor(BLACK);						//设置字体颜色
	settextstyle(30, 0, _T("楷体"));			//设置字体格式
	setbkmode(TRANSPARENT);						//去除文字背景
	outtextxy(45, 30, "WASD控制蛇移动,长按方向键可加速移动");
	outtextxy(45, 80, "碰到墙壁游戏失败");
	outtextxy(45, 130, "吃的食物越多,分数奖励越高");
	outtextxy(45, 180, "历史最高分:");
	sprintf(best, "%d", max);
	outtextxy(220, 180, best);



	while (1) {
		m = GetMouseMsg();						//获取一个鼠标消息
		if (m.x >= 100 && m.x <= 500 && m.y >= 400 && m.y <= 540) {
			if (m.uMsg == WM_LBUTTONDOWN) {		//当鼠标按下左键
				drawmenu();					//返回主菜单
			}
		}
	}
}

void back() {
	closegraph();		//关闭画面
	exit(0);			//退出程序
}

Guess you like

Origin blog.csdn.net/neadsc/article/details/131355205