C语言实现贪吃蛇
实现方式
双向链表
移动方式
-
蛇尾 -> 蛇头
-
食物添加到蛇头的下一个
闪屏问题
在基本的工作完成之后,程序的功能也就实现了,但是会存在一个 Bug,就是屏幕会出现闪烁,对于这个问题,使用双缓冲解决。(网上看了一大堆,也没懂,不过应该是下面的意思)
COORD coord = {0, 0};
DWORD count = 0;
char data[3200];
HANDLE G_hOut = GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE G_hBuf = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
// Other code.
SetConsoleActiveScreenBuffer(G_hOut);
// 在 G_hOut 上绘制
// do something...
// 从 G_hOut 上读取,写入到 G_hBuf,显示
ReadConsoleOutputCharacter(G_hOut, data, 3200, coord, &count);
WriteConsoleOutputCharacter(G_hBuf, data, 3200, coord, &count);
SetConsoleActiveScreenBuffer(G_hBuf);
下载
主要代码
/**
* 函数名: moveSnake
* 功能 : 移动蛇
* 参数 :
* @s 蛇
*
* 返回值: 无
*/
void moveSnake(snake *s)
{
snake_body *p, *q;
position *pos;
short x, y;
boolean eatFood = FALSE;
if (s->head->pos->x == G_food->pos->x && s->head->pos->y == G_food->pos->y)
{
G_food = NULL;
eatFood = TRUE;
}
p = createSnakeBody(s->head->pos->x, s->head->pos->y);
p->next = s->head->next;
p->prev = s->head;
s->head->next->prev = s->head->next = p;
G_direction = setDirection(G_nextDirection);
switch (G_direction)
{
case 77:
s->head->pos->x++;
break;
case 75:
s->head->pos->x--;
break;
case 72:
s->head->pos->y--;
break;
case 80:
s->head->pos->y++;
break;
default:
system("cls");
printCharAt("System Error", WALL_WIDTH, WALL_HEIGHT / 2);
system("pause");
system("exit");
}
if (!eatFood)
{
printCharAt(" ", s->tail->pos->x * 2, s->tail->pos->y);
q = s->tail;
s->tail = s->tail->prev;
q = q->prev->next = NULL;
}
}
本文来自博客园,作者:小码哥鸭,转载请注明原文链接:https://www.cnblogs.com/Super-Lee/p/14208709.html