python - 如何创建两个独立的 pygame 显示?如果我不能,我如何创建 pygame 的两个实例?

标签 python python-3.x pygame

我想创建两个单独的 pygame 显示。我知道用 pygame 的单个实例不可能做到这一点。我想知道如何/是否可以实现以下任何解决方案:

  1. 创建一个单独的模块来运行使用单独显示的功能。这是否会使用我的主代码中的一个单独的 pygame 实例,从而能够运行?
  2. 使用子 shell 使用一些特殊参数从自身内部运行脚本,解析 sys.argv,然后在第二个实例中运行该函数。如何确保跨平台兼容性?
  3. 还有别的事吗?

我不关心程序的结果是多么低效、丑陋等等。我只是想让这个工作成功。

重要的是,主代码必须与相关代码进行通信(即更改下面属于 extraDisplayManager 的一些变量),但我计划使用 pickle 保存到文件并以这种方式进行通信。不过,我已经对相关部分进行了多线程处理,因此缺乏同步性并不重要。

我的代码相当长且复杂,所以我不会在这里发布它,但相关部分的要点是:

def mainCode(*someargs):
    d = pygame.display.set_mode(dimensions)
    if relevantArg:
        extraDisplayManager = RelevantClass(*someotherargs)
        threading.Thread(target=extraDisplayManager.relevantFunction,
                         daemon=True).start()


...

class RelevantClass:
    def relevantFunction(self, *someotherargs):
        self.d = pygame.display.set_mode(dimensions)
        while True:
            updateDisplay(someargs) # This is part of my main code, but it
            # is standalone, so I could copy it to a new module

如果您能回答我的一些问题或向我展示一些相关文档,我将不胜感激。

最佳答案

如果您确实(确实)需要两个显示器,您可以使用 python 的 multiprocessing生成进程并使用 Queue 的模块在两个进程之间传递数据。

这是我一起编写的一个示例:

import pygame
import pygame.freetype
import random
import multiprocessing as mp

# a simple class that renders a button
# if you press it, it calls a callback function
class Button(pygame.sprite.Sprite):
    def __init__(self, callback, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((200, 200))
        self.image.set_colorkey((1,2,3))
        self.image.fill((1,2,3))
        pygame.draw.circle(self.image, pygame.Color('red'), (100, 100), 50)
        self.rect = self.image.get_rect(center=(300, 240))
        self.callback = callback

    def update(self, events, dt):
        for e in events:
            if e.type == pygame.MOUSEBUTTONDOWN:
                if (pygame.Vector2(e.pos) - pygame.Vector2(self.rect.center)).length() <= 50:
                    pygame.draw.circle(self.image, pygame.Color('darkred'), (100, 100), 50)
                    self.callback()
            if e.type == pygame.MOUSEBUTTONUP:
                    pygame.draw.circle(self.image, pygame.Color('red'), (100, 100), 50)

# a simple class that display a text for 1 second anywhere
class Message(pygame.sprite.Sprite):
    def __init__(self, screen_rect, text, font, *grps):
        super().__init__(*grps)
        self.image = pygame.Surface((300, 100))
        self.image.set_colorkey((1,2,3))
        self.image.fill((1,2,3))
        self.rect = self.image.get_rect(center=(random.randint(0, screen_rect.width), 
                                                random.randint(0, screen_rect.height)))
        font.render_to(self.image, (5, 5), text)
        self.timeout = 1000
        self.rect.clamp_ip(screen_rect)

    def update(self, events, dt):
        if self.timeout > 0:
            self.timeout = max(self.timeout - dt, 0)
        else:
            self.kill()

# Since we start multiple processes, let's create a mainloop function
# that can be used by all processes. We pass a logic_init_func-function
# that can do some initialisation and returns a callback function itself.
# That callback function is called before all the events are handled.
def mainloop(logic_init_func, q):
    import pygame
    import pygame.freetype
    pygame.init()
    screen = pygame.display.set_mode((600, 480))
    screen_rect = screen.get_rect()
    clock = pygame.time.Clock()
    dt = 0
    sprites_grp = pygame.sprite.Group()

    callback = logic_init_func(screen, sprites_grp, q)

    while True:
        events = pygame.event.get()
        callback(events)

        for e in events:
            if e.type == pygame.QUIT:
                return

        sprites_grp.update(events, dt)
        screen.fill((80, 80, 80))
        sprites_grp.draw(screen)
        pygame.display.flip()
        dt = clock.tick(60)

# The main game function is returned by this function.
# We need a reference to the slave process so we can terminate it when
# we want to exit the game.
def game(slave):
    def game_func(screen, sprites_grp, q):

        # This initializes the game.
        # A bunch of words, and one of it is randomly choosen to be
        # put into the queue once the button is pressed
        words = ('Ouch!', 'Hey!', 'NOT AGAIN!', 'that hurts...', 'STOP IT')

        def trigger():
            q.put_nowait(random.choice(words))

        Button(trigger, sprites_grp)

        def callback(events):
            # in the mainloop, we check for the QUIT event
            # and kill the slave process if we want to exit
            for e in events:
                if e.type == pygame.QUIT:
                    slave.terminate()
                    slave.join()

        return callback

    return game_func

def second_display(screen, sprites_grp, q):

    # we create font before the mainloop
    font = pygame.freetype.SysFont(None, 48)

    def callback(events):
        try:
            # if there's a message in the queue, we display it
            word = q.get_nowait()
            Message(screen.get_rect(), word, font, sprites_grp)
        except:
            pass

    return callback

def main():
    # we use the spawn method to create the other process
    # so it will use the same method on each OS.
    # Otherwise, fork will be used on Linux instead of spawn
    mp.set_start_method('spawn')
    q = mp.Queue()

    slave = mp.Process(target=mainloop, args=(second_display, q))
    slave.start()

    mainloop(game(slave), q)


if __name__ == '__main__':
    main()

enter image description here

当然这只是一个简单的例子;你可能需要更多的错误处理,停止疯狂的嵌套函数等等。此外,还有其他方法可以做到 IPC在Python中。

最后但并非最不重要的一点是,考虑一下您是否真的需要两个 pygame 显示,因为多重处理会增加大量的复杂性。我已经回答了一些有关 pygame 的问题,并且在询问有关 pygame 的线程/多重处理时,几乎总是 OP 提出 XY 问题。

关于python - 如何创建两个独立的 pygame 显示?如果我不能,我如何创建 pygame 的两个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56334330/

相关文章:

python - 右对齐python

python - 动态向python中的对象添加 "real"方法

python - Nose:基于 TestCase 的类的生成器

python - 我如何获得opencv中显示的图像坐标

python - 如何用pygame播放视频?

python - 如何在pycharm中从中心旋转一个对象?

python - 设置python环境-安装后找不到模块

python - 如何从 python 请求响应/异常对象访问对等方的证书链?

python - 值错误 : Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe

python - opencv-tkinter 集成中的闪烁视频