Why is my PyGame application not running at all?

橙三吉。 提交于 2021-01-29 21:08:18

问题


I have a simple Pygame program:

#!/usr/bin/env python

import pygame
from pygame.locals import *

pygame.init()

win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")

But every time I try to run it, I get this:

pygame 2.0.0 (SDL 2.0.12, python 3.8.3)
Hello from the pygame community. https://www.pygame.org/contribute.html

And then nothing happens. Why I can't run this program?


回答1:


Your application works well. However, you haven't implemented an application loop:

#!/usr/bin/env python

import pygame
from pygame.locals import *

pygame.init()

win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")
clock = pygame.time.Clock()

run = True
while run:
    clock.tick(60)
    
    # handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # update game objects
    # [...]

    # clear display
    win.fill((0, 0, 0))

    # draw game objects
    # [...]

    # update display
    pygame.display.flip()

pygame.quit()

The typical PyGame application loop has to:

  • handle the events by either pygame.event.pump() or pygame.event.get().
  • update the game states and positions of objects dependent on the input events and time (respectively frames)
  • clear the entire display or draw the background
  • draw the entire scene (blit all the objects)
  • update the display by either pygame.display.update() or pygame.display.flip()

repl.it/@Rabbid76/PyGame-MinimalApplicationLoop See also Event and application loop



来源:https://stackoverflow.com/questions/65264616/why-is-my-pygame-application-not-running-at-all

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