用c语言编写一个贪吃蛇小游戏
时间: 2023-09-14 12:09:44 浏览: 104
tanchishe.rar_c 小游戏代码_c语言 小游戏_c语言 贪吃蛇_c语言小游戏_贪吃蛇
当然可以!下面是一个简单的贪吃蛇游戏的C语言代码示例:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
int width = 20, height = 20;
int gameover, score;
int x, y, fruitX, fruitY, flag;
int tailX[100], tailY[100];
int countTail = 0;
void setup()
{
gameover = 0;
x = width / 2;
y = height / 2;
label1:
fruitX = rand() % width;
if (fruitX == 0)
goto label1;
label2:
fruitY = rand() % height;
if (fruitY == 0)
goto label2;
score = 0;
}
void draw()
{
system("cls");
int i, j;
for (i = 0; i < width; i++)
{
for (j = 0; j < height; j++)
{
if (i == 0 || i == height - 1 || j == 0 || j == width - 1)
printf("#");
else
{
if (i == x && j == y)
printf("O");
else if (i == fruitX && j == fruitY)
printf("F");
else
{
int isTail = 0;
for (int k = 0; k < countTail; k++)
{
if (i == tailX[k] && j == tailY[k])
{
printf("o");
isTail = 1;
}
}
if (!isTail)
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d", score);
printf("\n");
printf("Press X to quit the game");
}
void input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
flag = 1;
break;
case 's':
flag = 2;
break;
case 'd':
flag = 3;
break;
case 'w':
flag = 4;
break;
case 'x':
gameover = 1;
break;
}
}
}
void algorithm()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < countTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (flag)
{
case 1:
y--;
break;
case 2:
x++;
break;
case 3:
y++;
break;
case 4:
x--;
break;
}
if (x < 0 || x >= width || y < 0 || y >= height)
gameover = 1;
for (int i = 0; i < countTail; i++)
{
if (x == tailX[i] && y == tailY[i])
gameover = 1;
}
if (x == fruitX && y == fruitY)
{
label3:
fruitX = rand() % width;
if (fruitX == 0)
goto label3;
label4:
fruitY = rand() % height;
if (fruitY == 0)
goto label4;
score += 10;
countTail++;
}
}
int main()
{
int m, n;
char c;
printf("Enter the screen resolution (e.g. 80 25): ");
scanf("%d %d", &m, &n);
width = m;
height = n;
setup();
while (!gameover)
{
draw();
input();
algorithm();
Sleep(10); // 小休眠一会儿,控制游戏速度
}
printf("\nGame Over!\n");
printf("Your score: %d\n", score);
return 0;
}
```
这个代码示例使用了Windows.h库中的`Sleep`函数,所以在Windows平台上编译运行可能会更好。你可以根据需要进行修改和优化。希望能对你有所帮助!
阅读全文