c语言贪吃蛇代码简短
时间: 2023-09-26 21:02:40 浏览: 103
c语言简单的贪食蛇代码
5星 · 资源好评率100%
C语言贪吃蛇的代码可以通过合理的算法设计和简洁的代码实现。以下是一个简短的示例:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
int width = 20; // 游戏界面宽度
int height = 20; // 游戏界面高度
int gameOver = 0;
int score = 0;
int snakeX[100], snakeY[100]; // 蛇身坐标
int snakeLength = 1; // 蛇身长度
int fruitX, fruitY; // 水果坐标
enum Direction { STOP = 0, UP, DOWN, LEFT, RIGHT }; // 蛇运动方向
enum Direction dir;
void Setup()
{
srand(time(NULL));
gameOver = 0;
dir = STOP;
snakeX[0] = width / 2;
snakeY[0] = height / 2;
fruitX = rand() % (width - 1);
fruitY = rand() % (height - 1);
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 == snakeY[0] && j == snakeX[0])
printf("O");
else if (i == fruitY && j == fruitX)
printf("@");
else
{
int tailPrinted = 0;
for (int k = 1; k < snakeLength; k++)
{
if (snakeX[k] == j && snakeY[k] == i)
{
printf("o");
tailPrinted = 1;
break;
}
}
if (!tailPrinted)
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 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'x':
gameOver = 1;
break;
}
}
}
void Logic()
{
int prevX = snakeX[0];
int prevY = snakeY[0];
int prev2X, prev2Y;
snakeX[0] += (dir == RIGHT) ? 1 : (dir == LEFT) ? -1 : 0;
snakeY[0] += (dir == DOWN) ? 1 : (dir == UP) ? -1 : 0;
for (int i = 1; i < snakeLength; i++)
{
prev2X = snakeX[i];
prev2Y = snakeY[i];
snakeX[i] = prevX;
snakeY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
if (snakeX[0] >= width || snakeX[0] < 0 || snakeY[0] >= height || snakeY[0] < 0)
gameOver = 1;
for (int i = 1; i < snakeLength; i++)
{
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i])
gameOver = 1;
}
if (snakeX[0] == fruitX && snakeY[0] == fruitY)
{
score += 10;
fruitX = rand() % (width - 1);
fruitY = rand() % (height - 1);
snakeLength++;
}
}
int main()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
// 控制游戏速度
_sleep(10);
}
return 0;
}
```
以上代码为一个采用字符界面的简易贪吃蛇游戏实现,具备基本的蛇的移动、水果的生成与吃掉、边界碰撞和自身碰撞判断、分数统计等功能。同时,程序采用了简短的代码段实现游戏的逻辑处理。
阅读全文