帮我用c语言写一个贪吃蛇的代码
时间: 2024-06-13 15:05:20 浏览: 162
以下是一个简单的贪吃蛇游戏的C语言代码,你可以根据需要进行修改和优化:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define WIDTH 10
#define HEIGHT 20
int x, y, foodx, foody, score, gameover;
int tailx[100], taily[100], counttail = 0;
void setup()
{
gameover = 0;
x = WIDTH / 2;
y = HEIGHT / 2;
srand(time(NULL));
foodx = rand() % WIDTH;
foody = rand() % HEIGHT;
score = 0;
}
void draw()
{
int i, j, k;
system("cls");
for (i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
for (i = 0; i < HEIGHT; i++)
{
for (j = 0; j < WIDTH; j++)
{
if (j == 0)
printf("#");
if (i == y && j == x)
printf("0");
else if (i == foody && j == foodx)
printf("F");
else
{
int print = 0;
for (k = 0; k < counttail; k++)
{
if (tailx[k] == j && taily[k] == i)
{
printf("o");
print = 1;
}
}
if (!print)
printf(" ");
}
if (j == WIDTH - 1)
printf("#");
}
printf("\n");
}
for (i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
printf("SCORE:%d\n", score);
}
void input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
x--;
break;
case 'd':
x++;
break;
case 'w':
y--;
break;
case 's':
y++;
break;
case 'x':
gameover = 1;
break;
}
}
}
void logic()
{
int i;
int prevx = tailx[0];
int prevy = taily[0];
int prev2x, prev2y;
tailx[0] = x;
taily[0] = y;
for (i = 1; i < counttail; i++)
{
prev2x = tailx[i];
prev2y = taily[i];
tailx[i] = prevx;
taily[i] = prevy;
prevx = prev2x;
prevy = prev2y;
}
switch (_getch())
{
case 'a':
x--;
break;
case 'd':
x++;
break;
case 'w':
y--;
break;
case 's':
y++;
break;
case 'x':
gameover = 1;
break;
}
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)
gameover = 1;
for (i = 0; i < counttail; i++)
{
if (tailx[i] == x && taily[i] == y)
gameover = 1;
}
if (x == foodx && y == foody)
{
srand(time(NULL));
foodx = rand() % WIDTH;
foody = rand() % HEIGHT;
score += 10;
counttail++;
}
}
int main()
{
setup();
while (!gameover)
{
draw();
input();
logic();
}
printf("GAME OVER\n");
printf("YOUR SCORE:%d\n", score);
return 0;
}
```
阅读全文