#include<stdio.h>
2 #include<time.h>
3 #include<windows.h>
4 #include<stdlib.h>
5
6 #define U 1
7 #define D 2
8 #define L 3
9 #define R 4 //蛇的状态,U:上 ;D:下;L:左 R:右
10
11 typedef struct SNAKE //蛇身的一个节点
12 {
13 int x;
14 int y;
15 struct SNAKE *next;
16 }snake;
17
18 //全局变量//
19 int score = 0, add = 10;//总得分与每次吃食物得分。
20 int status, sleeptime = 200;//每次运行的时间间隔
21 snake *head, *food;//蛇头指针,食物指针
22 snake *q;//遍历蛇的时候用到的指针
23 int endGamestatus = 0; //游戏结束的情况,1:撞到墙;2:咬到自己;3:主动退出游戏。
24
25 //声明全部函数//
26 void Pos();
27 void creatMap();
28 void initSnake();
29 int biteSelf();
30 void createFood();
31 void cantCrossWall();
32 void snakeMove();
33 void pause();
34 void runGame();
35 void initGame();
36 void endGame();
37 void gameStart();
38
39 void Pos(int x, int y)//设置光标位置
40 {
41 COORD pos;
42 HANDLE hOutput;
43 pos.X = x;
44 pos.Y = y;
45 hOutput = GetStdHandle(STD_OUTPUT_HANDLE);//返回标准的输入、输出或错误的设备的句柄,也就是获得输入、输出/错误的屏幕缓冲区的句柄
46 SetConsoleCursorPosition(hOutput, pos);
47 }
48
49 void creatMap()//创建地图
50 {
51 int i;
52 for (i = 0; i<58; i += 2)//打印上下边框
53 {
54 Pos(i, 0);
55 printf("■");//一个方块占两个位置
56 Pos(i, 26);
57 printf("■");
58 }
59 for (i = 1; i<26; i++)//打印左右边框
60 {
61 Pos(0, i);
62 printf("■");
63 Pos(56, i);
64 printf("■");
65 }
66 }
67
68 void initSnake()//初始化蛇身
69 {
70 snake *tail;
71 int i;
72 tail = (snake*)malloc(sizeof(snake));//从蛇尾开始,头插法,以x,y设定开始的位置//
73 tail->x = 24;
74 tail->y = 5;
75 tail->next = NULL;
76 for (i = 1; i <= 4; i++)//初始长度为4
77 {
78 head = (snake*)malloc(sizeof(snake));
79 head->next = tail;
80 head->x = 24 + 2 * i;
81 head->y = 5;
82 tail = head;
83 }
84 while (tail != NULL)//从头到为,输出蛇身
85 {
86 Pos(tail->x, tail->y);
87 printf("■");
88 tail = tail->next;
89 }
90 }
91 //??
92 int biteSelf()//判断是否咬到了自己
93 {
贪吃蛇游戏代码
最新推荐文章于 2024-04-11 20:53:51 发布