C/C++教程

C++实现迷宫(alpha)

本文主要是介绍C++实现迷宫(alpha),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

The implementation of mazegame with C++(alpha V)

Write at the begining :

Rubbish words:
  As a computer professional student, I have never carried on a big relatively program and my programming level is so low and I get a sense of blank and nothingness because I will survive relying on it
  Moreover, it seem to be a little useless in that it couldn't bring me bonus in overall evaluation and others
  However, I hate the sense of extremely astute and this sense influence on my judgement. In other words, it can be seen as a entertainment. 
Of course, my similiar behavior will surround my courses 
  At last, I want to be a advanced programmer and apply computer technology that others studied to business development to influence the world, though may be lower than scientific research 
Function introduction:
    1.welcome
	![image](https://www.www.zyiz.net/i/l/?n=20&i=blog/2371174/202109/2371174-20210912155109912-1213084113.png)
    2.menu
	![image](https://www.www.zyiz.net/i/l/?n=20&i=blog/2371174/202109/2371174-20210912155135565-1045724364.png)
    3.view_ans
	![image](https://www.www.zyiz.net/i/l/?n=20&i=blog/2371174/202109/2371174-20210912155143931-556047400.png)
    4.autogame
	![image](https://www.www.zyiz.net/i/l/?n=20&i=blog/2371174/202109/2371174-20210912155153346-1148985667.png)
    5.yourgame
	![image](https://www.www.zyiz.net/i/l/?n=20&i=blog/2371174/202109/2371174-20210912155203591-1503586946.png)

Word is cheap, show the code:

/*linux version(my host machine)*/
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<ctime>
#ifdef linux
#include<termios.h>
#include<unistd.h>
#endif
#ifdef _WINDOWS_
#include<conio.h>
#endif
#define MAX_X 20
#define MAX_Y 30
using namespace std;

bool flag=false;
bool slow=false;
bool autogame=true;
int maze[MAX_X][MAX_Y];
void delay(int time){
    int now=clock();
    while(clock()-now<time);
}
struct node{
    int x;
    int y;
    char direction;
    node* next;
};
class stack_of_maze{
    private:
        node * head;

    public:
        stack_of_maze(){
            head=NULL;
        }
        ~stack_of_maze(){
            node* p=head;
            while(head!=NULL){
                head=head->next;
                delete p;
                p=head;
            }
        }
        void push(int nx,int ny,char ndirection){
            node* new_node = new node;
            if (new_node!=NULL){
                new_node->x=nx;
                new_node->y=ny;
                new_node->direction=ndirection;
                new_node->next=NULL;
                if (head==NULL){
                    head=new_node;
                }
                else{
                    new_node->next=head;
                    head=new_node;
                }
            }
            else{
                cout<<"Training allocation failed!"<<endl;
            }
        }
        node* pop(int& xx,int& yy){
            if (head!=NULL){
                node* p=head;
                head=head->next;
                xx=p->x;
                yy=p->y;
                delete p;
            }
            return head;
        }
        void print(){   //printf th到行尾后开始插入如何更改为在后面e routine 
            if (head!=NULL){
                node* p=head;
                while(p!=NULL){
                    cout<<" "<<p->x<<" "<<p->y<<" "<<p->direction<<endl;
                    p=p->next;
                }
            }
            else cout<<"stack is empty, printing failed!"<<endl;
        }
};
// create maze
void createMaze(){
    int maxway = MAX_X*MAX_Y;
    // fill the maze with 1
    for (int i=0;i<MAX_X;i++){
        for (int j=0;j<MAX_Y;j++){
            maze[i][j] = 1;
        }
    }
    //random function seed taking time as parameter
    srand((unsigned)time(NULL));
    //create maze randomly
    int x,y;
    for (int i=0;i<maxway;i++){
        x=rand()%(MAX_X-2)+1;
        y=rand()%(MAX_Y-2)+1;
        maze[x][y]=0;
    }
    maze[1][1]=0;
    maze[MAX_X-2][MAX_Y-2]=0;

    maze[0][1]=3;
    maze[MAX_X-1][MAX_Y-2]=0;
}
void printMaze(){
    system("clear");
    for (int i=0;i<MAX_X;i++){
        for (int j=0;j<MAX_Y;j++){
            if (maze[i][j]==0) {cout<<"  ";continue;}
            if (maze[i][j]==1) {cout<<"■ ";continue;}
            if (maze[i][j]==2) {cout<<"× ";continue;}        //死胡同
            if (maze[i][j]==3) {cout<<"↓ ";continue;}        //向下走
            if (maze[i][j]==4) {cout<<"→ ";continue;}
            if (maze[i][j]==5) {cout<<"← ";continue;}
            if (maze[i][j]==6) {cout<<"↑ ";continue;}
            if (maze[i][j]==7) {cout<<"※ ";continue;}       //the now position
        }
        cout<<endl;
    }
    //slow or not
    // if (slow) sleep(1);
    if (slow) delay(CLOCKS_PER_SEC*0.1);
}
// check the maze having access or not 
// simple analysis about the check function:
/*
1. (the auxilliary measure I couldn't consider of) mark the routine having passed in the maze(temp actually, after all, mazemap shall not be changed)
2. s store the optimized or tending to optimization routine and is optimized by the last if sentence
3. It doesn't employ the recursion method, but use temp and s implement that a way to black, and backtracking when it's black !!!\
*/
void check(stack_of_maze &s){
    // backup the mapmaze
    int temp[MAX_X][MAX_Y];
    for (int i=0;i<MAX_X;i++){
        for (int j=0;j<MAX_Y;j++){
            temp[i][j]=maze[i][j];
        }
    }
    int x=1,y=1;                            //start point
    while(1){
        temp[x][y] = 2;
        // go down
        if (temp[x+1][y]==0){
            s.push(x,y,'D');
            // mark current location with a downward symbol
            temp[x][y]=3;
            x++;
            temp[x][y]=7;                   //current location
            // judge that whether having gotten the exit or not ; y-->flag=true
            if (x==MAX_X-1 && y==MAX_Y-2){
                flag=true;
                return ;
            }
            else continue;
        }

        // go right 
        if (temp[x][y+1]==0){
            s.push(x,y,'R');
            // mark current location with a rightward symbol
            temp[x][y]=4;
            y++;
            temp[x][y]=7;
            if (x==MAX_X-1 && y==MAX_Y-2){
                flag=true;
                return ;
            }
            else continue;
        }

        // go left
        if (temp[x][y-1]==0){
            s.push(x,y,'L');
            temp[x][y]=5;
            y--;
            temp[x][y]=7;
            if (x==MAX_X-1 && y==MAX_Y-2){
                flag=true;
                return ;
            }
            else continue;
        }

        // go up
        if (temp[x-1][y]==0){
            s.push(x,y,'U');
            temp[x][y]=6;
            x--;
            temp[x][y]=7;
            if (x==MAX_X-1 && y==MAX_Y-2){
                flag=true;
                return ;
            }
            else continue;
        }

        // the four directions !=0 , and then back start
        //Pay attention to the pop !!! ( after some circulation back one point can be go on OR the start point
        // pop behavior has been done before it is used to judge
        if (s.pop(x,y)==NULL && temp[x-1][y]!=0 && temp[x+1][y]!=0 && temp[x][y-1]!=0 && temp[x][y+1]!=0){
            temp[0][1]=7;
            if (temp[1][1]!=1) temp[1][1]=2;
            return ;
        }
    }
}
#ifdef linux
// the next content is so difficult and strange for me and 
char getch(){
    char ch;
    //保存原有终端属性和新设置的终端属性
    static struct termios oldt, newt;

    //获得终端原有属性并保存在结构体oldt
    tcgetattr( STDIN_FILENO, &oldt);

    //设置新的终端属性
    newt = oldt;
    newt.c_lflag &= ~(ICANON);
    tcsetattr( STDIN_FILENO, TCSANOW, &newt);

    //取消回显
    system("stty -echo");
    ch = (char) getchar();
    system("stty echo");

    //让终端恢复为原有的属性
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}
#endif
void move(){
    int x=1,y=1;
    maze[x][y]=7;
    printMaze();
    while(1){
        switch(getch()){
            case 's':
                if (maze[x+1][y]==0){
                    maze[x][y]=3;           // In the interface with customer, just display the current position
                    maze[++x][y]=7;
                    printMaze();
                    if (x==MAX_X-1 && y==MAX_Y-2) {cout<<"\n\nVictory!"<<endl;
                    return ;}
                }
                break;
                // else cout<<"\a";
            case 'd':
                if (maze[x][y+1]==0){
                    maze[x][y]=4;
                    maze[x][++y]=7;
                    printMaze();
                    if (x==MAX_X-1 && y==MAX_Y-2) {cout<<"\n\nVictory!"<<endl;
                    return ;}
                }
                break;
            case 'a':
                if (maze[x][y-1]==0){
                    maze[x][y]=5;
                    maze[x][--y]=7;
                    printMaze();
                    if (x==MAX_X-1 && y==MAX_Y-2) {cout<<"\n\nVictory!"<<endl;
                    return ;}
                }
                break;
            case 'w':
                if (maze[x-1][y]==0){
                    maze[x][y]=6;
                    maze[--x][y]=7;
                    printMaze();
                    if (x==MAX_X-1 && y==MAX_Y-2) {cout<<"\n\nVictory!"<<endl;
                    return ;}
                }
                break;
        }
    }
}
void automove(stack_of_maze & s){
    int x=1,y=1;
    while(1){
        maze[x][y]=2;
        //down
        if (maze[x+1][y]==0){
            s.push(x,y,'D');
            maze[x][y]=3;
            maze[++x][y]=7;
            if (slow) printMaze();
            if (x==MAX_X-1 && y==MAX_Y-2) {
                s.push(x,y,'*');
                cout<<"\n\nVictory!"<<endl;
                return ;
            }
            else continue;
        }
        //right
        if (maze[x][y+1]==0){
            s.push(x,y,'R');
            maze[x][y]=4;
            maze[x][++y]=7;
            if (slow) printMaze();
            if (x==MAX_X-1 && y==MAX_Y-2) {
                s.push(x,y,'*');
                cout<<"\n\nVictory!"<<endl;
                return ;
            }
            else continue;
        }
        //left
        if (maze[x][y-1]==0){
            s.push(x,y,'L');
            maze[x][y]=5;
            maze[x][--y]=7;
            if (slow) printMaze();
            if (x==MAX_X-1 && y==MAX_Y-2) {
                s.push(x,y,'*');
                cout<<"\n\nVictory!"<<endl;
                return ;
            }
            else continue;
        }
        //up
        if (maze[x-1][y]==0){
            s.push(x,y,'U');
            maze[x][y]=6;
            maze[--x][y]=7;
            if (slow) printMaze();
            if (x==MAX_X-1 && y==MAX_Y-2) {
                s.push(x,y,'*');
                cout<<"\n\nVictory!"<<endl;
                return ;
            }
            else continue;
        }
        node* ntemp=s.pop(x,y);
        if (maze[x][y]==3) maze[x][y]=6;
        if (maze[x][y]==4) maze[x][y]=5;
        if (maze[x][y]==5) maze[x][y]=4;
        if (maze[x][y]==6) maze[x][y]=3;
        if (slow) printMaze();
        if (ntemp==NULL){
            if (maze[x+1][y]!=0 && maze[x-1][y]!=0 && maze[x][y+1]!=0 && maze[x][y-1]!=0){
                cout<<"\n\ncan't find routine!"<<endl;
                maze[0][1]=7;
                if (maze[1][1]!=1) maze[1][1]=2;
                return ;
            }
        }
    }
}
void menu();

void gamestart(){
    // Initialize the map 

    flag=false;
    while (!flag){
        stack_of_maze stack;
        createMaze();
        check(stack);
        system("clear");
        cout<<"\t*              loading.            *"<<endl;
        system("clear");
        cout<<"\t*              loading..           *"<<endl;
        system("clear");
        cout<<"\t*              loading...          *"<<endl;
    }
    printMaze();
    cout<<"\n\n\tEnter the enter key to continue and then input your command!"<<endl;
    getchar();
    //Games on their own
    if (!autogame){
        move();
        cout<<"\n\n\tEnter the enter key to continue"<<endl;
        getchar();
        menu();
    }
    //autogame
    else{
        stack_of_maze stack2;
        automove(stack2);
    }
    printMaze();
    cout<<"\n\n         Enter the enter key to continue"<<endl;
    getchar();
    menu();
}
void menu(){
    system("clear");
    cout<<"\n\n\t****************************************"<<endl;
    cout<<"\t*                                      *"<<endl;
    cout<<"\t*               1.查看路径             *"<<endl;
    cout<<"\t*                                      *"<<endl;
    cout<<"\t*               2.自动进行             *"<<endl;
    cout<<"\t*                                      *"<<endl;
    cout<<"\t*               3.自行游戏             *"<<endl;
    cout<<"\t*                                      *"<<endl;
    cout<<"\t*               4.退出游戏             *"<<endl;
    cout<<"\t*                                      *"<<endl;
    cout<<"\t****************************************"<<endl;
    slow=false;
    //choose
    switch(getch()){
        case '1':
            autogame=true;
            gamestart();
            break;
        case '2':
            autogame=true;
            slow=true;
            gamestart();
            break;
        case '3':
            autogame=false;
            gamestart();
            break;
        case '4':
            exit(1);
            break;
        default:
            cout<<"\n\n\tWrong operation! Enter the enter key to back"<<endl;
            getchar();
            menu();
    }
    getchar();
}

// int main(int argc,char** argv){
int main(){
    system("clear");
    printf(R"deli(                                                                                                                                            
                                                                                                                                            
            ,---,               ,--,                                    ,---,                      ____                                     
          ,--.' |      ,--,   ,--.'|         ,---,  ,--,              ,--.' |                    ,'  , `.                                   
          |  |  :    ,--.'|   |  | :       ,---.'|,--.'|              |  |  :                 ,-+-,.' _ |                  ,----,           
          :  :  :    |  |,    :  : '       |   | :|  |,      .--.--.  :  :  :              ,-+-. ;   , ||                .'   .`|           
   ,---.  :  |  |,--.`--'_    |  ' |       |   | |`--'_     /  /    ' :  |  |,--.         ,--.'|'   |  || ,--.--.     .'   .'  .'   ,---.   
  /     \ |  :  '   |,' ,'|   '  | |     ,--.__| |,' ,'|   |  :  /`./ |  :  '   |        |   |  ,', |  |,/       \  ,---, '   ./   /     \  
 /    / ' |  |   /' :'  | |   |  | :    /   ,'   |'  | |   |  :  ;_   |  |   /' :        |   | /  | |--'.--.  .-. | ;   | .'  /   /    /  | 
.    ' /  '  :  | | ||  | :   '  : |__ .   '  /  ||  | :    \  \    `.'  :  | | |        |   : |  | ,    \__\/: . . `---' /  ;--,.    ' / | 
'   ; :__ |  |  ' | :'  : |__ |  | '.'|'   ; |:  |'  : |__   `----.   \  |  ' | :        |   : |  |/     ," .--.; |   /  /  / .`|'   ;   /| 
'   | '.'||  :  :_:,'|  | '.'|;  :    ;|   | '/  '|  | '.'| /  /`--'  /  :  :_:,'        |   | |`-'     /  /  ,.  | ./__;     .' '   |  / | 
|   :    :|  | ,'    ;  :    ;|  ,   / |   :    :|;  :    ;'--'.     /|  | ,'            |   ;/        ;  :   .'   \;   |  .'    |   :    | 
 \   \  / `--''      |  ,   /  ---`-'   \   \  /  |  ,   /   `--'---' `--''              '---'         |  ,     .-./`---'         \   \  /  
  `----'              ---`-'             `----'    ---`-'                                               `--`---'                   `----'   
                                                                                                                                            )deli");
    // printf("\nRead the instruction carefully, please:\n1. Due to my desperately poor programming level, there exists many bugs inevitably. Long for your feedback sincerely(email:2945034270@qq.com)\n2. The given map displayed by the first choice isn't the optimum(I will amend it in the Beta version), show your optimum\n3. TBC...");
    printf("Read the instruction carefully, please:\n");
    printf("1. Due to my desperately poor programming level, there exists many bugs inevitably. Long for your feedback sincerely(email:2945034270@qq.com)\n");
    printf("2. man is young but once, you couldn't go back in the games on your own");
    printf("3. s/↓  d/→  a/←  w/↑ to manipulate your movement\n");
    printf("4. Found problems(I want change in the beta version):");
    printf("    1>The given map displayed by the first choice isn't the optimum(I will amend it in the Beta version), show your optimum");
    printf("-1. TBC...");
    printf("\n\n\tEnter the enter key to continue");
    getchar();
    menu();
    return 0;
}

Some improvement will be implemented in the beta version:

1. The method of creating maze is not excellent! It can be optimized;
2. The implementation of getch in linux is so strange for me 
3. automove function is the visualization of the dfs method, not show the optimized routine
4. The displayed map should be optimized in the Beta version
5 TBC...

Transplantation from linux to windows(TBC)
Reference:
1. VS2019,MingW和GCC(G++)的微妙区别
2. linux与windows交叉编译
3. MinGW gcc 生成动态链接库 dll 的一些问题汇总
4. conio.h中的常用函数——getch()
5. 将exe和dll文件打包成单一的启动文件(两种方法)
6. 跨平台C、C++代码注意的事项及如何编写跨平台的C/C++代码

这篇关于C++实现迷宫(alpha)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!