C语言代码:给我一个贪吃蛇游戏代码
时间: 2023-07-10 19:06:22 浏览: 136
以下是一个简单的贪吃蛇游戏的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
int score;
int gameover;
int speed;
int x, y;
int fruit_x, fruit_y;
int tail_x[100], tail_y[100];
int ntail;
enum direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
enum direction dir;
void Setup()
{
gameover = 0;
dir = STOP;
x = WIDTH / 2;
y = HEIGHT / 2;
fruit_x = rand() % WIDTH;
fruit_y = rand() % HEIGHT;
score = 0;
speed = 100;
ntail = 0;
}
void Draw()
{
system("cls");
for (int i = 0; i < HEIGHT + 2; i++)
{
for (int j = 0; j < WIDTH + 2; j++)
{
if (i == 0 || i == HEIGHT + 1)
printf("#");
else if (j == 0 || j == WIDTH + 1)
printf("#");
else if (i == y && j == x)
printf("O");
else if (i == fruit_y && j == fruit_x)
printf("F");
else
{
int print_tail = 0;
for (int k = 0; k < ntail; k++)
{
if (tail_x[k] == j && tail_y[k] == i)
{
printf("o");
print_tail = 1;
}
}
if (!print_tail)
printf(" ");
}
}
printf("\n");
}
printf("Score: %d\n", score);
printf("Speed: %d\n", speed);
}
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameover = 1;
break;
}
}
}
void Logic()
{
int prev_x = tail_x[0];
int prev_y = tail_y[0];
int prev2_x, prev2_y;
tail_x[0] = x;
tail_y[0] = y;
for (int i = 1; i < ntail; i++)
{
prev2_x = tail_x[i];
prev2_y = tail_y[i];
tail_x[i] = prev_x;
tail_y[i] = prev_y;
prev_x = prev2_x;
prev_y = prev2_y;
}
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
if (x < 1 || x > WIDTH || y < 1 || y > HEIGHT)
gameover = 1;
for (int i = 0; i < ntail; i++)
{
if (tail_x[i] == x && tail_y[i] == y)
gameover = 1;
}
if (x == fruit_x && y == fruit_y)
{
score += 10;
fruit_x = rand() % WIDTH;
fruit_y = rand() % HEIGHT;
ntail++;
speed -= 5;
}
}
int main()
{
Setup();
while (!gameover)
{
Draw();
Input();
Logic();
Sleep(speed);
}
printf("Game Over!\n");
return 0;
}
```
该代码基于控制台,在 Windows 系统下编译运行。游戏规则与经典贪吃蛇游戏相同,玩家通过方向键控制蛇的移动,吃到食物加分并增加蛇的长度,碰到边界或自身游戏结束。
阅读全文