勇闯迷宫
2025-01-13 17:41:07
发布于:江苏
#include<iostream>
#include<conio.h>
#include<ctime> //time(0)
#include<cstdlib> //rand()
#include<windows.h>
using namespace std;
int main(){
char maze[18][24]= {"************** ",//1
" * * ",//2
" ************ * ** * ",//3
" * **** * ",//4
" ********** * * * ",//5
" ** * * ",//6
" ** ***** ***** * ** ",//7
" * * ",//8
" * ********** ",//9
" * * * * $ ",//10
" **** * * ****** ",//11
" * * * * * * ",//12
" * ****** * ** * * * ",//13
" * * ** * * * ",//14
" ********** ** * ",//15
" * ",//16
"*** *******",//17
"***********************"};//18
//生成i角色
int x,y;
srand(time(0)); //随机种子
x = rand()%18;
y = rand()%23;
while(maze[x][y] != ' '){
x = rand()%18;
y = rand()%23;
}
maze[x][y] = 'i';
//显示迷宫
for(int i =0;i<18;i++){ //外层行数
for(int j=0;j<23;j++){ //内层列数
cout<<maze[i][j]<<" "; //数组名[行数][列数]
}
cout<<endl;
}
//实现上下左右移动
char c;
int cnt = 0;
while(true){
c = getch();
cnt++;
system("cls"); //清屏
if(c == 'w'){
//向上 行x变,列y不变
if(maze[x-1][y] != '*'){
maze[x][y] = ' ';
--x;
maze[x][y] = 'i';
}
}
if(c == 's'){
//向下
if(maze[x+1][y] != '*'){
maze[x][y] = ' ';
++x;
maze[x][y] = 'i';
}
}
if(c == 'a'){
//向左
if(maze[x][y-1] != '*'){
maze[x][y] = ' ';
--y;
maze[x][y] = 'i';
}
}
if(c == 'd'){
//向右
if(maze[x][y+1] != '*'){
maze[x][y] = ' ';
++y;
maze[x][y] = 'i';
}
}
//显示迷宫
for(int i =0;i<18;i++){ //外层行数
for(int j=0;j<23;j++){ //内层列数
cout<<maze[i][j]<<" "; //数组名[行数][列数]
}
cout<<endl;
}
if(maze[9][20]=='i'){
maze[0][14] = ' ';
MessageBox(0,"取到宝箱","提示",MB_OK);
}
//到达出口
if(maze[0][14]=='i'){
string steps="到达终点,共用步数:";
char sum[100];
itoa(cnt,sum,10);//
steps+=sum;
MessageBox(0,steps.c_str(),"提示",MB_OK);
break;
}
}
return 0;
}
这里空空如也
有帮助,赞一个