2012-01-04 92 views
3

这个问题正在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 

我的问题是,是否有更好的方式来做到这一点,使屏幕不是全球性的。谢谢!

回答

1

有没有这个全球性的具体问题? 无论如何,您可以添加显示表面作为对象的init()函数的参数,并呈现给此参数。

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

2

display.get_surface()

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