通过C++设计了一个迷宫游戏,涉及到链表,C++基本操作,终端字符处理,深度优先遍历算法。下面开始吧!
- 在全局变量中定义地图,包括地图的长和高(30*20),同时还需定义一些标记。
- flag 用于创建地图,true代表地图传创建成功。
- slow用于更换游戏速度,true代表游戏慢速。
- autogame用于更换游戏模式,true代表自动游戏。
#define MAX_X 20
#define MAX_Y 30
bool flag = false;
bool slow = false;
bool autogame = true;
int maze[MAX_X][MAX_Y]; //迷宫
2.路线栈
路线栈设计来记录移动路径。路径栈是一个类,它可以记录地图的坐标和移动轨迹。
class stack_of_maze{
private:
//code
public:
//code
};
- 成员变量
在成员变量中定义一个数据结构来包括地图坐标和移动信息。
//记录迷宫坐标
struct node
{
int x;
int y;
char direction; //上一步路径(如何来的)
node* next;
};
node* head;
- 成员函数
构造和析构
stack_of_maze(){
//初始化
head = NULL;
}
~stack_of_maze(){
node* p = head;
//逐个删除
while(head!=NULL){
head = head->next;
delete p;
p = head;
}
}
压栈
设置一个新节点用于插入,首先将信息记录到新节点中,再把新节点插入到栈顶。这个函数的功能用于添加新的移动信息。
void push(int xx,int yy,char ddirection){
//定义一个新节点
node* new_node = new node;
//赋值
if(new_node!=NULL){
new_node->x = xx;
new_node->y = yy;
new_node->direction = ddirection;
new_node->next = NULL;
//判断栈是否为空,如果为空则直接把新节点赋值给栈,否则添加到栈顶
if(head==NULL)
head = new_node;
else{
new_node->next = head;
head = new_node;
}
}
else
cout<<"内存分配失败"<<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(){
if(head!=NULL){
node* p = h