小编给大家分享一下如何使用C语言实现贪吃蛇游戏,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
键位:使用wasd四个键位来控制方向,按q键退出(注意在终用英文输入法实现键控)
规则:蛇每吃一个豆会得10分,同时身体边长、移速加快
当蛇碰到墙壁或咬到自身时游戏结束,同时会输出游戏得分
(1)用结构体定义蛇和豆
typedef struct Snakes { int x; int y; struct Snakes *next; }snake; snake *head,*tail; struct Food { int x; int y; }food;
(2)打印墙壁
void creatgraph() { int i; for (i = 0; i<58; i += 2)//打印上下边框 { gotoprint(i, 0); gotoprint(i, 26); } for (i = 1; i < 26; i++) { gotoprint(0, i); gotoprint(56, i); } head = (snake*)malloc(sizeof(snake)); head->x = 16; head->y = 15; //gotoprint(head->x, head->y); tail = (snake*)malloc(sizeof(snake)); snake *p = (snake*)malloc(sizeof(snake)); snake *q = (snake*)malloc(sizeof(snake)); p->x = 16; p->y = 16; q->x = 16; q->y = 17; head->next = p; p->next = q; q->next = tail; //gotoprint(p->x, p->y); //gotoprint(q->x, q->y); tail->next = NULL; tail->x = 4; tail->y = 2; } void gotoxy(int x, int y) { COORD pos; HANDLE hOutput; pos.X = x; pos.Y = y; hOutput = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hOutput, pos); } void gotoprint(int x, int y) { gotoxy(x, y); printf("■"); } void gotodelete(int x, int y) { gotoxy(x, y); printf(" "); }
(3)生成豆
void creatfood() { srand((int)time(NULL)); lable: food.y = rand() % (25 - 1 + 1) + 1; food.x = rand() % (54 - 2 + 1) + 2; if (food.x % 2 != 0) { food.x = food.x+1; } snake *judge = head; while (1) { if (judge->next == NULL) break; if (food.x == judge->x&&food.y == judge->y) { goto lable; } judge = judge->next; } gotoxy(food.x, food.y); printf("⊙"); }
(4)点击控制函数
int ClickControl() { char c; while (1) { if (Judge()==0) return 0; if (_kbhit()) { click = _getch(); } MovingBody(); Eating(); } return 1; }
(5)移动控制
void MovingBody() { int count = 0; int a = head->x, b = head->y; snake *p = head; while (1) { if (p->next == NULL) break; gotodelete(p->x, p->y); count++; p = p->next; } switch (click) { case up: head->y -= 1; ChangeBody(a,b); break; case down: head->y += 1; ChangeBody(a,b); break; case left: head->x -= 2; ChangeBody(a,b); break; case right: head->x += 2; ChangeBody(a,b); break; case stop: _getch(); break; } p = head; while (1) { if (p->next == NULL) break; gotoprint(p->x, p->y); p = p->next; } p = head; gotoxy(0, 28); if (count <= 10) speed = 150; else if (count > 10 && count <= 20) speed = 100; else if (count > 20 && count <= 40) speed = 50; else speed = 10; Sleep(speed); }
(6)更改蛇身
void ChangeBody(int a,int b) { snake *p = head->next; int mid1, mid2,_mid1,_mid2; mid1 = p->x; mid2 = p->y; while (1) { if (p->next->next == NULL) break; _mid1 = p->next->x; _mid2 = p->next->y; p->next->x = mid1; p->next->y = mid2; mid1 = _mid1; mid2 = _mid2; p = p->next; } p = head->next; { p->x = a; p->y = b; } }
以上是“如何使用C语言实现贪吃蛇游戏”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。