用dev写个贪吃蛇代码、
时间: 2023-09-24 18:06:20 浏览: 48
好的,以下是使用Dev C++编写的贪吃蛇代码:
```c++
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
int width = 30, height = 20;
int snake_x[100], snake_y[100];
int food_x, food_y, score;
int direction, gameover;
void draw() // 绘制游戏界面
{
system("cls"); // 清屏
for (int i = 0; i <= width; i++)
printf("#"); // 顶部边框
printf("\n");
for (int i = 1; i <= height; i++)
{
for (int j = 0; j <= width; j++)
{
if (j == 0 || j == width)
printf("#"); // 左右边框
else if (i == snake_y[0] && j == snake_x[0])
printf("O"); // 蛇头
else if (i == food_y && j == food_x)
printf("*"); // 食物
else
{
int flag = 0;
for (int k = 1; k < score; k++)
{
if (i == snake_y[k] && j == snake_x[k])
{
printf("o"); // 蛇身
flag = 1;
}
}
if (flag == 0) // 空格
printf(" ");
}
}
printf("\n");
}
for (int i = 0; i <= width; i++)
printf("#"); // 底部边框
printf("\n");
printf("Score: %d\n", score);
}
void setup() // 初始化
{
snake_x[0] = width / 2; // 蛇的初始位置
snake_y[0] = height / 2;
food_x = rand() % (width - 2) + 1; // 食物的初始位置
food_y = rand() % (height - 2) + 1;
score = 0; // 得分
gameover = 0; // 游戏是否结束
direction = RIGHT; // 初始方向
}
void input() // 接收方向键
{
if (_kbhit()) // 检测键盘输入
{
switch (_getch())
{
case UP:
if (direction != DOWN)
direction = UP;
break;
case DOWN:
if (direction != UP)
direction = DOWN;
break;
case LEFT:
if (direction != RIGHT)
direction = LEFT;
break;
case RIGHT:
if (direction != LEFT)
direction = RIGHT;
break;
}
}
}
void logic() // 游戏逻辑
{
int prev_x = snake_x[0];
int prev_y = snake_y[0];
int temp_x, temp_y;
snake_x[0] += (direction == RIGHT) ? 1 : (direction == LEFT) ? -1 : 0;
snake_y[0] += (direction == DOWN) ? 1 : (direction == UP) ? -1 : 0;
for (int i = 1; i < score; i++)
{
temp_x = snake_x[i];
temp_y = snake_y[i];
snake_x[i] = prev_x;
snake_y[i] = prev_y;
prev_x = temp_x;
prev_y = temp_y;
}
if (snake_x[0] == 0 || snake_x[0] == width || snake_y[0] == 0 || snake_y[0] == height)
gameover = 1; // 碰到边界,游戏结束
for (int i = 1; i < score; i++)
{
if (snake_x[0] == snake_x[i] && snake_y[0] == snake_y[i])
gameover = 1; // 碰到自身,游戏结束
}
if (snake_x[0] == food_x && snake_y[0] == food_y) // 吃到食物
{
score++;
food_x = rand() % (width - 2) + 1;
food_y = rand() % (height - 2) + 1;
}
}
int main()
{
setup(); // 初始化
while (!gameover)
{
draw(); // 绘制游戏界面
input(); // 接收方向键
logic(); // 游戏逻辑
Sleep(50); // 延时,调整游戏速度
}
printf("Game Over!\n");
return 0;
}
```
这是一个简单的控制台小游戏,用户通过方向键控制蛇的移动,吃到食物得分,碰到自身或者边界游戏结束。