方法很简单,打开页面,复制,粘贴
一.整体思维架构

我们根据游戏的开始,运行,结束,将整个游戏划分成三个部分。在每个部分下面又划分出多个功能,接下来我们就根据模块一一实现功能。
二.Gamestart
2.1设置窗口大小与窗口名字
由于游戏需要用到控制台窗口,所以我们需要使用一些win32API的相关知识。
首先我们需要调整窗口大小,这里用到了一个mode con的指令,以及给title进行命名,通过调用system来实现

在使用system之前要加上头文件

2.2隐藏屏幕光标
2.2.1 GetStdHandle
GetStdHandle是Windows ApI函数,他用于从一个特定的标准设备(标准输入,标准输出,标准错误)中取得一个句柄,用这个句柄可以操作设备。

我们通过一个houput指针来接收一份标准输出光标。
2.2.2 GetConsoleCursorInfo
GetConsoleCursorInfo是用来检索有关指定控制台屏幕缓冲区的光标大小和可见性信息。他的参数为一个bool类型。使用时,需要一份handle指针,以及一个相关结构体(包含控制台光标信息)。

2.2.3 CONSOLE_CURSOR_INFO
这是一个结构体,能够获取有关控制台光标的信息。包括dwSize光标填充的字符单元格的百分比,bVisinle游标的可见性。

这里我们将其置为false,就可以隐藏光标。
2.2.4 SetConsoleCursorInfo
设置指定控制台屏幕缓冲区的光标大小和可见性。

我们将指针与检索信息传给其,就能完成光标设置。
2.3 欢迎界面WelcomeToGame
在此之前我们需要制作一个坐标设置的函数。
COORD是Windows API中定义的一个结构体,表示一个字符在控制台屏幕上的坐标。
由此我们可以制作一个定位函数

输入x,y的坐标,将光标定位到该处。
我们根据这个函数,以及屏幕的大小,适当调整位置打印相关信息。

这里我们运用到了pause 和cls,使每打印完一次信息就清理屏幕打印下一句信息。
2.4创建地图CreatMap
首先我们定义一下墙体

为一个□,这个字符号可以在输入法内找到。接着我们开始输入墙体,从0.0开始,在控制台内输入要用到wprintf,输入则需要在类型前加上L。由于控制台的x坐标与y坐标大小不一样的原因,x坐标相较于y坐标的每个单位要小,所以我们的循环中,x坐标处我们每两个一打印。

2.5创建蛇身InitSnake
2.5.1蛇身结点创建
这里我们用到一个结构体,蛇身需要xy坐标,以及下一个蛇身结点的地址。

2.5.2蛇的维护结构
一条蛇内要包含蛇头的指针,维护蛇食物的指针,蛇的初始方向,蛇的状态,得分情况,蛇的大小,每走一步需要休眠的时间。

我们用一个枚举结构体储存蛇的相关状态以及方向控制。


2.5.3初始化蛇身
传递一个蛇身结点,初始化为cur。我们先初始化蛇身为5个结点,通过for循环一次malloc出一块空间,结点依次链接。将结点赋给_psnake。

之后我们需要将蛇身打印出来,并且初始化数据。

2.6创建食物CreateFood
首先我们要保证食物要在地图内部,其次食物不能与蛇身重复。
我们将食物坐标设置为⭐

我们可以用x=rand%53+2,y=rand%25+1使得坐标在地图内部,while循环x%2!=0使x坐标恒为2的倍数。

完成上述判断后给食物进行初始化

2.7总结Gamestart

三. GameRun
3.1右侧打印有效信息PrintHelpInfo

3.2 KEY_PRESS
这是一个宏,用于检测按键状态,若按键被按下则首位为1,否则则为0

3.3主要设计思路
首先我们在右侧打印出游戏相应提示,用KEY_PRESS判断按键,来判断蛇的移动方向以及加速减速,游戏暂停等等。我们用一个do while循环来操作蛇的每一步,每走一步休眠一定时间,直到游戏结束为止。


我们通过控制sleep和weight来实现加速和减速效果。
3.4 蛇的移动SnakeMove
蛇的移动首先要满足不能和原先方向相反移动。蛇头向前走,蛇尾销毁结点。以及蛇的状态,是吃食物,撞墙,自杀。
3.4.1上下左右移动
通过判断按键是否按下,用Switch来进行循环判断,注意x坐标每次移动2个单位。

3.4.2判断是否有食物
若下一个结点有食物,就将食物与蛇结点相连接,随后打印出整条蛇,改变相应的分数,最后销毁的食物空间,创建一个新的食物。

若不是食物,则创建一个新结点放在蛇头出,并与蛇连接,销毁最后一个蛇结点。

3.4.3撞墙或自杀

3.5总结GameRun


四. GameEnd
4.1主要思路
告知死亡原因,并且释放所有结点。
4.2代码实现

五.完整代码
5.1 test.c

5.2 Snake.c











5.3 Snake.h


