增加开始界面包括开始游戏、游戏说明、退出游戏 #include <graphics.h> #include <stdio.h> #include <time.h> #include <conio.h> #pragma comment(lib,"winmm.lib") //最简单的贪吃蛇 #define NUM 100 //蛇的最大长度 //枚举4个方向 72 80 75 77 ↑↓←→ enum Ch{up=72,down=80,left=75,right=77}; //坐标 struct Coor { int x; int y; }; //蛇的结构体 struct Snake { int n; //蛇当前的节数 Ch ch; //方向 Coor szb[NUM]; //蛇每一节的坐标 }snake; //snake //食物 struct Food { int x; int y; bool isEat; }food; //游戏的初始化函数 void InitGame() { srand((unsigned int)time(NULL)); mciSendString(L"open 甩葱歌.mp3 alias BGM", 0, 0, 0); mciSendString(L"play BGM", 0, 0, 0); //先得到一条蛇 1节 right 320 240 snake.n = 4; snake.ch = right; snake.szb[0].x = 320; snake.szb[0].y = 240; sna
时间: 2024-03-31 10:33:27 浏览: 83
ke.szb[1].x = 300; snake.szb[1].y = 240; snake.szb[2].x = 280; snake.szb[2].y = 240; snake.szb[3].x = 260; snake.szb[3].y = 240; //初始化食物 food.isEat = true; //随机生成一个食物 food.x = rand() % 640; food.y = rand() % 480; } //绘制游戏界面 void DrawGame() { cleardevice(); //绘制蛇 for (int i = 0; i < snake.n; i++) { setfillcolor(RED); solidcircle(snake.szb[i].x, snake.szb[i].y, 10); } //绘制食物 setfillcolor(GREEN); solidcircle(food.x, food.y, 10); } //更新蛇的位置 void UpdateSnake() { //移动蛇 for (int i = snake.n - 1; i > 0; i--) { snake.szb[i].x = snake.szb[i - 1].x; snake.szb[i].y = snake.szb[i - 1].y; } //根据方向更新蛇头 switch (snake.ch) { case up: snake.szb[0].y -= 20; break; case down: snake.szb[0].y += 20; break; case left: snake.szb[0].x -= 20; break; case right: snake.szb[0].x += 20; break; default: break; } //判断是否吃到食物 if (snake.szb[0].x == food.x && snake.szb[0].y == food.y) { snake.n++; food.isEat = true; food.x = rand() % 640; food.y = rand() % 480; } } //判断游戏是否结束 bool IsGameOver() { //判断是否撞墙 if (snake.szb[0].x < 0 || snake.szb[0].x > 640 || snake.szb[0].y < 0 || snake.szb[0].y > 480) { return true; } //判断是否撞到自己 for (int i = 1; i < snake.n; i++) { if (snake.szb[0].x == snake.szb[i].x && snake.szb[0].y == snake.szb[i].y) { return true; } } return false; } //游戏结束 void GameOver() { //关闭音乐 mciSendString(L"close BGM", 0, 0, 0); //输出得分 printf("Game Over! You got %d score!\n", snake.n - 4); } //主函数 int main() { //初始化窗口 initgraph(640, 480); //初始化游戏 InitGame(); //游戏循环 while (1) { //绘制游戏界面 DrawGame(); //更新蛇的位置 UpdateSnake(); //判断游戏是否结束 if (IsGameOver()) { GameOver(); break; } //延时一段时间 Sleep(200); //判断是否需要重新生成食物 if (food.isEat) { food.isEat = false; } } //关闭窗口 closegraph(); return 0; }
阅读全文