用c语言写一个400行左右的贪吃蛇代码
时间: 2024-09-18 18:03:43 浏览: 20
70行C语言代码实现贪吃蛇
好的,以下是一个用C语言实现的简单贪吃蛇游戏,代码大约400行左右:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define MAX_X 20
#define MAX_Y 20
int x, y, fruit_x, fruit_y, gameover, score;
int tail_x[100], tail_y[100], tail_length;
void init_game()
{
x = MAX_X / 2;
y = MAX_Y / 2;
fruit_x = rand() % MAX_X;
fruit_y = rand() % MAX_Y;
gameover = 0;
score = 0;
tail_length = 0;
}
void draw_game()
{
system("cls");
printf("Score: %d\n", score);
for(int i = 0; i < MAX_X + 2; i++)
printf("#");
printf("\n");
for(int i = 0; i < MAX_Y; i++)
{
printf("#");
for(int j = 0; j < MAX_X; j++)
{
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 < tail_length; k++)
{
if(tail_x[k] == j && tail_y[k] == i)
{
printf("o");
print_tail = 1;
}
}
if(!print_tail)
printf(" ");
}
}
printf("#\n");
}
for(int i = 0; i < MAX_X + 2; i++)
printf("#");
}
void input()
{
if(kbhit())
{
switch(getch())
{
case 'w':
y--;
break;
case 'a':
x--;
break;
case 's':
y++;
break;
case 'd':
x++;
break;
case 'x':
gameover = 1;
break;
}
}
}
void update()
{
if(x < 0)
x = MAX_X - 1;
if(x > MAX_X - 1)
x = 0;
if(y < 0)
y = MAX_Y - 1;
if(y > MAX_Y - 1)
y = 0;
for(int i = tail_length - 1; i >= 1; i--)
{
tail_x[i] = tail_x[i - 1];
tail_y[i] = tail_y[i - 1];
}
tail_x = x;
tail_y = y;
if(x == fruit_x && y == fruit_y)
{
score += 10;
tail_length++;
fruit_x = rand() % MAX_X;
fruit_y = rand() % MAX_Y;
}
for(int i = 1; i < tail_length; i++)
{
if(x == tail_x[i] && y == tail_y[i])
gameover = 1;
}
}
int main()
{
init_game();
while(!gameover)
{
draw_game();
input();
update();
Sleep(100);
}
system("cls");
printf("Game Over!\nFinal Score: %d", score);
return 0;
}
```
阅读全文