Python 3.6 pygame崩溃

2024-04-20 08:03:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用一个非常简单的代码,用python3.6.1创建一个矩形。我不确定我使用的代码是不是每次我使用它时都会导致程序崩溃,或者是否有人能给我提供关于我的pygame模块、cmd和我使用的代码之间可能发生的事情的建议。screenshot of windows


Tags: 模块代码程序cmd事情pygame建议矩形
3条回答

当我运行您的代码时,窗口加载并显示矩形,但是,我认为您的问题涉及尝试退出程序。为此,您需要有一个事件循环,当用户退出游戏循环时,它将终止游戏:

import pygame

pygame.init()

isrunning = True

window = pygame.display.set_mode((500, 400))

while isrunning:
   for event in pygame.event.get():
            if event.type == pygame.QUIT:
                isrunning = False
    pygame.draw.rect(window, (255, 0, 0), (0, 0, 50, 30)) #here, access the rect method

    pygame.display.update()

你需要用背景色填充屏幕。如果想要黑色,仍然需要手动将背景色设置为黑色。你知道吗

import pygame

pygame.init()
window = pygame.display.set_mode((500, 400))

while True:
    window.fill(0, 0, 0)
    pygame.draw.rect(window, (255, 0, 0), (0, 0, 50, 30))

    pygame.display.flip()

如果你增加一个帧速率,再加上一个事件循环,效果会更好。你知道吗

import pygame

pygame.init()
window = pygame.display.set_mode((500, 400))
clock = pygame.time.Clock()

while True:
    window.fill(0, 0, 0)
    pygame.event.pump()  # use pump if you’re not planning to catch any event

    pygame.draw.rect(window, (255, 0, 0), (0, 0, 50, 30))
    pygame.display.flip()
    clock.tick(50)  # add the frame rate, should always be > 30

作为一般提示,如果不将任何矩形参数传递给update(),请使用flip()

import pygame
pygame.init()
window = pygame.display.set_mode((500, 400))
while True:
    pygame.draw.rect(window, (255,0,0),
        (0, 0, 50, 30))
    pygame.display.update()

这是密码

相关问题 更多 >