用C语言编写贪吃蛇游戏
时间: 2024-05-01 16:22:32 浏览: 137
好的,我可以为你提供一个简单的贪吃蛇游戏的C语言代码。以下是代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define MAX_X 20
#define MAX_Y 20
#define SNAKE_LENGTH 50
int x, y, fruitX, fruitY, score, gameOver;
int snakeX[SNAKE_LENGTH], snakeY[SNAKE_LENGTH];
int snakeLength = 3;
char direction;
void Setup()
{
gameOver = 0;
direction = 'w';
x = MAX_X / 2;
y = MAX_Y / 2;
fruitX = rand() % MAX_X;
fruitY = rand() % MAX_Y;
score = 0;
}
void Draw()
{
system("cls");
printf("Score: %d\n\n", score);
for (int i = 0; i < MAX_X + 1; i++)
{
printf("#");
}
printf("\n");
for (int i = 0; i < MAX_Y; i++)
{
for (int j = 0; j < MAX_X; j++)
{
if (j == 0 || j == MAX_X - 1)
{
printf("#");
}
else if (i == y && j == x)
{
printf("O");
}
else if (i == fruitY && j == fruitX)
{
printf("F");
}
else
{
int print = 0;
for (int k = 0; k < snakeLength; k++)
{
if (snakeX[k] == j && snakeY[k] == i)
{
printf("o");
print = 1;
}
}
if (!print)
{
printf(" ");
}
}
}
printf("\n");
}
for (int i = 0; i < MAX_X + 1; i++)
{
printf("#");
}
printf("\n");
}
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case 'w':
direction = 'w';
break;
case 'a':
direction = 'a';
break;
case 's':
direction = 's';
break;
case 'd':
direction = 'd';
break;
case 'x':
gameOver = 1;
break;
}
}
}
void Logic()
{
int prevX = snakeX[0];
int prevY = snakeY[0];
int prev2X, prev2Y;
snakeX[0] = x;
snakeY[0] = y;
for (int i = 1; i < snakeLength; i++)
{
prev2X = snakeX[i];
prev2Y = snakeY[i];
snakeX[i] = prevX;
snakeY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (direction)
{
case 'w':
y--;
break;
case 'a':
x--;
break;
case 's':
y++;
break;
case 'd':
x++;
break;
}
if (x > MAX_X - 2 || x < 1 || y > MAX_Y - 1 || y < 1)
{
gameOver = 1;
}
for (int i = 0; i < snakeLength; i++)
{
if (snakeX[i] == x && snakeY[i] == y)
{
gameOver = 1;
}
}
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % MAX_X;
fruitY = rand() % MAX_Y;
snakeLength++;
}
}
int main()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
Sleep(50);
}
printf("Game Over!\n");
printf("Your Score: %d\n", score);
return 0;
}
```
这是一个比较简单的代码,如果你想增加游戏难度或者添加更多功能,可以在此基础上进行修改和扩展。
阅读全文