使用Python编写的迷宫游戏
发布时间:2023-12-04 13:37:17
以下是使用Python编写的迷宫游戏的代码。
import random
def create_maze(rows, cols):
maze = []
for i in range(rows):
row = []
for j in range(cols):
row.append('#')
maze.append(row)
return maze
def print_maze(maze):
for row in maze:
print(' '.join(row))
def get_neighbours(row, col, rows, cols):
neighbours = []
if row > 1:
neighbours.append((row - 2, col))
if row < rows - 2:
neighbours.append((row + 2, col))
if col > 1:
neighbours.append((row, col - 2))
if col < cols - 2:
neighbours.append((row, col + 2))
random.shuffle(neighbours)
return neighbours
def remove_wall(maze, current, next):
row = (current[0] + next[0]) // 2
col = (current[1] + next[1]) // 2
maze[row][col] = ' '
def generate_maze(maze, row, col):
maze[row][col] = ' '
neighbours = get_neighbours(row, col, len(maze), len(maze[0]))
for neighbour in neighbours:
if maze[neighbour[0]][neighbour[1]] == '#':
remove_wall(maze, (row, col), neighbour)
generate_maze(maze, neighbour[0], neighbour[1])
def main():
rows = 21
cols = 41
maze = create_maze(rows, cols)
start_row = 1
start_col = 1
generate_maze(maze, start_row, start_col)
maze[1][0] = 'S'
maze[-2][-1] = 'E'
print_maze(maze)
if __name__ == '__main__':
main()
使用例子:
from queue import Queue
def solve_maze(maze, start, end):
visited = set()
q = Queue()
q.put([start])
rows = len(maze)
cols = len(maze[0])
while not q.empty():
path = q.get()
current = path[-1]
if current == end:
return path
elif current not in visited:
for neighbour in get_neighbours(current[0], current[1], rows, cols):
new_path = list(path)
new_path.append(neighbour)
q.put(new_path)
visited.add(current)
return None
maze = create_maze(21, 41)
generate_maze(maze, 1, 1)
maze[1][0] = 'S'
maze[-2][-1] = 'E'
print_maze(maze)
start = (1, 0)
end = (len(maze) - 2, len(maze[0]) - 1)
path = solve_maze(maze, start, end)
if path:
print("
Solution:")
for step in path:
maze[step[0]][step[1]] = ' '
print_maze(maze)
else:
print("
No solution found.")
这个例子演示了生成一个迷宫并在迷宫中找到从起点到终点的路径。首先,我们创建一个21行41列的迷宫,并通过调用generate_maze函数来生成迷宫的布局。然后,在起点和终点的位置上分别标记"S"和"E"。接下来,我们通过调用solve_maze函数来找到从起点到终点的路径。如果找到了路径,我们将路径上的位置标记为空格,并打印出解决方案迷宫。否则,我们打印出"找不到解决方案"。
