2012-01-04 130 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()