模拟迷宫游戏
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#define ROW 10
#define CUL 10
//设置X,Y坐标(全局变量);
int currentX=8,currentY=1;
//移动后的XY坐标(全局变量);
int nextX,nextY;
//看下一步是否能走 int[x][y]==' ' ;
char street = ' ';
char map[ROW][CUL] = {
{'#','#','#','#','#','#','#','#','#','#'},
{'#','#',' ',' ',' ',' ','#','#','#','#'},
{'#',' ',' ','#','#',' ',' ','#','#','#'},
{'#',' ','#',' ','#','#',' ',' ','#','#'},
{'#',' ',' ',' ',' ','#','#',' ','#','#'},
{'#',' ','#','#',' ','#','#',' ','#','#'},
{'#',' ','#','#',' ',' ','#',' ','#','#'},
{'#',' ','#','#','#',' ','#',' ',' ',' '},
{'#','0','#',' ',' ',' ','#','#','#','#'},
{'#','#','#','#','#','#','#','#','#','#'},
};
using namespace std;
void show(); // 打印地图
void moveTo(char direction); //控制小人移动
void judge(); // 判断是非否为边界
int main()
{
nextX = currentX;
nextY = currentY;
//屏幕打印出迷宫;
show();
char direction;
while (1) {
cout <<"请移动人物,用键盘W/S/A/D(上下左右)操作" << endl;
direction = getch();
moveTo(direction);
judge();
system("CLS");
show();
if (currentX==ROW-1||currentY==CUL-1){
cout << "通关了,呵呵!" << endl;
break;
}
}
return 0;
show();
}
//打印地图
void show(){
for(int i = 0;i<ROW;i++){
for (int j = 0;j<CUL;j++) {
printf("%c",map[i][j]);
}
printf("\n");
}
}
//移动人物
void judge(){
if (map[nextX][nextY]==street) {
char temp = map[currentX][currentY];
map[currentX][currentY] = map[nextX][nextY];
map[nextX][nextY] = temp;
currentX = nextX;
currentY = nextY;
}else{
nextX = currentX;
nextY = currentY;
}
}
//计算下一个位置
void moveTo(char direction){
switch (direction) {
case 'w':{
nextX = currentX - 1;
break;
}
case 's':{
nextX = currentX + 1;
break;
}
case 'a':{
nextY = currentY - 1;
break;
}
case 'd':{
nextY = currentY + 1;
break;
}
default:
break;
}
}