#include <stdio.h>
#include <conio.h>
#include <windows.h>
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
int x, y; // 豆人的坐标
int fruitX, fruitY; // 果实的坐标
int score; // 得分
int width = 20; // 地图宽度
int height = 20; // 地图高度
int gameover; // 游戏结束标志
int tailX[100], tailY[100]; // 豆人尾巴的坐标
int nTail; // 豆人尾巴的长度
void setup()
{
gameover = 0;
x = width / 2; // 初始位置在地图中间
y = 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 == y && j == x)
printf("O"); // 打印豆人
else if (i == fruitY && j == fruitX)
printf("F"); // 打印果实
else
{
int printTail = 0;
for (int k = 0; k < nTail; 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 'w':
y--;
break;
case 's':
y++;
break;
case 'a':
x--;
break;
case 'd':
x++;
break;
case 'x':
gameover = 1;
break;
}
}
}
void logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (_getch())
{
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case 'x':
gameover = 1;
break;
}
if (x >= width || x < 0 || y >= height || y < 0)
gameover = 1; // 撞墙,游戏结束
for (int i = 0; i < nTail; i++)
{
if (tailX[i] == x && tailY[i] == y)
gameover = 1; // 撞到自己,游戏结束
}
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
}
int main()
{
setup();
while (!gameover)
{
draw();
input();
logic();
Sleep(100); // 控制游戏速度
}
return 0;
}
标签:case,width,新人,练习,++,break,int,printf,贪吃
From: https://blog.51cto.com/u_16485171/9040954