修练者
这是迷宫小游戏:
#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
bool f,v[15][15];
char s[15][15]={{'#','#','#','#','#','#','#','#','#','#','#'},//40
{'@',' ',' ',' ',' ',' ',' ',' ',' ','&','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#',' ',' ',' ',' ',' ',' ',' ',' ',' ','#'},
{'#','#','#','#','#','#','#','#','#','#','#'}
};
int sx,sy,ex,ey;
int d[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct node{
int x,y;
};
queue<node> q;
char a;
int main(){
do{
system("cls");
memset(v,0,sizeof(v));
for(int i=1;i<11;i++){
for(int j=1;j<10;j++){
if(s[i][j]=='&'){
continue;
}
// srand(time(0));
int x=rand()%3+1;
if(x==2){
s[i][j]='#';
}else{
s[i][j]='?';
}
}
}
sx=1,sy=9,ex=1,ey=0;
q.push({sx,sy});
v[sx][sy]=true;
while(!q.empty()){
node h=q.front();
if(h.x==ex&&h.y==ey){
goto aab;
}
q.pop();
for(int i=0;i<=3;i++){
int nx=h.x+d[i][0],ny=h.y+d[i][1];
if(nx>=0&&nx<=9&&ny>=0&&ny<=9&&!v[nx][ny]&&s[nx][ny]=='?'){
q.push({nx,ny});
v[nx][ny]=true;
}
}
}
}while(true);
aab:;
int cnt=0;
int x=1,y=9;
for(;;){
cnt++;
aa:;
system("cls");
cout<<"w=↑,s=↓,a=←,d=→,#=墙,&=你,@=出口\n";
for(int i=x-1;i<=x+1;i++){
for(int j=y-1;j<=y+1;j++){
cout<<s[i][j];
}
cout<<'\n';
}
cin>>a;
switch(a){
case 'w':
if(s[x-1][y]=='#'){
system("cls");
cout<<"走不通\n";
system("pause");
goto aa;
}else if(s[x-1][y]=='?'){
swap(s[x][y],s[x-1][y]);
x--;
}else{
system("cls");
cout<<"通关!";
Sleep(2000);
return cnt;
}
break;
case 'a':
if(s[x][y-1]=='#'){
system("cls");
cout<<"走不通\n";
system("pause");
goto aa;
}else if(s[x][y-1]=='?'){
swap(s[x][y],s[x][y-1]);
y--;
}else{
system("cls");
cout<<"通关!";
Sleep(2000);
return cnt;
}
break;
case 's':
if(s[x+1][y]=='#'){
system("cls");
cout<<"走不通\n";
system("pause");
goto aa;
}else{
swap(s[x][y],s[x+1][y]);
x++;
}
break;
case 'd':
if(s[x][y+1]=='#'){
system("cls");
cout<<"走不通\n";
system("pause");
goto aa;
}else{
swap(s[x][y],s[x][y+1]);
y++;
}
break;
}
}
return 0;
}
中级守护
把打印地图时system("cls")都换成这个
void cls(){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coordScreen = { 0, 0 }; // home for the cursor
SetConsoleCursorPosition( hConsole, coordScreen );
}
函数功能:将光标位置调到(0,0)
然后重新打印地图
for(int i=x-1;i<=x+1;i++){
for(int j=y-1;j<=y+1;j++){
cout<<s[i][j];
}
cout<<'\n';
}
如果要把整个屏幕都清了,用system("cls")
初级守护
用system("cls")就会很卡,换成
void cls(){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coordScreen = { 0, 0 }; // home for the cursor
SetConsoleCursorPosition( hConsole, coordScreen );
}