Home > Mobile >  pygame repeat sound on condition automatically
pygame repeat sound on condition automatically

Time:10-17

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!

CodePudding user response:

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)

CodePudding user response:

In general, when there is a bug in your code put points in different parts of your code:

print("point1")

lines of codes ...

print("point2")

lines of codes ...

print("point3")

lines of codes ...

print("point4")

lines of codes ...

Then, when your code crashes you can see the output and see which "point" was printed last. This way you can find out which part of your code is problematic. This approach helps you gradually find the bug in your code.

  • Related