我正在制作游戏的另一个问题,我希望每次新的小行星由spawner类创建时,Asteroids精灵都是随机的,但我一直得到这个错误'非默认参数遵循默认值参数',我对于该做什么感到非常难过。实际的随机图像存储在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)
答案 0 :(得分: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)