How to make a sprites speed increase after a certain score is achieved in Pygame

StackOverflow https://stackoverflow.com/questions/19498987

  •  01-07-2022
  •  | 
  •  

سؤال

In my game the player has the avoid asteroids, and when the asteroid hits the bottom of the screen it's destroyed and the score increases by ten, but I want the asteroids speed to increase after the player reaches a certain score but every time I do this with the code I'm using the asteroid just glitches and the score begins to increase rapidly, could someone help me please?

The Asteroid class, the code is in the update method.

class Asteroid(games.Sprite):
global lives
global score
global inventory
"""
A asteroid which falls through space.
"""

image = games.load_image("asteroid_med.bmp")
speed = 2

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


def update(self):
    """ Check if bottom edge has reached screen bottom. """
    if self.bottom>games.screen.height:
        self.destroy()
        score.value+=10

    if score.value == 100:
        Asteroid.speed+= 1

The score variable if needed

score = games.Text(value = 0, size = 25, color = color.green,
               top = 5, right = games.screen.width - 10)
games.screen.add(score)
هل كانت مفيدة؟

المحلول

if score.value == 100:
    Asteroid.speed += 1

For every frame that the score is 100, you are going to add 1 to the speed of the asteroids. This means that if you're game is running at 60 fps, after 1 second your asteroids will have added 60 to their speed. Am I correct in assuming that this is when things begin to 'glitch?'

All you should have to do to correct this is add speed only once the player's score reaches 100, and ensure it happens in a reactive manner:

if self.bottom > games.screen.height:
    self.destroy()
    score.value += 10

    # Check if the score has reached 100, and increase speeds as necessary
    if score.value == 100:
        Asteroid.speed += 1

It's unclear from your code whether Asteroid.speed will set the speed for all asteroids. If not, you'll have to work out a way of broadcasting the fact that speed must increase to all other active asteroids.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top