迷宫小游戏实现

来源:互联网 发布:airplay windows 10 编辑:程序博客网 时间:2024/05/16 10:39

 一.首先给出一个迷宫

1 1 1 1 1 1 1 1 1 1

1 1 1 1 1 1 1 1 1 1
0 0 0 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1 1 1
1 1 0 0 0 0 0 0 1 1
1 1 0 1 1 1 1 0 1 1
1 1 0 1 1 1 1 0 1 1

1 1 0 1 1 1 1 1 1 1

二.迷宫路径为


三.实现想法

1,首先给出初始位置,遍历其位置的上下左右,如果为0则表是可以走通,如果为一则表示没有通路。

2,走到分岔路口时,选择一条通路,继续前行。如果此路不通,则返回到分岔路口处选择另一通路继续前行,如果每条分叉路口都不通,则返回到初始位置,打印没有通路。选择下一个位置是否为通条件是:位置合法和此位置为0.

3,保存走过的路线,给每条走过的路赋值2。

四,开始时,要fopen 文件读取保存在文件中的地图,读取完毕后腰fclose文件。

五,代码实现

#pragma once
#define N 10


#include<stack>
#include<assert.h>
#include<iostream>


using namespace std;


struct Pos
{
int _row;//行
int _col;//列
};


void GetMaza(int* a, int n)//读取地图
{
FILE* fout = fopen("Maza.log", "r");
assert(fout);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n;)
{
char ch = fgetc(fout);
if (ch == '0' || ch == '1')
{
a[i*n + j] = ch - '0';
++j;
}
else
{
continue;
}
}
}
fclose(fout);
}


bool CheakIsAccess(int* a, int n, Pos next)
{
assert(a);
if (next._row >= 0 && next._row < n
&&next._col >= 0 && next._col < n
&&a[next._row*n + next._col] == 0)//行列都合法且下一个为0路通
{
return true;
}
else
return false;
}


bool MazaPath(int* a, int n, const Pos& entry, stack <Pos>& path)
{
Pos next;
Pos cur = entry;
path.push(cur);
while (!path.empty())
{
if (cur._row == n - 1)
{
return true;
}
a[cur._row*n + cur._col] = 2;


next = cur;
next._col++;
if (CheakIsAccess(a, n, next))
{
cur = next;
path.push(cur);
continue;
}

next = cur;
next._row--;
if (CheakIsAccess(a, n, next))
{
cur = next;
path.push(cur);
continue;
}


next = cur;
next._col--;
if (CheakIsAccess(a, n, next))
{
cur = next;
path.push(cur);
continue;
}


next = cur;
next._row++;
if (CheakIsAccess(a, n, next))
{
cur = next;
path.push(cur);
continue;
}

cur = path.top();
path.pop();
}
return false;
}
void PrintMaza(int* a, int n)
{
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
cout << a[i*n + j] << " ";
}
cout << endl;
}
cout << endl;
}
void TestMaze()
{
int a[N][N] = {};
GetMaza((int *)a, N);
PrintMaza((int *)a, N);
//MazaPath((int *)a, N);
stack<Pos>path;
Pos entry = { 2, 0 };
bool ret = MazaPath((int *)a, N, entry, path);
cout << "是否有通道?" << ret << endl;
PrintMaza((int *)a, N);
}

主函数

#define _CRT_SECURE_NO_WARNINGS 1
#include"Maza.h"
int main()
{
TestMaze();
system("pause");
return 0;
}

六,运行结果


0 0
原创粉丝点击