增加了操作说明
#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<windows.h>
#include<ctime>
using namespace std;
int Height,Width;
int map[101][101],nx=2,ny=1;
void color(int a){//设置字体颜色
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);
}
void gotoxy(int x,int y){//移动光标
COORD pos={x,y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}
void hide(){//隐藏光标
CONSOLE_CURSOR_INFO a;
GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&a);
a.bVisible=false;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&a);
}
void create(int x,int y){//创建地图
int c[4][2]={0,1,1,0,0,-1,-1,0};
for(int i=0;i<4;i++){
int j=rand()%4;
swap(c[i][0],c[j][0]);
swap(c[i][1],c[j][1]);
}
map[x][y]=1;
for(int i=0;i<4;i++){
if(map[x+2*c[i][0]][y+2*c[i][1]]==0){
map[x+c[i][0]][y+c[i][1]]=1;
create(x+2*c[i][0],y+2*c[i][1]);
}
}
}
int get_key(){//获取按键
char c;
while(1){
if(c==27){//Esc
return 0;
}
c=getch();
if(c==72){//上
return 1;
}else if(c==80){//下
return 2;
}else if(c==75){//左
return 3;
}else if(c==77){//右
return 4;
}
}
return 0;
}
void paint(int x,int y){//画图
hide();
gotoxy(2*y-2,x-1);
if(x==nx&&y==ny){//本身
color(15);
cout<<"▇";
return;
}
if(x==2&&y==1){//起点
color(7);
cout<<"●";
return;
}
switch(map[x][y]){
case 0://墙
color(7);
cout<<"▇";
break;
case 1://路
cout<<" ";
break;
case 2://终点
color(14);
cout<<"★";
break;
}
}
void game(){
while(1){
if(map[nx][ny]==2){//是否到达终点
system("cls");
cout<<"Victory!";
break;
}
int c=get_key();
switch(c){
case 1://当指令为上
if(map[nx-1][ny]!=0){
nx--;
if(f==0){
paint(nx+1,ny);
paint(nx,ny);
}else{
paint2(nx,ny);
}
}
break;
case 2://当指令为下
if(map[nx+1][ny]!=0){
nx++;
if(f==0){
paint(nx-1,ny);
paint(nx,ny);
}else{
paint2(nx,ny);
}
}
break;
case 3://当指令为左
if(map[nx][ny-1]!=0){
ny--;
if(f==0){
paint(nx,ny+1);
paint(nx,ny);
}else{
paint2(nx,ny);
}
}
break;
case 4://当指令为右
if(map[nx][ny+1]!=0){
ny++;
if(f==0){
paint(nx,ny-1);
paint(nx,ny);
}else{
paint2(nx,ny);
}
}
break;
}
}
}
int main(){
srand(time(0));//随机种子
hide();
cout<<"操作说明:"<<endl;
cout<<" ↑←↓→移动"<<endl;
color(15);
cout<<"▇ ";
color(7);
cout<<":本身"<<endl;
cout<<"▇ :墙"<<endl;
cout<<" :路"<<endl;
cout<<"●:起点"<<endl;
color(14);
cout<<"★";
color(7);
cout<<":终点"<<endl;
system("pause");
while(1){
system("cls");
cout<<"地图长(必须为奇数):";
cin>>Height;
if(Height%2==0){
cout<<"Error";
Sleep(1000);
continue;
}
cout<<"地图宽(必须为奇数):";
cin>>Width;
if(Width%2==0){
cout<<"Error";
Sleep(1000);
continue;
}
break;
}
Sleep(1000);
system("cls");
for(int i=0;i<=Height+1;i++){
for(int j=0;j<=Width+1;j++){
if(i==0||i==Height+1||j==0||j==Width+1){
map[i][j]=1;
}else{
map[i][j]=0;
}
}
}
create(2*(rand()%(Height/2)+1),2*(rand()%(Width/2)+1));
for(int i=0;i<=Height+1;i++){
map[i][0]=0;
map[i][Width+1]=0;
}
for(int i=0;i<=Width+1;i++){
map[0][i]=0;
map[Height+1][i]=0;
}
map[2][1]=-1;
map[Height-1][Width]=2;
for(int i=1;i<=Height;i++){
for(int j=1;j<=Width;j++){
paint(i,j);
ans[i][j]=map[i][j];
}
}
game();
Sleep(2000);
return 0;
}