写一个带图像的贪吃蛇C++
时间: 2024-01-08 15:02:08 浏览: 23
以下是一个简单的带图像的贪吃蛇C++代码。它使用了EasyX图形库来实现图像的绘制和显示。你需要先安装EasyX图形库才能运行此代码。
```c++
#include <graphics.h>
#include <conio.h>
#include <time.h>
#define ROWS 30
#define COLS 30
#define BLOCK_SIZE 20
struct Point {
int x, y;
};
enum Direction {
UP, DOWN, LEFT, RIGHT
};
Direction dir = RIGHT;
Point snake[ROWS * COLS];
int snake_length = 3;
Point food;
void init() {
initgraph(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE, SHOWCONSOLE);
setbkcolor(WHITE);
cleardevice();
// 初始化蛇
snake[0].x = 2;
snake[0].y = 0;
snake[1].x = 1;
snake[1].y = 0;
snake[2].x = 0;
snake[2].y = 0;
// 随机生成食物位置
srand((unsigned int)time(NULL));
food.x = rand() % COLS;
food.y = rand() % ROWS;
}
void draw_block(int x, int y, COLORREF color) {
setfillcolor(color);
setlinecolor(BLACK);
fillrectangle(x * BLOCK_SIZE, y * BLOCK_SIZE, (x + 1) * BLOCK_SIZE, (y + 1) * BLOCK_SIZE);
}
void draw_snake() {
for (int i = 0; i < snake_length; i++) {
draw_block(snake[i].x, snake[i].y, i == 0 ? LIGHTBLUE : YELLOW);
}
}
void draw_food() {
draw_block(food.x, food.y, RED);
}
bool is_collide(int x, int y) {
if (x < 0 || x >= COLS || y < 0 || y >= ROWS) {
return true;
}
for (int i = 1; i < snake_length; i++) {
if (snake[i].x == x && snake[i].y == y) {
return true;
}
}
return false;
}
bool move_snake() {
int x = snake[0].x;
int y = snake[0].y;
switch (dir) {
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
if (is_collide(x, y)) {
return false;
}
// 判断是否吃到食物
if (x == food.x && y == food.y) {
snake_length++;
food.x = rand() % COLS;
food.y = rand() % ROWS;
}
// 移动蛇
for (int i = snake_length - 1; i > 0; i--) {
snake[i].x = snake[i - 1].x;
snake[i].y = snake[i - 1].y;
}
snake[0].x = x;
snake[0].y = y;
return true;
}
void change_direction() {
if (_kbhit()) {
int ch = _getch();
switch (ch) {
case 'w':
case 'W':
if (dir != DOWN) {
dir = UP;
}
break;
case 's':
case 'S':
if (dir != UP) {
dir = DOWN;
}
break;
case 'a':
case 'A':
if (dir != RIGHT) {
dir = LEFT;
}
break;
case 'd':
case 'D':
if (dir != LEFT) {
dir = RIGHT;
}
break;
}
}
}
int main() {
init();
while (true) {
cleardevice();
draw_snake();
draw_food();
if (!move_snake()) {
break;
}
change_direction();
Sleep(200);
}
settextstyle(50, 0, _T("Arial"));
settextcolor(BLACK);
outtextxy(150, 200, _T("Game Over"));
_getch();
closegraph();
return 0;
}
```
运行效果如下:
![snake](https://img-blog.csdn.net/20180723225818706?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NlZV9zaG9wcGluZ19zdGF0aWM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/85)