帮我用c语言写一个贪吃蛇
时间: 2023-03-27 09:01:28 浏览: 80
Contour,用c语言写贪吃蛇源码,c语言项目
好的,我可以为您提供一个基本的贪吃蛇游戏的 C 语言代码。请注意,这只是一个基本的版本,您可以根据需要进行修改和改进。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
#define MAX_LENGTH (WIDTH * HEIGHT)
int x, y;
int fruitX, fruitY;
int score;
int gameOver;
int tailX[MAX_LENGTH], tailY[MAX_LENGTH];
int tailLength = ;
enum eDirection { STOP = , LEFT, RIGHT, UP, DOWN };
enum eDirection dir;
void Setup()
{
gameOver = ;
dir = STOP;
x = WIDTH / 2;
y = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
score = ;
}
void Draw()
{
system("cls");
for (int i = ; i < WIDTH + 2; i++)
printf("#");
printf("\n");
for (int i = ; i < HEIGHT; i++)
{
for (int j = ; j < WIDTH; j++)
{
if (j == )
printf("#");
if (i == y && j == x)
printf("O");
else if (i == fruitY && j == fruitX)
printf("F");
else
{
int print = ;
for (int k = ; k < tailLength; 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 = ; i < WIDTH + 2; i++)
printf("#");
printf("\n");
printf("Score: %d\n", score);
}
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver = 1;
break;
}
}
}
void Logic()
{
int prevX = tailX[];
int prevY = tailY[];
int prev2X, prev2Y;
tailX[] = x;
tailY[] = y;
for (int i = 1; i < tailLength; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
if (x >= WIDTH) x = ; else if (x < ) x = WIDTH - 1;
if (y >= HEIGHT) y = ; else if (y < ) y = HEIGHT - 1;
for (int i = ; i < tailLength; i++)
if (tailX[i] == x && tailY[i] == y)
gameOver = 1;
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
tailLength++;
}
}
int main()
{
Setup();
while (!gameOver)
{
Draw();
Input();
Logic();
Sleep(50);
}
return ;
}
阅读全文