user14341820
user14341820

Reputation:

How to change an integer every certain amount of time

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).

Upvotes: 1

Views: 72

Answers (2)

tominekan
tominekan

Reputation: 313

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

Upvotes: 0

Locke
Locke

Reputation: 8964

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?

Upvotes: 1

Related Questions