给一份贪吃蛇C++代码
时间: 2023-12-11 10:04:02 浏览: 69
贪吃蛇c++代码
以下是一份简单的贪吃蛇C代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 40
#define HEIGHT 20
#define SNAKE_LENGTH 50
int head_x, head_y; // 贪吃蛇头的位置
int body_x[SNAKE_LENGTH], body_y[SNAKE_LENGTH]; // 贪吃蛇身体的位置
int body_length; // 贪吃蛇身体的长度
int food_x, food_y; // 食物的位置
void draw_border(); // 画边界
void draw_food(); // 画食物
void draw_snake(); // 画贪吃蛇
void generate_food(); // 生成食物
void move_snake(); // 移动贪吃蛇
int check_collision(); // 检查碰撞
int main()
{
srand(time(NULL)); // 初始化随机种子
head_x = WIDTH / 2;
head_y = HEIGHT / 2;
body_length = 1;
body_x[0] = head_x;
body_y[0] = head_y;
generate_food();
while (1)
{
draw_border();
draw_food();
draw_snake();
move_snake();
if (check_collision())
{
printf("Game over.\n");
break;
}
Sleep(100);
}
return 0;
}
void draw_border()
{
system("cls");
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
for (int i = 0; i < HEIGHT; i++)
{
printf("#");
for (int j = 0; j < WIDTH; j++)
printf(" ");
printf("#\n");
}
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
}
void draw_food()
{
printf("\033[%d;%dH$", food_y + 1, food_x + 1);
}
void draw_snake()
{
printf("\033[%d;%dH@", head_y + 1, head_x + 1);
for (int i = 0; i < body_length; i++)
printf("\033[%d;%dH*", body_y[i] + 1, body_x[i] + 1);
}
void generate_food()
{
while (1)
{
food_x = rand() % WIDTH;
food_y = rand() % HEIGHT;
if (food_x != head_x || food_y != head_y)
{
int found = 0;
for (int i = 0; i < body_length; i++)
{
if (food_x == body_x[i] && food_y == body_y[i])
{
found = 1;
break;
}
}
if (!found)
break;
}
}
}
void move_snake()
{
int dx = 0, dy = 0;
if (_kbhit())
{
int c = _getch();
switch (c)
{
case 'w':
case 'W':
dy = -1;
break;
case 's':
case 'S':
dy = 1;
break;
case 'a':
case 'A':
dx = -1;
break;
case 'd':
case 'D':
dx = 1;
break;
}
}
int prev_x = head_x, prev_y = head_y;
head_x += dx;
head_y += dy;
if (head_x < 0)
head_x = WIDTH - 1;
else if (head_x >= WIDTH)
head_x = 0;
if (head_y < 0)
head_y = HEIGHT - 1;
else if (head_y >= HEIGHT)
head_y = 0;
if (head_x == food_x && head_y == food_y)
{
body_length++;
body_x[body_length - 1] = prev_x;
body_y[body_length - 1] = prev_y;
generate_food();
}
for (int i = body_length - 1; i > 0; i--)
{
body_x[i] = body_x[i - 1];
body_y[i] = body_y[i - 1];
}
body_x[0] = prev_x;
body_y[0] = prev_y;
}
int check_collision()
{
for (int i = 0; i < body_length; i++)
{
if (head_x == body_x[i] && head_y == body_y[i])
return 1;
}
return 0;
}
```
阅读全文