贪吃蛇游戏是一款经典的小型游戏,玩家需要控制一条蛇在屏幕上移动,通过吃掉食物使其变长,同时要避免蛇头撞到墙或自己的身体。本文将介绍如何使用C语言和Windows API来实现贪吃蛇游戏。
首先,我们需要定义一些基本的数据结构和函数。蛇由一系列节点组成,每个节点包含坐标和指向下一个节点的指针。蛇的状态包括游戏状态和移动方向。地图由墙和食物组成,我们需要创建地图并初始化蛇和食物。
接下来,我们需要实现游戏运行逻辑。在每一帧中,根据蛇的移动方向移动蛇,判断蛇头是否吃到食物,如果是则增长蛇身并得分。同时,我们需要检测是否撞到墙或自己的身体,如果是则游戏结束。
为了提高游戏的可玩性,我们可以添加一些功能,比如加速和减速。我们可以通过按下F3和F4键来控制蛇的移动速度。另外,我们还可以在屏幕上显示帮助信息,让玩家了解如何操作游戏。
最后,我们需要实现游戏结束后的资源释放。我们需要清除屏幕上的地图和蛇,释放动态分配的内存。
通过以上步骤,我们可以实现一个简单的贪吃蛇游戏。玩家可以使用键盘上的箭头键来控制蛇的移动,通过吃掉食物使其变长,同时要避免撞到墙或自己的身体。游戏会根据玩家的得分来提高难度,增加游戏趣味性。
#pragma once
#include<locale.h>
#include<stdlib.h>
#include<stdio.h>
#include<windows.h>
#include<stdbool.h>
#define WALL L'□'//墙体
#define BODY L'●'//蛇身体
#define FOOD L'★'//食物
#define POS_X 24//蛇初始坐标
#define POS_Y 5
#define KEY_PRESS(VK) ( (GetAsyncKeyState(VK) & 0x1) ? 1 : 0 )
//蛇走的方向
enum DIRECTION
{
UP=1,
DOWN,
LEFT,
RIGHT
};
//蛇的状态
enum GAME_STATE
{
OK = 1,
ESC,
KILL_BY_WALL,
KILL_BY_SELF
};
//蛇身节点
typedef struct SnakeNode
{
int x;
int y;
struct SnakeNode* next;
}SnakeNode, * pSnakeNode;
//贪吃蛇
typedef struct Snake
{
pSnakeNode pSnake;//蛇的长度
pSnakeNode pFood;//食物
int Score; //当前累计的分数
int FoodWeight; //一个食物的分值
int SleepTime; //蛇的速度
enum GAME_STATE state;//蛇的状态
enum DIRECTION dir;//蛇的方向
}Snake,* pSnake;
void SetPos(int x, int y);//设置光标位置
void GameStart(pSnake ps);//游戏初始化
void WelcomeToGame();//打印欢迎信息
void CreateMap();//创建地图
void InitSnake(pSnake ps);//初始化蛇
void CreateFood(pSnake ps);//创建食物
void GameRun(pSnake ps);//游戏运行逻辑
void PrintHelpInfo();//打印帮助信息
void SnakeMove(pSnake ps);//蛇移动一步
int NextIsFood(pSnake ps,pSnakeNode pNext);//判断蛇头的下一步是否是食物
void EatFood(pSnake ps, pSnakeNode pNext);//下一个位置是食物吃掉
void NotEatFood(pSnake ps, pSnakeNode pNext);//下一个位置不是食物,正常走
void KillByWall(pSnake ps);//检测撞墙
void KillBySelf(pSnake ps);//撞到自己
void GameEnd(pSnake ps);//游戏结束资源释放
#define _CRT_SECURE_NO_WARNINGS 1
#include"snake.h"
//设置光标位置
void SetPos(int x,int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos = { x,y };
SetConsoleCursorPosition(handle, pos);
}
void WelcomeToGame()
{
SetPos(40, 15);
printf("欢迎来到贪吃蛇");
SetPos(40, 20);
system("pause");
system("cls");
//功能介绍
SetPos(15, 10);
printf("用 ↑ . ↓ . ← . → 来控制蛇的移动,F3是加速,F4是减速");
SetPos(15, 11);
printf("加速能得到更高的分数");
SetPos(38, 20);
system("pause");
system("cls");
}
void CreateMap()
{
//上
SetPos(0, 0);
for (int i = 0; i <= 56; i += 2)
{
wprintf(L"%c", WALL);
}
//下
SetPos(0, 26);
for (int i = 0; i <= 56; i += 2)
{
wprintf(L"%c", WALL);
}
//左
for (int i = 1; i <= 25; i ++)
{
SetPos(0, i);
wprintf(L"%c", WALL);
}
//右
for (int i = 1; i <= 25; i++)
{
SetPos(56, i);
wprintf(L"%c", WALL);
}
}
void InitSnake(pSnake ps)
{
//创建五个蛇神节点
pSnakeNode cur = NULL;
for (int i = 0; i < 5; i++)
{
cur = (pSnakeNode)malloc(sizeof(SnakeNode));
if (cur == NULL)
{
perror("InitSnake:malloc");
return;
}
cur->x = POS_X + 2 * i;
cur->y = POS_Y;
cur->next = NULL;
//头插法
if (ps->pSnake == NULL)
{
ps->pSnake = cur;
}
else
{
cur->next = ps->pSnake;
ps->pSnake = cur;
}
}
//打印蛇的身体
cur = ps->pSnake;
while (cur)
{
SetPos(cur->x, cur->y);
wprintf(L"%lc", BODY);
cur = cur->next;
}
//贪吃蛇其他信息初始化
ps->dir = RIGHT;
ps->FoodWeight = 10;
ps->pFood = NULL;
ps->Score = 0;
ps->SleepTime = 200;
ps->state = OK;
}
void CreateFood(pSnake ps)
{
int x = 0;
int y = 0;
again:
do
{
x = rand() % 53 + 2;
y = rand() % 24 + 1;
} while (x % 2 != 0);
//判断食物是否在蛇身上
pSnakeNode cur = ps->pSnake;
while (cur)
{
if (x == cur->x && y == cur->y)
{
goto again;
}
cur = cur->next;
}
//创建食物
pSnakeNode pFood = (pSnakeNode)malloc(sizeof(SnakeNode));
if (pFood == NULL)
{
perror("CreateFood():malloc()");
return;
}
pFood->x = x;
pFood->y = y;
ps->pFood = pFood;
SetPos(x, y);
wprintf(L"%c", FOOD);
}
void GameStart(pSnake ps)
{
//设置控制台
system("mode con cols=100 lines=30");
system("title 贪吃蛇@安");
//隐藏光标
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorinfo;
GetConsoleCursorInfo(handle, &cursorinfo);
cursorinfo.bVisible = false;
SetConsoleCursorInfo(handle, &cursorinfo);
//打印欢迎信息
WelcomeToGame();
//绘制地图
CreateMap();
//初始化蛇
InitSnake(ps);
//创建食物
CreateFood(ps);
}
void PrintHelpInfo()
{
SetPos(60, 15);
printf("1.不能撞墙 不能撞自己");
SetPos(60, 16);
printf("2.用上下左右控制蛇的方向");
SetPos(60, 17);
printf("3.f3加速 f4减速");
SetPos(60, 19);
printf("版权@an");
}
void Pause()//游戏暂停
{
while (1)
{
Sleep(200);
if (KEY_PRESS(VK_SPACE))
{
break;
}
}
}
int NextIsFood(pSnake ps, pSnakeNode pNext)
{
if (ps->pFood->x == pNext->x && ps->pFood->y == pNext->y)
return 1;
else
return 0;
}
void EatFood(pSnake ps, pSnakeNode pNext)
{
pNext->next = ps->pSnake;
ps->pSnake = pNext;
pSnakeNode cur = ps->pSnake;
while (cur)
{
SetPos(cur->x, cur->y);
wprintf(L"%c", BODY);
cur = cur->next;
}
ps->Score += ps->FoodWeight;
//释放掉旧食物
free(ps->pFood);
//创建新食物;
CreateFood(ps);
}
void NotEatFood(pSnake ps, pSnakeNode pNext)
{
pNext->next = ps->pSnake;
ps->pSnake = pNext;
pSnakeNode cur = ps->pSnake;
while (cur->next->next)
{
SetPos(cur->x, cur->y);
wprintf(L"%c", BODY);
cur = cur->next;
}
SetPos(cur->next->x, cur->next->y);
printf(" ");
free(cur->next);
cur->next = NULL;
}
void KillByWall(pSnake ps)
{
if (ps->pSnake->x == 0 ||
ps->pSnake->x == 56 ||
ps->pSnake->y == 0 ||
ps->pSnake->y == 26)
{
ps->state = KILL_BY_WALL;
}
}
void KillBySelf(pSnake ps)
{
pSnakeNode cur = ps->pSnake->next;
while (cur)
{
if (cur->x == ps->pSnake->x && cur->y == ps->pSnake->y)
{
ps->state = KILL_BY_SELF;
return;
}
cur = cur->next;
}
}
void SnakeMove(pSnake ps)
{
pSnakeNode pNext = (pSnakeNode)malloc(sizeof(SnakeNode));
if (pNext == NULL)
{
perror("SnakeMove():malloc:");
return;
}
pNext->next = NULL;
switch (ps->dir)
{
case UP:
pNext->x = ps->pSnake->x;
pNext->y = ps->pSnake -> y - 1;
break;
case DOWN:
pNext->x = ps->pSnake->x;
pNext->y = ps->pSnake -> y + 1;
break;
case LEFT:
pNext->x = ps->pSnake->x - 2;
pNext->y = ps->pSnake->y;
break;
case RIGHT:
pNext->x = ps->pSnake->x + 2;
pNext->y = ps->pSnake->y;
break;
}
//下一个坐标处是否是食物
if (NextIsFood(ps, pNext))
{
//是食物就吃掉
EatFood(ps, pNext);
}
else
{
//不是,正常走
NotEatFood(ps, pNext);
}
//检测撞墙
KillByWall(ps);
//是否撞到自己
KillBySelf(ps);
}
void GameRun(pSnake ps)
{
//打印帮助信息
PrintHelpInfo();
do
{
//当前的分数情况
SetPos(60, 10);
printf("总分:%5d", ps->Score);
SetPos(60, 11);
printf("食物的分值:%02d", ps->FoodWeight);
//检测按键
if (KEY_PRESS(VK_UP) && ps->dir != DOWN)
{
ps->dir = UP;
}
else if (KEY_PRESS(VK_DOWN) && ps->dir != UP)
{
ps->dir = DOWN;
}
else if (KEY_PRESS(VK_LEFT) && ps->dir != RIGHT)
{
ps->dir = LEFT;
}
else if (KEY_PRESS(VK_RIGHT) && ps->dir != LEFT)
{
ps->dir = RIGHT;
}
else if (KEY_PRESS(VK_ESCAPE))
{
ps->state = ESC;
break;
}
else if (KEY_PRESS(VK_SPACE))
{
//暂停和恢复游戏
Pause();
}
else if (KEY_PRESS(VK_F3))
{
if (ps->SleepTime >= 80 )
{
ps->SleepTime -= 30;
ps->FoodWeight += 2;
}
}
else if (KEY_PRESS(VK_F4))
{
if (ps->FoodWeight > 2)
{
ps->SleepTime += 30;
ps->FoodWeight -= 2;
}
}
//走一步
SnakeMove(ps);
//休眠一下
Sleep(ps->SleepTime);
} while (ps->state == OK);
}
void GameEnd(pSnake ps)
{
SetPos(15, 12);
switch (ps->state)
{
case ESC:
printf("主动退出游戏\n");
break;
case KILL_BY_WALL:
printf("很遗憾,撞墙了,游戏结束\n");
break;
case KILL_BY_SELF:
printf("很遗憾,撞到自己,游戏结束\n");
break;
}
//释放
pSnakeNode cur = ps->pSnake;
pSnakeNode del = NULL;
while (cur)
{
del = cur;
cur = cur->next;
free(del);
}
free(ps->pFood);
ps = NULL;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include"snake.h"
void test()
{
int ch = 0;
do
{
Snake snake = { 0 };
GameStart(&snake);
GameRun(&snake);
GameEnd(&snake);//善后工作
SetPos(20, 15);
printf("再来一局?(y/n)");
ch = getchar();
getchar();
} while (ch == 'Y' || ch == 'y');
}
int main()
{
//适配本地中文环境
setlocale(LC_ALL, "");
//贪吃蛇游戏的设置
test();
return 0;
}