Do not go gentle into that good night.
Rage, rage against the dying of the light.
目录
1.🍊游戏框架
首先,我们来梳理一下贪吃蛇游戏的基本功能和游戏流程,将任务一点点细化~(非常推荐用思维导图的方式进行梳理,很清晰!)
如下图:
2.🍉分段代码详解
2.1😆GameStart
void GameStart(Snake* ps) {
system("mode con cols=100 lines=30");
system("title 贪吃蛇");
HANDLE houtput = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO CursorInfo;
GetConsoleCursorInfo(houtput, &CursorInfo);
CursorInfo.bVisible = false;
SetConsoleCursorInfo(houtput, &CursorInfo);
Welcome();
CreateMap();
InitSnake(ps);
CreateFood(ps);
}
2.1.1🤗welcome
实现两个欢迎界面的编写
void Welcome() {
Setpos(40, 15);
printf("欢迎来到贪吃蛇游戏!");
Setpos(40, 25);
system("pause");
system("cls");
Setpos(25, 12);
printf("请用 ↑ . ↓ . ← . →分别控制蛇蛇的移动,按F3加速,按F4减速。");
Setpos(25, 13);
printf("加速可获得更高的分数。\n");
Setpos(40, 25);
system("pause");
system("cls");
}
2.1.2🗺️createmap
绘制出围墙
void CreateMap() {
int i = 0;
//打印围墙上侧
Setpos(0, 0);
for (i = 0; i < 58; i += 2) {
wprintf(L"%lc", WALL);
}
//打印围墙下侧
Setpos(0, 26);
for (i = 0; i < 58; i += 2) {
wprintf(L"%lc", WALL);
}
//打印左边围墙
for (i = 1; i < 26; i++) {
Setpos(0, i);
wprintf(L"%lc", WALL);
}
//打印右边围墙
for (i = 1; i < 26; i++) {
Setpos(56, i);
wprintf(L"%lc", WALL);
}
}
2.1.3🐍InitSnake
void InitSnake(Snake* ps) {
SnakeNode* pcur = NULL;
for (int i = 0; i < 5; i++) {
pcur = (SnakeNode*)malloc(sizeof(SnakeNode));
if (pcur == NULL) {
perror("InitSnake:malloc fail!");
return;
}
pcur->next = NULL;
pcur->x = POS_X + i * 2;
pcur->y = POS_Y;
//头插
if (ps->snake == NULL) {
ps->snake = pcur;
}
else {
pcur->next = ps->snake;
ps->snake = pcur;
}
}
//打印蛇身体
pcur = ps->snake;
while (pcur) {
Setpos(pcur->x, pcur->y);
wprintf(L"%lc", BODY);
pcur = pcur->next;
}
ps->dir=RIGHT;
ps->status=OK;
ps->foodweight=10;
ps->score=0;
ps->sleeptime=200;
}
2.1.4 🥘createfood
void CreateFood(Snake* ps ){
//确定食物位置
int x = 0;
int y = 0;
again:
do {
x = rand() % 53 + 2;
y = rand() % 23 + 2;
} while (x % 2 != 0);
SnakeNode* pcur = ps->snake;
while (pcur) {
if (pcur->x == x && pcur->y == y) {
goto again;
}
pcur = pcur->next;
}
//开辟食物空间
SnakeNode* pfood = (SnakeNode*)malloc(sizeof(SnakeNode));
if (pfood == NULL) {
perror("Creatfood:malloc fail!");
return;
}
else {
pfood->x = x;
pfood->y = y;
Setpos(pfood->x, pfood->y);
wprintf(L"%c", FOOD);
ps->food = pfood;
}
}
2.2🙂GameRun
2.2.1❓PrintHelpInfo
void PrintHelpInfo()
{
//打印提⽰信息
Setpos(64, 15);
printf("不能穿墙,不能撞到自己\n");
Setpos(64, 16);
printf("用↑.↓.←.→分别控制蛇的移动.");
Setpos(64, 17);
printf("F3为加速,F4为减速\n");
Setpos(64, 18);
printf("ESC :退出游戏.space:暂停游戏.");
Setpos(64, 20);
}