【问题标题】:How to avoid global screen variable?如何避免全局屏幕变量?
【发布时间】:2012-02-02 00:04:19
【问题描述】:

这个问题是在 Pygame 的上下文中提出的,但我想知道任何类型的图形编程的好解决方案。

因此,每当您编写图形程序时,通常都会有一个屏幕变量来保存正在显示的屏幕的数据。我见过的所有示例都将此变量设为全局变量,以便所有其他对象也可以轻松访问它,例如下面的简单示例。

import pygame

background_colour = (255,255,255)
(width, height) = (300, 200)

class Particle:
    def __init__(self, (x, y), size):
        self.x = x
        self.y = y
        self.size = size
        self.colour = (0, 0, 255)
        self.thickness = 1

    def display(self):
        pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness)

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Tutorial 2')
screen.fill(background_colour)

my_first_particle = Particle((150, 50), 15)
my_first_particle.display()

pygame.display.flip()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

我的问题是是否有更好的方法可以使屏幕不是全局的。谢谢!

【问题讨论】:

    标签: screen global pygame


    【解决方案1】:

    display.get_surface()

    class Particle:
        def __init__(self, (x, y), size):
            self.screen = pygame.display.get_surface()
    

    【讨论】:

      【解决方案2】:

      这个 global 有什么具体问题吗? 无论如何,您可以将显示表面添加为对象的 init() 函数的参数,然后渲染到该参数。

      也许这只是我自己使用 pygame 的方式,但我主要使用精灵,并通过渲染器的 clear() 和 draw() 函数来渲染它们。这些函数需要一个表面(可能是屏幕)变量,因此我的屏幕不是全局的(如果我没记错的话)。

      【讨论】:

        猜你喜欢
        • 2012-12-19
        • 2016-03-19
        • 2015-12-26
        • 1970-01-01
        • 2010-12-22
        • 2011-04-10
        • 2011-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多