【问题标题】:pygame with multiprocessing具有多处理功能的 pygame
【发布时间】:2021-08-26 22:05:37
【问题描述】:

我正在尝试创建一个带有 2d 可绘制网格和可长时间运行的方法的 pygame 程序。我希望主游戏循环能够在方法运行时进行处理,所以我选择了threading 模块,它运行良好,但我发现multiprocessing 模块更适合 CPU 密集型程序,所以我想要换成。下面的代码是我的实际代码的示例或代表

# importing the necessary libraries

class Board:
    # class representing the actual 2d grid or board on screen

class Graph:
    # class for drawing methods that take a long time to run
    # Graph's methods call q.get() to get the Board object then 
    # make appropriate changes to it then call q.put() to put it back in the Queue

def draw_board(surface, rects):
    # surface: pygame.display
    # rects: list of pygame rectangle objects
    # draw every rectangle in rects to the display surface.

def main():
    # main game loop
    board = Board(*args)
    q = multiprocessing.Queue()
    q.put(board)
    graph = Graph(q)
    while True:
        draw_board(*args)
        for event in pygame.event.get():
            # checking some conditions and keypresses here
            elif event.type == KEYDOWN:
                if event.key == pygame.K_r:
                   t = multiprocessing.Process(target=graph.draw_sth)
                   t.start()
        pygame.display.update()
        # fps clock ticks for 60 FPS here

if __name__ == "__main__":
    main()

我使用multiprocessing.Queue 将资源从主进程传输到main() 内部产生的进程并返回。当我运行它并单击键“r”时,什么也没有发生,并且终端在首次调用main 时打印介绍行,即

pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html

这在我使用线程时不会发生,所以我认为这是由于我使用了Queue 或者我可能误解并误用了multiprocessing。对此问题的任何帮助表示赞赏。为简单起见,省略了一些代码行。

【问题讨论】:

  • 显然pygame不能很好地支持多处理或者你必须遵循指定的规则
  • @user16038533 能否提供有关上述规则的材料?
  • 这只是我在某处读到的东西,我自己并不熟悉。这可能并不完全正确。只是想我会让你知道,以防万一出现问题而你不知道为什么,你会有一些事情需要调查。
  • 您可以禁止显示“来自 pygame 的您好...”消息。 stackoverflow.com/questions/51464455/…
  • 所有与 pygame 的直接交互都必须发生在单个进程(甚至单个线程)内。除非您自己重新实现渲染内容并传递numpy 数组或其他东西,否则很难将其拆分为多个。不需要 pygame 的非渲染内容应该以某种方式运行,以使 pygame 甚至不被导入。

标签: python pygame multiprocessing


【解决方案1】:

尝试在事件循环之前调用此函数。 (我不知道这是否适用于多处理)

def continue_pygame_loop():
    pygame.mainloop(0.1)
    yield

这篇文章可以更好地解释其背后的机制:pyGame in a thread

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-28
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多