yemi.JUMP
yemi.JUMP

Reputation: 323

Update text in real time by calling two functions Pygame

I have program that takes input from the user and displays multiple variations of the input using the Population() function. The store_fit function adds these different variations to a list then deletes them so that the list is only populated with one variation at a time.

I want to be able to get the variation from the list and use it to update my text. However, my program only updates the text after the Population function is completed. How could I run the Population function and update my text simultaneously?

code:

fit = []
...

def store_fit(fittest): # fittest is each variation from Population
    clear.fit()
    fit.append(fittest)
...

pg.init()
...
done = False

while not done:
...
    if event.key == pg.K_RETURN:
        print(text)
        target = text
        Population(1000) #1000 variations
        store_fit(value)
        # I want this to run at the same time as Population
        fittest = fit[0]
...
top_sentence = font.render(("test: " + fittest), 1, pg.Color('lightskyblue3'))
screen.blit(top_sentence, (400, 400))

Upvotes: 2

Views: 107

Answers (1)

Rabbid76
Rabbid76

Reputation: 211146

I recommend to make Population a generator function. See The Python yield keyword explained:

def Populate(text, c):
    for i in range(c):

        # compute variation
        # [...]

        yield variation

Create an iterator and use next() to retrieve the next variation in the loop, so you can print every single variation:

populate_iter = Populate(text, 1000)

final_variation = None
while not done:

    next_variation = next(populate_iter, None)
    if next_variation :
        final_variation = next_variation 

        # print current variation
        # [...]

    else:
        done = True

Edit according to the comment:

In order to keep my question simple, I didn't mention that Population, was a class [...]

Of course Populate can be a class, too. I this case you've to implement the object.__iter__(self) method. e.g.:

class Populate:
    def __init__(self, text, c):
        self.text = text
        self.c    = c

    def __iter__(self):
        for i in range(self.c):

            # compute variation
            # [...]

            yield variation

Create an iterator by iter(). e.g.:

populate_iter = iter(Populate(text, 1000))

final_variation = None
while not done:

    next_variation = next(populate_iter, None)
    if next_variation :
        final_variation = next_variation 

        # print current variation
        # [...]

    else:
        done = True

Upvotes: 2

Related Questions