Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

python - Why is my pygame application loop not working properly?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your basic misunderstanding, is that you try to draw the background at the position of an object, then you move the object and blit it finally on its new position. That all is not necessary.
In common the entire scene is drawn in each frame in the main application loop. It is sufficient to draw the background to the entire window and blit each object on top of it. Note, you do not see the changes of the window surface immediately. The changes become visible, when the display is updated by pygame.display.update() or pygame.display.flip():

The main application loop has to:

e.g.:

while 1:

    # handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    # update objects (depends on input events and frames)
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        objects[0].move_left()    
    if keys[pygame.K_RIGHT]:
        objects[0].move_right()
    if keys[pygame.K_UP]:
        objects[0].move_up()
    if keys[pygame.K_DOWN]:
        objects[0].move_down()

    for num in range(num_objects - 1):
        objects[num + 1].rand_move()

    # draw background
    screen.blit(background, (0, 0))

    # draw scene
    for o in objects:
        screen.blit(o.image, o.pos)

    # update dispaly
    pygame.display.update()
    pygame.time.delay(100)

Minimal example: repl.it/@Rabbid76/PyGame-MinimalApplicationLoop


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...