Pygame无法正常运行

时间:2020-05-08 12:06:30

标签: python pygame

我无法使用pygame来运行任何东西,就像我每次运行任何东西一样,即使是显示圆圈的非常简单的程序,该程序也会产生黑屏,什么都不做。

我正在谈论的黑屏是这个black screen

这到底是什么?并有解决方法吗?

编辑: 我忘了提到程序似乎运行良好,并且没有任何错误。

编辑#2:这是我非常简单的程序:

import pygame
pygame.init()

screen = pygame.display.set_mode([500, 500])

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

screen.fill((255, 255, 255))

SCREEN_TITLE = 'Chess Game'
pygame.display.set_caption(SCREEN_TITLE)

pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)

pygame.display.flip()

pygame.quit()

编辑#3:python控制台上显示的图片 after I press the exit button

before I press the exit button

1 个答案:

答案 0 :(得分:1)

您可能会遇到两个独立的问题:

问题1:在MacOS上安装Pygame

在MacOS上运行PyGame时,存在一些已记录的问题。请检查您是否已在计算机中正确安装并设置了pygame。 This post可能有用。

问题2:代码不正确

除此之外,您的代码还有几个问题。您的运行循环不显示任何内容,因为它被卡在处理事件之内,仅此而已。因此,您会看到黑屏。请注意,执行结束后,您正在打印屏幕和圆圈。

在使用pygame时,我建议区分:

  • 初始化:设置pygamescreen。呈现任何静态内容。
  • 运行循环:处理事件并呈现任何动态内容。
  • 结束:显示任何结束动画/对象并完成pygame

我建议进行以下修改:

  • 首先渲染屏幕
  • 在运行循环中,只需处理事件并渲染圆
  • 我添加了调试消息。您可以通过运行python mygame.pypython -O mygame.py来启用和禁用它们。请注意,运行循环中的print语句将打印很多消息。

代码如下:

#!/usr/bin/python

# -*- coding: utf-8 -*-

# For better print formatting
from __future__ import print_function

# Imports
import pygame


#
# MAIN FUNCTION
#
def main():
    # Setup display and static content
    if __debug__:
        print("Initialising pygame")
    pygame.init()
    SCREEN_TITLE = 'Chess Game'
    pygame.display.set_caption(SCREEN_TITLE)
    screen = pygame.display.set_mode([500, 500])
    screen.fill((255, 255, 255))
    pygame.display.flip()    

    # Running loop
    running = True
    while running:
        if __debug__:
            print("New iteration")
        # Process events
        if __debug__:
            print("- Processing events...")
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # Display any dynamic content
        if __debug__:
            print("- Rendering dynamic content...")
        pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)

        # Update display
        if __debug__:
            print("- Updating display...")
        pygame.display.flip()

    # End
    if __debug__:
        print("End")
    pygame.quit()


#
# ENTRY POINT
#
if __name__ == "__main__":
    main()

调试输出:

$ python mygame.py 
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Initialising pygame
New iteration
- Processing events...
- Rendering dynamic content...
- Updating display...
.
.
.
New iteration
- Processing events...
- Rendering dynamic content...
- Updating display...
End

显示:

Game display