python - pygame类结构

标签 python refactoring pygame

我的目标是制作一个模块,在 pygame Canvas 上制作网格,并允许您通过 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()

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

import pygame
import sys

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)
        self.screen = pygame.display.set_mode((self.width, self.height))

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

    def clearGrid(self):
        pass

    def highlightBox(self, x, y, color):
        xx = x * (self.cellSize + self.borderWidth)
        yy = y * (self.cellSize + self.borderWidth)
        pygame.draw.rect(self.screen, color, (xx, yy, self.cellSize, self.cellSize), 0)

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

最佳答案

对于初学者来说,我不会将游戏循环放在初始化函数中;为它寻找其他地方。要解决此问题,只需将要执行的代码放在游戏循环中,位于处理事件的代码旁边:

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

关于python - pygame类结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8607513/

相关文章:

.net - 为什么重命名文件有时会重构类名,有时不会?

python - 如何在一个函数中休眠而不休眠整个程序

python - 如何用pygame播放视频?

python - 无法在 Linux 上安装 Python 包

python - 如何处理与坐标的碰撞? (在 python 中)

java - Eclipse方法调用重构

parallel-processing - 为并行执行重写顺序代码

python - 如何为 pygame.transform.rotate() 设置枢轴点(旋转中心)?

python - 在不平衡数据集上计算 ROC AUC 时应使用哪种平均值?

python - lxml Python包将版权符号更改为HTML实体