帮我写贪吃蛇的C语言程序
时间: 2023-08-28 16:57:49 浏览: 99
gobang,贪吃蛇c语言编程源码,c语言程序
当然可以帮你写贪吃蛇的C语言程序!下面是一个简单的贪吃蛇程序的示例代码:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
int score;
int gameover;
int length;
int headX, headY;
int fruitX, fruitY;
int tailX[100], tailY[100];
enum eDirecton { STOP = 0, LEFT, RIGHT, UP, DOWN };
enum eDirecton dir;
void Setup()
{
gameover = 0;
dir = STOP;
headX = WIDTH / 2;
headY = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
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 == headY && j == headX)
printf("O");
else if (i == fruitY && j == fruitX)
printf("F");
else
{
int printTail = 0;
for (int k = 0; k < length; k++)
{
if (tailX[k] == j && tailY[k] == i)
{
printf("o");
printTail = 1;
}
}
if (!printTail)
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':
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[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = headX;
tailY[0] = headY;
for (int i = 1; i < length; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir)
{
case LEFT:
headX--;
break;
case RIGHT:
headX++;
break;
case UP:
headY--;
break;
case DOWN:
headY++;
break;
}
if (headX >= WIDTH)
headX = 0;
else if (headX < 0)
headX = WIDTH - 1;
if (headY >= HEIGHT)
headY = 0;
else if (headY < 0)
headY = HEIGHT - 1;
for (int i = 0; i < length; i++)
{
if (tailX[i] == headX && tailY[i] == headY)
gameover = 1;
}
if (headX == fruitX && headY == fruitY)
{
score += 10;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
length++;
}
}
int main()
{
Setup();
while (!gameover)
{
Draw();
Input();
Logic();
Sleep(10); // 程序暂停10毫秒
}
return 0;
}
```
这是一个基本的贪吃蛇游戏程序,使用了 `conio.h` 和 `windows.h` 头文件来实现一些控制台窗口的功能。你可以将上述代码保存为一个 C 文件,然后编译运行即可尝试玩贪吃蛇游戏。希望这个示例代码能帮到你!如果有任何问题,请随时向我提问。
阅读全文