1

我正在制作的游戏有另一个问题,我希望每次我由 spawner 类创建新的小行星时,小行星精灵都会随机化,但我不断收到此错误“非默认参数遵循默认参数”,我非常困惑该怎么做,实际的随机图像存储在生成器中,然后导入到 Asteroid 类。任何帮助将不胜感激,图像列表是一个全局变量。

images = [games.load_image("asteroid_small.bmp"),
      games.load_image("asteroid_med.bmp"),
      games.load_image("asteroid_big.bmp")]

 def check_drop(self):
    """ Decrease countdown or drop asteroid and reset countdown. """
    if self.time_til_drop > 0:
        self.time_til_drop -= 0.7
    else:
        asteroid_size = random.choice(images)
        new_asteroid = Asteroid(x = self.x,image = asteroid_size)
        games.screen.add(new_asteroid)

然后这是小行星类的一部分,随机图像将存储在其中

def __init__(self, x, y = 10,image):
    """ Initialize a asteroid object. """
    super(Asteroid, self).__init__(image = image,
                                x = x, y = y,
                                dy = Asteroid.speed)
4

1 回答 1

1

您的问题不在于您如何实例化小行星,而在于您如何定义它:

def __init__(self, x, y = 10,image):

如果你看,image是最后一个,在 y 之后,它有一个默认参数。在 Python 中,你不能做这样的事情。你有两个选择:

def __init__(self, x, y = 10, image = None):
    # default the argument to some sentinel value
    # Test for sentinel and the reassign if not matched.
    image = image if image else random.choice(images)

或者

def __init__(self, x, image, y = 10):
    # re-order your arguments.
    # Also note that image, x, y might be a better order 
    # (@see comment by Micael0x2a)
于 2013-10-08T14:54:46.313 回答