一个从文件读取地图的推箱子小游戏
用 P 代表人物,B 代表箱子,E代表终点。
程序代码:
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<conio.h>
#define N 12
using namespace std;
char Map[N][N]; //地图数组
struct Position{int x,y;};//坐标结构体
Position person, //人物坐标
next, //人物下一步坐标
dnext; //人物下两步坐标
char dirction; //方向
int arrive, //到达的箱子的个数
destination; //目的地(箱子)个数
void Hello(){ //欢迎界面
cout << "\n\n\t\t\t■■■■ ■■■ ■ ■ ■ ■ ■■■ ■ ■ \n";
cout << "\t\t\t■ ■ ■ ■ ■ ■ ■■ ■■ ■ ■ ■■ ■ \n";
cout << "\t\t\t■ ■ ■ ■ ■■ ■ ■ ■ ■ ■ ■ ■ ■ ■ \n";
cout << "\t\t\t■■■■ ■ ■ ■ ■ ■■ ■ ■■■■ ■ ■■ \n";
cout << "\t\t\t■ ■ ■ ■ ■■ ■ ■ ■ ■ ■ ■ ■ \n";
cout << "\t\t\t■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ \n";
cout << "\t\t\t■■■■ ■■■ ■ ■ ■ ■ ■ ■ ■ ■ \n";
getchar();
}
void Initialise(){ //初始化函数
destination=arrive=0;
ifstream out("推箱子.txt"); //从文件里读取地图
out>>noskipws; //不跳过空格
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){ //从文件读取地图
out>>Map[i][j];
if(Map[i][j]=='P'){ //读取P(人)的坐标
person.x=j;
person.y=i;
}
if(Map[i][j]=='E') destination++;//有几个目的地(箱子)
}
}
}
void Map_Upate(){ //地图刷新函数
system("cls"); //清空屏幕
for(int i=0;i<N;i++){
for(int j=0;j<N;j++)
cout<<Map[i][j]<<' ';
if(i==4) cout<<"\t\t 按r重来";
cout<<endl;
}
if(arrive==destination){
cout<<"end";
exit(-1);
}
}
void Move(){ //人物移动
dirction=_getch();
switch(dirction){ //输入字符控制移动
case 'w':
next.x=person.x;
next.y=person.y-1;
dnext.x=person.x;
dnext.y=person.y-2;
break;
case 's':
next.x=person.x;
next.y=person.y+1;
dnext.x=person.x;
dnext.y=person.y+2;
break;
case 'a':
next.x=person.x-1;
next.y=person.y;
dnext.x=person.x-2;
dnext.y=person.y;
break;
case 'd':
next.x=person.x+1;
next.y=person.y;
dnext.x=person.x+2;
dnext.y=person.y;
break;
}if(Map[dnext.y][dnext.x]=='E'&&Map[next.y][next.x]=='B') arrive++; //箱子到达终点
/************************更新地图信息******************************/
if(Map[next.y][next.x]=='B'){ //人碰到箱子
if(Map[dnext.y][dnext.x]!='+'&&Map[dnext.y][dnext.x]!='B'){ //箱子前方无障碍
Map[person.y][person.x]=' '; //擦除原先的人物位置
Map[next.y][next.x]=' '; //擦除原先的箱子位置
person.x=next.x; //新坐标
person.y=next.y;
Map[person.y][person.x]='P'; //记录新的人物位置
Map[dnext.y][dnext.x]='B'; //记录新的箱子位置
}
}
else{ //人没碰到箱子
if(Map[next.y][next.x]!='+'&&Map[next.y][next.x]!='E'){ //人前方无障碍
Map[person.y][person.x]=' ';
person.x=next.x;
person.y=next.y;
Map[person.y][person.x]='P';
}
}
}
int main(){
Hello();
Initialise();
while(1){
if(dirction=='r') Initialise(); //按 r 重新初始化
Map_Upate();
Move();
}
}