基于C語言實現(xiàn)簡單的走迷宮游戲
更新時間:2016年04月18日 16:07:22 作者:LiaoGlenn
這篇文章主要介紹了基于C語言實現(xiàn)簡單的走迷宮游戲,用到雙向隊列,方便在運行完畢后輸出經(jīng)過的點,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例講述了C語言實現(xiàn)簡單的走迷宮游戲的方法,代碼完整,便于讀者理解。
學(xué)數(shù)據(jù)結(jié)構(gòu)時用“?!睂懙囊粋€走迷宮程序,實際上用到雙向隊列,方便在運行完畢后輸出經(jīng)過的點。
#include <cstdio>
#include <deque>
#include <windows.h>
using namespace std;
class node
{
public:
int x,y;
int lastOpt;
};
deque<node> sta;
int x,y;
int endx,endy;
int mapW,mapH;
int steps;
int xopt[5]= {0,0,1,0,-1};
int yopt[5]= {0,1,0,-1,0};
int map[100][100]=
{
};
void init()
{
x = 1;
y = 1;
endx = 1;
endy = 9;
mapH = 10;
mapW = 10;
for(int i=0; i<=mapH; i++)
for(int j=0; j<=mapW; j++)
{
if(i==0 ||j==0 ||i==mapH||j==mapW)
map[i][j]=-1;
}
steps=0;
map[1][2]=-1;
map[2][2]=-1;
map[3][2]=-1;
map[4][2]=-1;
map[6][2]=-1;
map[7][2]=-1;
map[8][2]=-1;
map[9][2]=-1;
map[9][3]=-1;
map[8][3]=-1;
map[1][4]=-1;
map[3][4]=-1;
map[4][4]=-1;
map[5][4]=-1;
map[6][4]=-1;
map[7][4]=-1;
map[1][6]=-1;
map[2][6]=-1;
map[3][6]=-1;
map[4][6]=-1;
map[5][6]=-1;
map[6][6]=-1;
map[7][6]=-1;
map[8][6]=-1;
map[8][7]=-1;
map[8][8]=-1;
map[7][8]=-1;
map[6][8]=-1;
map[5][8]=-1;
map[4][8]=-1;
map[3][8]=-1;
map[2][8]=-1;
map[1][8]=-1;
map[endx][endy]=5;
}
void dis()
{
system("cls");
int ori = map[x][y];
map[x][y]=1;
for(int i=0; i<=mapH; ++i)
{
for(int j=0; j<=mapW; ++j)
{
if(map[i][j]==0)
printf(" ");
else if(map[i][j]==-1)
printf(" #");
else if(map[i][j]==1)
printf(" @");
else if(map[i][j]==2)
printf(" .");
else if(map[i][j]==5)
printf(" !");
}
cout<<i<<endl;
}
for(int j=0; j<=mapW; ++j)
cout<<j<<" ";
printf("\n\n > steps:%d Exit:(%d,%d)\n",steps,endx,endy);
map[x][y] = ori;
}
int can(int n)
{
if(map[x+xopt[n]][y+yopt[n]] == 0 || map[x+xopt[n]][y+yopt[n]] == 5)
return 1;
return 0;
}
void visit(int n)
{
map[x][y]=2;
x+=xopt[n];
y+=yopt[n];
node tem;
tem.x = x;
tem.y = y;
tem.lastOpt = n;
sta.push_back(tem);
steps++;
}
int main()
{
init();
node tem;
while( x != endx || y!=endy)
{
int cans = 0;
for(int i=1; i<=4; i++)
{
if(can(i))
{
cans = 1;
visit(i);
break;
}
}
if(!cans)
{
if(!sta.empty())
{
tem = sta.back();
map[tem.x][tem.y]=0;
sta.pop_back();
}
else
{
map[x][y]=2;
x+=xopt[tem.lastOpt];
x+=yopt[tem.lastOpt];
dis();
break;
}
}
dis();
Sleep(500);
}
if(x==endx && y == endy)
cout<<"\n > i am finished....\n";
else
cout<<"\n > i am finished...but i can't find the right way\n";
return 0;
}
效果圖:

以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)C語言有所幫助。
相關(guān)文章
c語言的cps實現(xiàn)求fibonacci數(shù)列示例
這篇文章主要介紹了c語言的cps實現(xiàn)求fibonacci數(shù)列示例,需要的朋友可以參考下2014-03-03
C++中用兩個標準容器stack,實現(xiàn)一個隊列的方法詳解
本篇文章是對C++中使用兩個標準容器stack,實現(xiàn)一個隊列的方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05
一文詳解如何實現(xiàn)QT的多語言切換(靜態(tài)+動態(tài))
這篇文章主要給大家介紹了關(guān)于如何實現(xiàn)QT的多語言切換(靜態(tài)+動態(tài))的相關(guān)資料,Qt是一款跨平臺的C++應(yīng)用程序開發(fā)框架,提供了一套豐富的工具和類庫來簡化應(yīng)用程序開發(fā),文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-06-06

