pygame类结构

2024-05-19 08:58:55 发布

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

我的目标是制作一个模块,它将在pygame画布上生成一个网格,并允许您通过它们的x和y坐标高亮显示框。在

下面是一个简单的用法示例。在

from grid import Grid

g = Grid(100, 100, 10) # width and height in cells, cell width in pixels
g.highlightBox(2, 2, (0, 255, 0)) # cell x and y, rgb color tuple
g.clearGrid()

这是我目前掌握的密码。问题是,我需要一个事件循环来保持窗口打开并使关闭按钮起作用,但是我还需要允许其他函数绘制到屏幕上。在

^{pr2}$

当我运行第一个示例时,代码将被困在循环中,直到循环完成(按下exit按钮),才允许我运行highlightBox函数。在


Tags: 模块and函数in网格示例用法目标
3条回答

首先,我不会将游戏循环放在初始化函数中;请为它找到其他位置。要解决这个问题,只需将要执行的代码放在游戏循环中处理事件的代码旁边:

running = True
while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = False

    # Print your screen in here
    # Also do any other stuff that you consider appropriate

我认为您需要的是断开网格类与它的显示的连接。你应该让它生成表面,然后由主游戏循环打印到屏幕表面。例如,您的init、highlight_cell和clear_grid方法可以返回曲面,或者创建一个get_surface方法,该方法将在每个游戏循环中调用一次

这将提供更大的灵活性

我得到了一个带有multiprocessing库和管道的工作版本。这似乎有点不和谐,但它将为这个项目工作。在

import pygame
import sys
from multiprocessing import Process, Pipe

class Grid:
    colors = {"blue":(0, 0, 255), "red":(255, 0, 0), "green":(0, 255, 0), "black":(0, 0, 0), "white":(255, 255, 255)}

    def __init__(self, width, height, cellSize, borderWidth=1):
        self.cellSize = cellSize
        self.borderWidth = borderWidth
        self.width = width * (cellSize + borderWidth)
        self.height = height * (cellSize + borderWidth)

        #pygame.draw.rect(self.screen, todo[1], (todo[2], todo[3], todo[4], todo[5]), 0)
        self.parent_conn, self.child_conn = Pipe()
        self.p = Process(target=self.mainLoop, args=(self.child_conn, self.width, self.height,))
        self.p.start()

    def close():
        self.p.join()

    def clearGrid(self):
        pass

    def highlightBox(self, x, y, color):
        xx = x * (self.cellSize + self.borderWidth)
        yy = y * (self.cellSize + self.borderWidth)
        self.parent_conn.send(["box", color, xx, yy, self.cellSize, self.cellSize])

    def mainLoop(self, conn, width, height):
        #make window
        screen = pygame.display.set_mode((self.width, self.height))

        running = True
        while running:
            # is there data to read
            if conn.poll():
                #read all data
                todo = conn.recv()
                print("Recived " + str(todo))

            #do the drawing
            if todo[0] == "box":
                print("drawing box")
                pygame.draw.rect(screen, todo[1], (todo[2], todo[3], todo[4], todo[5]), 0) #color, x, y, width, height
                todo = ["none"]

            #draw to screen
            pygame.display.flip()

            #get events
            event = pygame.event.poll()
            if event.type == pygame.QUIT:
                running = False

相关问题 更多 >

    热门问题