写一个有图片的贪吃蛇c++
时间: 2024-01-06 18:04:52 浏览: 34
以下是一个简单的贪吃蛇 C++ 程序,其中使用了图形库 `graphics.h` 来实现图形化界面:
```cpp
#include <graphics.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
const int WIDTH = 800; // 窗口宽度
const int HEIGHT = 600; // 窗口高度
const int BLOCK_SIZE = 20; // 方块大小
const int MAX_LENGTH = 100; // 蛇的最大长度
// 蛇的节点
struct SnakeNode {
int x, y;
};
// 游戏状态
enum GameState {
PLAYING,
GAMEOVER
};
int main() {
initwindow(WIDTH, HEIGHT, "贪吃蛇"); // 初始化窗口
// 随机数种子
srand(time(NULL));
// 初始化蛇
SnakeNode snake[MAX_LENGTH];
int length = 3;
for (int i = 0; i < length; i++) {
snake[i].x = (WIDTH / BLOCK_SIZE / 2 + i) * BLOCK_SIZE;
snake[i].y = (HEIGHT / BLOCK_SIZE / 2) * BLOCK_SIZE;
}
// 初始化食物
int food_x = rand() % (WIDTH / BLOCK_SIZE) * BLOCK_SIZE;
int food_y = rand() % (HEIGHT / BLOCK_SIZE) * BLOCK_SIZE;
// 初始方向向右
int dx = BLOCK_SIZE;
int dy = 0;
// 游戏状态
GameState state = PLAYING;
while (state == PLAYING) {
cleardevice(); // 清屏
// 绘制蛇
for (int i = 0; i < length; i++) {
setfillstyle(SOLID_FILL, GREEN);
bar(snake[i].x, snake[i].y, snake[i].x + BLOCK_SIZE, snake[i].y + BLOCK_SIZE);
}
// 绘制食物
setfillstyle(SOLID_FILL, RED);
bar(food_x, food_y, food_x + BLOCK_SIZE, food_y + BLOCK_SIZE);
// 移动蛇
for (int i = length - 1; i > 0; i--) {
snake[i].x = snake[i - 1].x;
snake[i].y = snake[i - 1].y;
}
snake[0].x += dx;
snake[0].y += dy;
// 检测是否吃到食物
if (snake[0].x == food_x && snake[0].y == food_y) {
length++;
food_x = rand() % (WIDTH / BLOCK_SIZE) * BLOCK_SIZE;
food_y = rand() % (HEIGHT / BLOCK_SIZE) * BLOCK_SIZE;
}
// 检测是否撞墙或撞自己
if (snake[0].x < 0 || snake[0].x >= WIDTH || snake[0].y < 0 || snake[0].y >= HEIGHT) {
state = GAMEOVER;
}
for (int i = 1; i < length; i++) {
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
state = GAMEOVER;
}
}
// 按键检测
if (kbhit()) {
char c = getch();
switch (c) {
case 'w':
dx = 0;
dy = -BLOCK_SIZE;
break;
case 's':
dx = 0;
dy = BLOCK_SIZE;
break;
case 'a':
dx = -BLOCK_SIZE;
dy = 0;
break;
case 'd':
dx = BLOCK_SIZE;
dy = 0;
break;
}
}
delay(100); // 延时
}
// 游戏结束,显示提示信息
settextstyle(50, 0, _T("Arial"));
setbkcolor(BLACK);
settextcolor(WHITE);
outtextxy(WIDTH / 2 - 150, HEIGHT / 2 - 25, _T("Game Over"));
getch(); // 等待用户按键
closegraph(); // 关闭窗口
return 0;
}
```
注意,需要在编译器中添加图形库 `graphics.h` 的支持,大多数 IDE 都不自带该库,需要手动下载并配置。