Python游戏总是崩溃或卡住| pygame

标签 python pygame

我正在使用 pygame 模块制作一个不错的游戏,基本上我想做两件事:

  1. 无限循环地运行游戏,看看用户是否想关闭游戏,如果他想关闭游戏,就给他弹出一个MessageBox。

  2. 在第二个函数中,我想添加游戏的所有功能并在屏幕上绘图。

我的问题是,当我尝试使用 Thread 运行它们时,游戏会卡住并且没有响应。

这是我的电脑的问题吗?意味着它太弱而无法运行游戏?
还是我的代码有问题导致游戏无法正常运行?

代码:

import pygame
import ctypes
from threading import Thread

class Game:
    def __init__(self):
        self.init = pygame.init()
        self.screen = pygame.display.set_mode((800, 500))
        self.allProcess()

    def runGame(self):
        self.running = True
        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    ctypes.windll.user32.MessageBoxW(0, 'Thank you for Playing!', 'Thank You', 0)
                    self.running = False

    def items(self):
        self.screen.fill((255, 255, 255))
        pygame.draw.circle(self.screen, (0, 0, 255), (250, 250), 75)

    def allProcess(self):
        Thread(target=self.runGame).start()
        Thread(target=self.items).start()


if __name__ == '__main__':
    ins = Game()

最佳答案

Pygame 是基于 SDL2 构建的,它有一些关于在哪些线程中可以调用某些函数的规则。例如,对于事件模块中的函数,( "you can only call this function in the thread that set the video mode." )。

除非绝对必要,否则您几乎应该始终避免使用线程!它们使您的程序具有不确定性,更难调试、更难测试、更难维护,而且通常速度较慢(除非您有效地使用它们)。在您的程序中,没有理由使用线程。就您而言,它们是不必要的。你应该这样做:

import pygame
import ctypes

class Game:
    def __init__(self):
        self.init = pygame.init()
        self.screen = pygame.display.set_mode((800, 500))
        self.runGame()

    def runGame(self):
        self.running = True
        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    ctypes.windll.user32.MessageBoxW(0, 'Thank you for Playing!', 'Thank You', 0)
                    self.running = False

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

            pygame.display.flip()  # Don't forget to call this to update the screen!



if __name__ == '__main__':
    ins = Game()

代码更少,具有确定性,并且很可能更快并且使用更少的内存。

关于Python游戏总是崩溃或卡住| pygame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60016180/

相关文章:

python - paramiko 结合 stdout 和 stderr

python - NumPy 的 : convert labels into indexes

python - 如何将包含键和值对的 dtype 对象列转换为新的数据框

python - 如何在 Pygame 中更改图像的颜色而不改变其透明度?

python - 我的 Pygame 贪吃蛇游戏陷入了无限循环?

python - pygame 未关闭并返回控制台(python)

python - 如何在没有相应值的列表中添加 None ?

python - 如何对 groupby 对象中包含的多个列表进行计数,并将该组列表中的每个值的计数相加

python - 提高 Sprite 渲染性能?

python - Pygame图像运动异常