SSブログ

迷路の作成プログラム [C++]

 乱数で迷路を作成するプログラムを紹介します。

 今回は、グラフィックを使用しないで、文字ベースで出力しております。

 迷路の作成自体は簡単ですが、グラフィック表示は面倒かな…

(by 心如) 

───〔出力例〕───
maze01.jpg

───〔プログラム例〕───
// Maze.cpp
//
// 迷路の作成
//
// 2012.04.29 ───── coded by 心如

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

const int Xmax = 42;
const int Ymax = 36;
const int MCan = 400;

struct Point{
    int x;
    int y;
};

class Maze{
    int map[Xmax + 1][Ymax + 1];
    Point cand[MCan + 1];
    Point dire[5];
    int ncan;
    int ndir;
    int ok;
public:
    Maze();
    void insertCan(int, int);
    Point selectCan();
    Point selectDir();
    void print();
};

Maze::Maze(){
    int i, j;
    for(i = 0; i <= Xmax; i++){
        for(j = 0; j <= Ymax; j++){
            map[i][j] = 1;
        }
    }
    for(i = 3; i <= Xmax - 3; i++){
        for(j = 3; j <= Ymax - 3; j++){
            map[i][j] = 0;
        }
    }
    ncan = 0;
    for(i = 2; i <= Xmax / 2 - 2; i++){
        insertCan(i * 2, 2);
        insertCan(i * 2, Ymax - 2);
    }
    for(j = 2; j <= Ymax / 2 - 2; j++){
        insertCan(2, j * 2);
        insertCan(Xmax - 2, j * 2);
    }
    ndir = 4;
    dire[1].x = 2; dire[1].y = 0;
    dire[2].x = 0; dire[2].y = 2;
    dire[3].x = -2; dire[3].y = 0;
    dire[4].x = 0; dire[4].y = -2;
    Point wp;
    while(ncan > 0){
        wp = selectCan();
        do{
            ndir = 4;
            Point dp;
            do{
                dp = selectDir();
                ok = (map[wp.x + dp.x][wp.y + dp.y])? 0: 1;
            }while(ok == 0 && ndir > 0);
            if(ok){
                map[wp.x + dp.x / 2][wp.y + dp.y / 2] = 1;
                wp.x += dp.x;
                wp.y += dp.y;
                map[wp.x][wp.y] = 1;
                insertCan(wp.x, wp.y);
            }
        }while(ok);

    }
}

inline void Maze::insertCan(int x, int y){
    ncan++;
    cand[ncan].x = x;
    cand[ncan].y = y;
}

Point Maze::selectCan(){
    Point rp;
    int n = rand() % ncan + 1;
    rp = cand[n];
    cand[n] = cand[ncan];
    ncan--;
    return rp;
}

Point Maze::selectDir(){
    int n = rand() % ndir + 1;
    Point rp = dire[n];
    dire[n] = dire[ndir];
    dire[ndir--] = rp;
    return rp;
}

void Maze::print(){
    int i, j;
    for(j = 2; j <= Ymax - 2; j++){
        for(i = 2; i <= Xmax - 2; i++){
            if(map[i][j]) cout << "■";
            else cout << " ";
        }
        cout << endl;
    }
}

int main(){
    srand((unsigned)time(NULL));
    Maze mz;
    mz.print();
    return 0;
}


タグ:パズル
nice!(0)  コメント(0)  トラックバック(0) 

nice! 0

コメント 0

コメントを書く

お名前:
URL:
コメント:
画像認証:
下の画像に表示されている文字を入力してください。

Facebook コメント

トラックバック 0

この広告は前回の更新から一定期間経過したブログに表示されています。更新すると自動で解除されます。