Update text in real time by calling two functions Pygame

假如想象 提交于 2020-01-15 09:04:29

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/58046380/update-text-in-real-time-by-calling-two-functions-pygame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!