1

I am making a pygame code where a helicopter sprite changes its images 3 times to make it look like the propellers are moving. I came up with something like this:

if heli == 1:
    self.surf = pygame.image.load("Heli_1.png")
if heli == 2:
    self.surf = pygame.image.load("Heli_2.png")
if heli == 3:
    self.surf = pygame.image.load("Heli_3.png")

I need to make it so that every say... .05 seconds the variable heli changes from 1 to 2, 2 to 3, and then 3 to 1. I tried looking into the time module, but I couldn't find any answers. Update: I have tried using time.sleep, but it will only display the image as the last one called (Heli_3).

2 Answers2

1

I think what you want is the modulo operator (%). You can think of it as getting the remainder when dividing two numbers (With some technicalities). Here is a quick example showing how it could be used. If you want to, time could even be replaced with game ticks passed.

import time

class Animation:
    def __init__(self, imgs, delay):
        self.imgs = imgs
        self.delay = delay

    def __call__(self, time):
        # Get index to use
        frame = int(time / self.delay) % len(self.imgs)
        return self.imgs[frame];

helicopter = Animation(helicopter_imgs, 0.5);

while True:
    img_to_draw = helicopter(time.time());

You can find more information here: What is the result of % in Python?

Locke
  • 7,626
  • 2
  • 21
  • 41
0

An answer to the problem would be to use the time module:

import time
heli = 1
while True:
    self.surf = pygame.image.load(f"Heli_{heli}.png")
    pygame.time.wait(500)
    if heli == 3:
        heli = 0
    heli += 1
tominekan
  • 303
  • 2
  • 10
  • I have some questions. You wrote: `pygame.image.load(f"Heli_{heli}.png")` Why is there an f before it, and why is there `{heli}`? –  Oct 05 '20 at 14:05
  • 1
    f strings are used to make things easier. If `heli == 1` then `f"Heli_{heli}.png"` is equal to "Heli_1.png" For more information, read [this site](https://realpython.com/python-f-strings/) – tominekan Oct 05 '20 at 15:16