#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
//定义豆子结构体
struct Bean{
int posx;
int posy;
};
//定义英雄结构体
struct Hero{
int posx;
int posy;
int score;
};
void ShowMap(struct Bean * bean,struct Hero * hero);
void getPos(int *posx,int *posy);
void Init_Game();
#define ySize 20
#define xSize 60
char Map[ySize][xSize] = {};
//定义英雄
struct Hero hero={0,0,0};
//定义豆子
struct Bean bean={0,0};
int main(int arg ,char * argv[])
{
//游戏初始化-----给英雄位置、豆子的位置、地图初始化
Init_Game();
while(1)
{
//设置键盘不等待回车
system("clear");
ShowMap(&bean,&hero);
//获取键盘输入
system("stty -icanon");
char c = getchar();
//根据键盘输入更改英雄的位置
if (c == 'w' || c == 'W')
{
hero.posy -= 1;
}
else if(c == 's' || c=='S')
{
hero.posy += 1;
}
else if( c == 'a' || c=='A')
{
hero.posx -=1;
}
else if(c == 'd' || c == 'D')
{
hero.posx += 1;
}
//英雄撞墙的处理方式
if(hero.posx == 0 || hero.posy==0 || hero.posx == xSize-1 || hero.posy == ySize-1)
{
system("clear");
printf("你撞墙了!!!!已死亡!!!\n");
return 0;
}
//英雄是否吃到豆子,豆子是否需要重新生成
if(hero.posx == bean.posx && hero.posy == bean.posy)
{
hero.score += 1;
getPos(&bean.posx,&bean.posy);
}
//显示地图就可以了
ShowMap(&bean,&hero);
}
return 0;
}
void ShowMap(struct Bean * bean,struct Hero * hero)
{
//填充内容
int i = 0, j =0;
for(j=0;j<ySize;j++)
{
for(i=0;i<xSize;i++)
{
Map[j][i]=' ';
}
}
//填充上下墙
for(i=0; i<xSize;i++)
{
Map[0][i]='*';
Map[ySize-1][i]='*';
}
//填充左右墙
for(j=0; j<ySize;j++)
{
Map[j][0]='*';
Map[j][xSize-1] = '*';
}
//填充豆子、英雄
Map[bean->posy][bean->posx]='@';
Map[hero->posy][hero->posx]='H';
//二位数组打印输出
for(j=0;j<ySize;j++)
{
for(i=0;i<xSize;i++)
{
if(j == bean->posy && i == bean->posx)
printf("\033[32m%c\033[0m",Map[j][i]);
else if(j == hero->posy && i == hero->posx)
printf("\033[36m%c\033[0m",Map[j][i]);
else
printf("%c",Map[j][i]);
}
printf("\n");
}
//用户提示信息
printf("w=up\ts=down\ta=left\td=right\t\t\033[33m score:%d \033[0m\n",hero->score);
}
//随机获取位置
void getPos(int *posx,int *posy)
{
//设置随机数种子
unsigned int seed = (unsigned int)time(NULL);
//产生随机数
srand(seed);
//填充位置
*posx = rand()%(xSize-1);
*posy = rand()%(ySize-1);
if(*posx == 0)
{
*posx += 1;
}
if(*posy == 0)
{
*posy += 1;
}
}
//游戏初始化
void Init_Game()
{
//初始化豆子位置
getPos(&bean.posx,&bean.posy);
sleep(1);
//初始化英雄位置
getPos(&hero.posx,&hero.posy);
//显示地图
ShowMap(&bean,&hero);
}