c语言贪吃蛇游戏代码
时间: 2023-08-02 16:06:52 浏览: 235
下面是一个简单的贪吃蛇游戏的C语言代码:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define N 20
int x, y, fx, fy, score, flag;
int bodyx[100], bodyy[100];
void init();
void draw();
void input();
void move();
int main()
{
init();
while (1)
{
draw();
input();
move();
if (flag == 1)
break;
}
printf("\nGame over! Your score is: %d", score);
return 0;
}
void init()
{
srand((unsigned)time(NULL));
x = N / 2, y = N / 2;
fx = rand() % N, fy = rand() % N;
score = 0;
flag = 0;
}
void draw()
{
system("cls");
for (int i = 0; i <= N; i++)
printf("#");
printf("\n");
for (int i = 0; i < N; i++)
{
printf("#");
for (int j = 0; j < N; j++)
{
if (i == x && j == y)
printf("O");
else if (i == fx && j == fy)
printf("*");
else
{
int flag = 0;
for (int k = 0; k < score; k++)
{
if (bodyx[k] == i && bodyy[k] == j)
{
printf("o");
flag = 1;
break;
}
}
if (!flag)
printf(" ");
}
}
printf("#\n");
}
for (int i = 0; i <= N; i++)
printf("#");
printf("\nScore: %d", score);
}
void input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
flag = (y == 0);
y--;
break;
case 'd':
flag = (y == N - 1);
y++;
break;
case 'w':
flag = (x == 0);
x--;
break;
case 's':
flag = (x == N - 1);
x++;
break;
case 'x':
flag = 1;
break;
}
}
}
void move()
{
if (x == fx && y == fy)
{
score++;
fx = rand() % N;
fy = rand() % N;
}
for (int i = score - 1; i > 0; i--)
{
bodyx[i] = bodyx[i - 1];
bodyy[i] = bodyy[i - 1];
}
bodyx[0] = x;
bodyy[0] = y;
for (int i = 1; i < score; i++)
{
if (bodyx[i] == x && bodyy[i] == y)
flag = 1;
}
if (x < 0 || x >= N || y < 0 || y >= N)
flag = 1;
}
```
该代码实现了一个基本的贪吃蛇游戏,玩家通过输入方向键控制蛇的移动,吃到食物可以得分,撞到墙或自己的身体则游戏结束。
阅读全文