user2855453
user2855453

Reputation: 11

How to randomize sprite image?

I'm having another problem with the game I'm making, I want the Asteroids sprite to be randomized every time I new asteroid is created by the spawner class, but I keep getting this error 'non-default argument follows default argument', and I'm pretty much stumped on what to do, The actual randomized image is stored inside the spawner and is then imported to the Asteroid class. Any help would be greatly appreciated, the images list is a global variable.

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)

And then this is the part of the asteroid class that the randomized image will be stored in

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

Upvotes: 1

Views: 68

Answers (1)

cwallenpoole
cwallenpoole

Reputation: 82028

Your problem isn't with how you instantiate the asteroid, it is how you define it:

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

If you look, image is last, after y, which has a default argument. In Python you cannot do such things. You have two options:

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)

or

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)

Upvotes: 1

Related Questions