基于easyx的贪吃蛇游戏C++程序
时间: 2024-01-02 20:21:31 浏览: 120
初学者单人easyx库和vc++6.0贪吃蛇小游戏
5星 · 资源好评率100%
以下是基于easyx的贪吃蛇游戏C++程序:
```c++
#include <graphics.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
#define WIDTH 800
#define HEIGHT 600
#define SIZE 20
struct Snake
{
int x, y;
struct Snake *next;
};
Snake *head, *tail;
int food_x, food_y;
int score = 0;
int direction = VK_RIGHT;
void init();
void draw();
void update_snake();
void update_direction();
void update_food();
bool is_game_over();
int main()
{
init();
while (true)
{
draw();
update_snake();
update_direction();
update_food();
if (is_game_over())
{
break;
}
Sleep(100);
}
closegraph();
return 0;
}
void init()
{
initgraph(WIDTH, HEIGHT);
setbkcolor(WHITE);
setfillcolor(BLACK);
head = new Snake{WIDTH / 2, HEIGHT / 2, NULL};
tail = head;
food_x = rand() % (WIDTH / SIZE) * SIZE;
food_y = rand() % (HEIGHT / SIZE) * SIZE;
}
void draw()
{
cleardevice();
fillrectangle(food_x, food_y, food_x + SIZE, food_y + SIZE);
Snake *p = head;
while (p != NULL)
{
fillrectangle(p->x, p->y, p->x + SIZE, p->y + SIZE);
p = p->next;
}
char str[10];
sprintf(str, "Score: %d", score);
outtextxy(10, 10, str);
}
void update_snake()
{
int x = head->x, y = head->y;
switch (direction)
{
case VK_LEFT:
x -= SIZE;
break;
case VK_RIGHT:
x += SIZE;
break;
case VK_UP:
y -= SIZE;
break;
case VK_DOWN:
y += SIZE;
break;
}
Snake *p = new Snake{x, y, NULL};
head->next = p;
head = p;
if (x == food_x && y == food_y)
{
score++;
}
else
{
Snake *q = tail;
tail = tail->next;
delete q;
}
}
void update_direction()
{
if (_kbhit())
{
int key = _getch();
if (key == VK_LEFT || key == VK_RIGHT || key == VK_UP || key == VK_DOWN)
{
if (abs(key - direction) != 2)
{
direction = key;
}
}
}
}
void update_food()
{
if (food_x == head->x && food_y == head->y)
{
food_x = rand() % (WIDTH / SIZE) * SIZE;
food_y = rand() % (HEIGHT / SIZE) * SIZE;
}
}
bool is_game_over()
{
if (head->x < 0 || head->x >= WIDTH || head->y < 0 || head->y >= HEIGHT)
{
return true;
}
Snake *p = tail;
while (p != head)
{
if (p->x == head->x && p->y == head->y)
{
return true;
}
p = p->next;
}
return false;
}
--相关问题--:
阅读全文