用c语言生成贪吃蛇的代码
时间: 2024-02-24 11:54:29 浏览: 88
以下是一个简单的用C语言生成贪吃蛇的代码,仅供参考:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define Up 1
#define Down 2
#define Left 3
#define Right 4
#define Width 30
#define Height 20
int x, y, fruitX, fruitY, score, gameover, speed;
int tailX[100], tailY[100], ntail;
int direction;
void setup()
{
gameover = 0;
direction = Right;
x = Width / 2;
y = Height / 2;
fruitX = rand() % Width;
fruitY = rand() % Height;
score = 0;
speed = 100;
}
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 == fruitY && j == fruitX)
printf("F");
else
{
int print = 0;
for (int k = 0; k < ntail; k++)
{
if (tailX[k] == j && tailY[k] == i)
{
printf("o");
print = 1;
}
}
if (!print)
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':
direction = Left;
break;
case 'd':
direction = Right;
break;
case 'w':
direction = Up;
break;
case 's':
direction = Down;
break;
case 'x':
gameover = 1;
break;
}
}
}
void logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < ntail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (direction)
{
case Up:
y--;
break;
case Down:
y++;
break;
case Left:
x--;
break;
case Right:
x++;
break;
default:
break;
}
if (x >= Width)
x = 0;
else if (x < 0)
x = Width - 1;
if (y >= Height)
y = 0;
else if (y < 0)
y = Height - 1;
for (int i = 0; i < ntail; i++)
{
if (tailX[i] == x && tailY[i] == y)
gameover = 1;
}
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % Width;
fruitY = rand() % Height;
ntail++;
if (score % 100 == 0)
speed -= 10;
}
}
int main()
{
srand(time(NULL));
setup();
while (!gameover)
{
draw();
input();
logic();
Sleep(speed);
}
printf("GAME OVER\n");
printf("Score: %d\n", score);
return 0;
}
```
该代码使用了Windows系统的conio.h库,可以通过键盘操作控制贪吃蛇的移动方向。其中,setup()函数初始化游戏界面和初始参数,draw()函数绘制游戏界面,input()函数获取玩家输入,logic()函数处理游戏逻辑。最后,在while循环中循环执行以上函数,直到游戏结束。
阅读全文