python - Pygame 迷宫游戏无法正确创建关卡

标签 python python-3.x pygame maze

所以我正在尝试为学校的一个项目创建一个带有关卡的迷宫游戏。该代码有点重复,抱歉我才刚刚开始使用 pygame 进行编码。运行时,程序应输出一个迷宫,一旦用户完成,就会进入下一个级别 - 每个级别都是随机生成的。然而,只有第一个关卡正确显示,其余关卡似乎是一个网格 - 这让我认为游戏正在旧迷宫上创建一个新迷宫。

我已经粘贴了下面的代码 - 请随时留下有关如何改进我的代码的任何建议:)

class Maze:

  def __init__(self, rows=30, cols=40):

    self.rows = rows
    self.cols = cols
    self.keep_going = 1

    self.maze = {}
    for y in range(rows):
      for x in range(cols):
        cell = {'south' : 1, 'east' : 1, 'visited': 0}
        self.maze[(x,y)] = cell

  def generate(self, start_cell=None, stack=[])

    if start_cell is None:
      start_cell = self.maze[(self.cols-1, self.rows-1)]

    if not self.keep_going:
      return

    self.check_finished()
    neighbors = []

    # if the stack is empty, add the start cell
    if len(stack) == 0:
      stack.append(start_cell)

    # set current cell to last cell
    curr_cell = stack[-1]

    # get neighbors and shuffle 'em up a bit
    neighbors = self.get_neighbors(curr_cell)
    shuffle(neighbors)

    for neighbor in neighbors:
      if neighbor['visited'] == 0:
        neighbor['visited'] = 1
        stack.append(neighbor)
        self.knock_wall(curr_cell, neighbor)

        self.generate(start_cell, stack)

  def get_coords(self, cell):
    # grabs coords of a given cell
    coords = (-1, -1)
    for k in self.maze:
      if self.maze[k] is cell:
        coords = (k[0], k[1])
        break
    return coords

  def get_neighbors(self, cell):
    # obvious
    neighbors = []

    (x, y) = self.get_coords(cell)
    if (x, y) == (-1, -1):
      return neighbors

    north = (x, y-1)
    south = (x, y+1)
    east = (x+1, y)
    west = (x-1, y)

    if north in self.maze:
      neighbors.append(self.maze[north])
    if south in self.maze:
      neighbors.append(self.maze[south])
    if east in self.maze:
      neighbors.append(self.maze[east])
    if west in self.maze:
      neighbors.append(self.maze[west])

    return neighbors

  def knock_wall(self, cell, neighbor):
    # knocks down wall between cell and neighbor.
    xc, yc = self.get_coords(cell)
    xn, yn = self.get_coords(neighbor)

    # Which neighbor?
    if xc == xn and yc == yn + 1:
      # neighbor's above, knock out south wall of neighbor
      neighbor['south'] = 0
    elif xc == xn and yc == yn - 1:
      # neighbor's below, knock out south wall of cell
      cell['south'] = 0
    elif xc == xn + 1 and yc == yn:
      # neighbor's left, knock out east wall of neighbor
      neighbor['east'] = 0
    elif xc == xn - 1 and yc == yn:
      # neighbor's right, knock down east wall of cell
      cell['east'] = 0

  def check_finished(self):
    # Checks if we're done generating
    done = 1
    for k in self.maze:
      if self.maze[k]['visited'] == 0:
        done = 0
        break
    if done:
      self.keep_going = 0

最佳答案

[...] the rest of the levels appear to be a grid- which is making me think that the game is creating a new maze over the old.

该问题是由 Python 中的一个常见错误引起的。

参见Default Argument Values

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes

在您的情况下,类 Maze 的方法 generate 的参数具有默认参数:

class Maze:
   # [...]

   def generate(self, start_cell=None, stack=[]):
       # [...]

在方法generate中,元素被附加到stack。迷宫是在信任默认参数的情况下生成的:

self.maze_obj.generate(self.maze_obj.maze[(0,0)])

这会导致狼牙棒的第一代成功,但接下来的生成失败,因为stack包含了前一个生成过程的所有元素。

将空列表传递给generate来解决问题:

self.maze_obj.generate(self.maze_obj.maze[(0,0)])

self.maze_obj.generate(self.maze_obj.maze[(0,0)], [])

或者将默认参数更改为None:

class Maze:
    # [...]

    def generate(self, start_cell=None, stack=None):
        if stack == None:
            stack = []

关于python - Pygame 迷宫游戏无法正确创建关卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436266/

相关文章:

python - 如何使用Python脚本删除多个文件?

python - 如何从数组字典中获取所有数组值作为列表?

python - Pygame 中完全透明的窗口?

python - 第 60 行,在 make_tuple 中返回 tuple(l) TypeError : iter() returned non-iterator of type 'Vector'

python - 一种型号是否可以使用 GPU 的所有内存?

python - TensorFlow 数据集洗牌每个 Epoch

python - NLTK、NUMPY 和 SCIPY - 无法导入

python-3.x - Keras: TypeError: run() 得到了一个意外的关键字参数 'kernel_regularizer'

python - 如何在安装了 python 2.7 的 Mac 上安装 pygame?

python - 键盘中断与 python 的多处理池和映射函数