贪吃蛇小游戏C语言代码
时间: 2023-07-09 20:07:06 浏览: 96
以下是一个简单的贪吃蛇小游戏的 C 语言代码,仅供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#define WIDTH 60
#define HEIGHT 20
int x, y; // 贪吃蛇头部的坐标
int fruit_x, fruit_y; // 水果的坐标
int tail_x[100], tail_y[100]; // 贪吃蛇身体的坐标
int nTail; // 贪吃蛇身体的长度
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN }; // 贪吃蛇的移动方向
enum eDirection dir;
int score; // 得分
void Setup()
{
// 初始化游戏
dir = STOP;
x = WIDTH / 2;
y = HEIGHT / 2;
srand(time(NULL));
fruit_x = rand() % (WIDTH - 2) + 1;
fruit_y = rand() % (HEIGHT - 2) + 1;
nTail = 0;
score = 0;
}
void Draw()
{
// 绘制游戏界面
system("cls");
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
if (j == 0)
printf("#");
if (i == y && j == x)
printf("O");
else if (i == fruit_y && j == fruit_x)
printf("F");
else
{
int bDraw = 0;
for (int k = 0; k < nTail; k++)
{
if (tail_x[k] == j && tail_y[k] == i)
{
printf("o");
bDraw = 1;
}
}
if (!bDraw)
printf(" ");
}
if (j == WIDTH - 1)
printf("#");
}
printf("\n");
}
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
printf("Score: %d\n", score);
}
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':
dir = STOP;
break;
case 'q':
exit(0);
break;
}
}
}
void Logic()
{
// 处理游戏逻辑
int prev_tail_x = tail_x[0];
int prev_tail_y = tail_y[0];
int prev2_tail_x, prev2_tail_y;
tail_x[0] = x;
tail_y[0] = y;
for (int i = 1; i < nTail; i++)
{
prev2_tail_x = tail_x[i];
prev2_tail_y = tail_y[i];
tail_x[i] = prev_tail_x;
tail_y[i] = prev_tail_y;
prev_tail_x = prev2_tail_x;
prev_tail_y = prev2_tail_y;
}
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
if (x == 0 || x == WIDTH - 1 || y == 0 || y == HEIGHT - 1) // 碰到边缘
{
printf("\a"); // 发出警告声
Sleep(1000);
Setup();
}
for (int i = 0; i < nTail; i++) // 碰到自己的身体
{
if (tail_x[i] == x && tail_y[i] == y)
{
printf("\a"); // 发出警告声
Sleep(1000);
Setup();
}
}
if (x == fruit_x && y == fruit_y) // 吃到水果
{
score += 10;
nTail++;
srand(time(NULL));
fruit_x = rand() % (WIDTH - 2) + 1;
fruit_y = rand() % (HEIGHT - 2) + 1;
}
}
int main()
{
Setup();
while (true)
{
Draw();
Input();
Logic();
Sleep(50);
}
return 0;
}
```
阅读全文