C语言用栈实现迷宫小游戏
时间: 2023-09-02 20:08:43 浏览: 52
好的,我们可以用C语言的栈来实现迷宫小游戏。
首先,我们需要定义迷宫的地图。可以用二维数组来表示迷宫的地图,其中0表示可以通行的路,1表示障碍物。
```c
#define ROW 10
#define COL 10
int map[ROW][COL] = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 0, 1, 1, 0, 0},
{0, 0, 0, 0, 1, 0, 1, 1, 0, 0},
{0, 1, 1, 0, 0, 0, 1, 1, 0, 0},
{0, 1, 1, 0, 1, 1, 1, 1, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 1, 1, 1, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 1, 1, 1, 1, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
```
接下来,我们定义栈的结构体和相关的操作。
```c
#define MAX_STACK_SIZE 100
typedef struct {
int row;
int col;
} Position;
typedef struct {
Position data[MAX_STACK_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isStackEmpty(Stack *s) {
return s->top == -1;
}
int isStackFull(Stack *s) {
return s->top == MAX_STACK_SIZE - 1;
}
void push(Stack *s, Position pos) {
if (isStackFull(s)) {
printf("Stack is full.\n");
return;
}
s->top++;
s->data[s->top] = pos;
}
Position pop(Stack *s) {
if (isStackEmpty(s)) {
printf("Stack is empty.\n");
Position p = {-1, -1};
return p;
}
Position p = s->data[s->top];
s->top--;
return p;
}
Position peek(Stack *s) {
if (isStackEmpty(s)) {
printf("Stack is empty.\n");
Position p = {-1, -1};
return p;
}
return s->data[s->top];
}
```
然后,我们定义一个函数来判断一个位置是否可以通行。
```c
int isPositionValid(Position pos) {
if (pos.row < 0 || pos.row >= ROW || pos.col < 0 || pos.col >= COL) {
return 0;
}
if (map[pos.row][pos.col] == 1) {
return 0;
}
return 1;
}
```
接下来,我们定义一个函数来打印迷宫的地图。
```c
void printMap() {
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%d ", map[i][j]);
}
printf("\n");
}
}
```
最后,我们定义一个函数来实现迷宫的小游戏。该函数首先将起点入栈,并不断出栈,判断出栈的位置是否为终点,如果是则游戏结束,否则将该位置的上、下、左、右四个相邻位置入栈,并将该位置标记为已访问。
```c
void mazeGame(Position start, Position end) {
Stack s;
initStack(&s);
push(&s, start);
while (!isStackEmpty(&s)) {
Position current = pop(&s);
if (current.row == end.row && current.col == end.col) {
printf("Congratulations! You have reached the end of the maze.\n");
return;
}
if (map[current.row][current.col] != 2) {
map[current.row][current.col] = 2;
if (isPositionValid((Position){current.row - 1, current.col})) {
push(&s, (Position){current.row - 1, current.col});
}
if (isPositionValid((Position){current.row + 1, current.col})) {
push(&s, (Position){current.row + 1, current.col});
}
if (isPositionValid((Position){current.row, current.col - 1})) {
push(&s, (Position){current.row, current.col - 1});
}
if (isPositionValid((Position){current.row, current.col + 1})) {
push(&s, (Position){current.row, current.col + 1});
}
}
}
printf("Sorry, you have failed to reach the end of the maze.\n");
}
```
现在我们可以在main函数中调用mazeGame函数来开始迷宫小游戏。
```c
int main() {
Position start = {1, 1};
Position end = {8, 8};
printMap();
mazeGame(start, end);
return 0;
}
```
这样,我们就用C语言的栈实现了迷宫小游戏。