很多C语言初学者都疑惑学习C语言能干什么,今天就给大家展示一段用C语言编写的一款简单小游戏-贪吃蛇
![5e6e11891d464ff4d500c8b3ec334d68.png](https://img-blog.csdnimg.cn/img_convert/5e6e11891d464ff4d500c8b3ec334d68.png)
游戏开始界面
![f052b919e3bb39279fe0a178398f0e86.png](https://img-blog.csdnimg.cn/img_convert/f052b919e3bb39279fe0a178398f0e86.png)
游戏中界面
![3052fe0afc9265d483f0cb67299ce84d.png](https://img-blog.csdnimg.cn/img_convert/3052fe0afc9265d483f0cb67299ce84d.png)
游戏失败后界面
#include
#include
#include
#include
#include
/// 游戏活动区域
#define GAME_W 20
#define GAME_H 14
/// 方向
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
#define gotoxyInGameAndPrint(x, y, color, ch) gotoxyAndPrint(x + 1, y + 1, color, ch)
/// 蛇结点
typedef struct
{
int x;
int y;
}Node;
/// 游戏相关数据
typedef struct
{
int map [GAME_H][GAME_W]; // 二维数组,用于碰撞检测
Node snake [GAME_H * GAME_W]; // 蛇身
double speed; // 速度
int length; // 蛇身长度
int director; // 蛇头当前方向
Node food; // 食物(坐标)
bool pause; // 游戏暂停
bool dead; // 是否死亡
}Data;
/// 句柄
HANDLE g_hConsoleHandl;
Data gameData;
//-------------------------------------------------------------------
//
// 函数声明
//
//-------------------------------------------------------------------
void gotoxyAndPrint (int x, int y, unsigned color, char* ch); // 设置光标位置并打印
void onEnter (); // 游戏开始前的处理
void gameMenu (); // 游戏菜单
void lostGame (); // 游戏失败
void drawGameBorder (int w, int h); // 绘制游戏边界
void printPrompting (); // 显示提示信息
void printGameData (Data* data); // 显示游戏数据
void initGame (Data* data); // 初始化游戏数据
void runGame (Data* data); // 运行游戏
void keyDownControl (Data* data, char key); // 键盘按键控制
Node getNewPos (Data* data);
void move (Data* data); // 移动蛇
void updateMap (Data* data); // 更新 map
void repaint (Data* data); // 刷新画面
void createFood (Data* data); // 生成食物
bool isEatDood (Data* data); // 判断前方是否有食物可吃
void eatFood (Data* data); // 吃食物
bool isDead (Data* data); // 是否死亡(结束游戏)
//-------------------------------------------------------------------
//
// 主函数 main()
//
//-------------------------------------------------------------------
int main ()
{
onEnter ();
while ( TRUE ) {
gameMenu ();
initGame (&gameData);
runGame (&gameData);
lostGame ();
}
system ("pause");
return 0;
}
//
// 游戏开始前的处理
//
void onEnter ()
{
g_hConsoleHandl = GetStdHandle (STD_OUTPUT_HANDLE); // 获取标准输出句柄
CONSOLE_CURSOR_INFO cursorInfo = { 1, FALSE }; // 光标信息
SetConsoleCursorInfo (g_hConsoleHandl, &cursorInfo); // 隐藏光标
system ("title GameSnake"); // 设置控制台窗口标题
}
//
// 设置光标位置
//
void gotoxyAndPrint (int x, int y, unsigned color, char* ch)
{
COORD pos;
pos.X = x << 1;
pos.Y = y;
// 移动到目标
SetConsoleTextAttribute (g_hConsoleHandl, color);
// 设置颜色
SetConsoleCursorPosition (g_hConsoleHandl, pos);
printf ("%s