pythonpython-3.xpygamemixer

pygame repeat sound on condition automatically


please excuse my n00bness but I am having some trouble with pygame that I could really use some help with!

I am looking to make a sort-of solar system simulation where the passing of each planet from a predefined set of coordinates will produce a simple note (one second long, no more) once per orbit

so far I have the visuals down exactly how I want them but I cannot get the sound to repeat. It only plays once at the beginning and never repeats even though the conditions are met again and again.

I am using an if condition and have tried adding a while condition on top of it to make it repeat but if I do that it makes it crash.

here is my code

planet1_sound = mixer.Sound('f-major.wav')
class PlanetMove:
    def planetX(planet_orbit, distance, X):
        x = math.cos(planet_orbit) * distance + X
        return x

    def planetY(planet_orbit, distance, Y):
        y = -math.sin(planet_orbit) * distance + Y
        return y

    def tone(sound):
        sound.play(0)
X1 = PlanetMove.planetX(planet1_orbit, distance1, defaultX)
Y1 = PlanetMove.planetY(planet1_orbit, distance1, defaultY)
if X1 == 715 and Y1 == 360:
    PlanetMove.tone(planet1_sound)

and here is the entire script

it's driving me crazy, any insight would be highly appreciated, thank you!


Solution

  • X1 and Y1 are floating point numbers. The coordinates are (715, 360) at the beginning, but they will never be exact (715, 360) again. You cannot use the == operator to test whether floating point numbers are nearly equal.

    You can try to round the coordinates for the collision test to integral numbers:

    if round(X1) == 715 and round(Y1) == 360:
        PlanetMove.tone(planet1_sound)
    

    However, this will probably not be sufficient. You have to tested whether the planet is in a certain area. Use pygame.Rect.collidepoint for the collision test. e.g.:

    if pygame.Rect(710, 355, 10, 10).collidepoint(X1, Y1):
        PlanetMove.tone(planet1_sound)