2013-07-20 15 views
2

我通過在屏幕上繪製矩形並不斷變化α來創建我的遊戲中的一天和一個週期。不過,我顯然希望爲遊戲添加一些燈光。有沒有一種方法可以使用pygame將矩形的特定部分的alpha設置爲0?或者,也許還有另外一種關於整個照明事物的方式?添加照明Pygame

這是我的白天週期的運作(這是很糟糕的,黑夜較長,但它只是用於測試):

#Setting up lighting 
game_alpha = 4 #Keeping it simple for now 
game_time = 15300 
time_increment = -1 
alpha_increment = 1 

#Main Game Loop: 
if float(game_time)%game_alpha == 0: 
     game_alpha += alpha_increment 
     print "Game Alpha: ",game_alpha 
     print "Game Time: ", game_time 
if game_time < 0: 
     time_increment = 1 
     alpha_increment = -1 
elif game_time >= 15300: 
     time_increment = -1 
     alpha_increment = 1 

    game_shadow = pygame.Surface((640, 640)) 
    game_shadow.fill(pygame.Color(0, 0, 0)) 
    game_shadow.set_alpha(game_alpha) 
    game_shadow.convert_alpha() 
    screen.blit(game_shadow, (0, 0)) 
+0

你可以在它上面點亮一下嗎? –

+0

你可以設置每個像素的alpha值,但我敢打賭它會比pyOpenGL慢。但也許夠快。 – ninMonkey

+0

你可以將屏幕分割成不同的矩形,然後用不同的alpha值對它們進行blit處理。 – alexpinho98

回答

1

雖然可能有分配不同的alpha通道,以不同的方式像素,這將是困難的,如果你每個像素做它會大大減慢你的程序(如果你真的決心這樣做,我能找到的最接近的東西是pygame.Surface.set_at)。看起來你可能是最好的把屏幕分解成更小的表面。您甚至可以通過重疊來實現簡單的漸變。通過這種方式,您可以設置各個區域的亮度,以獲得兩種效果。下面是一個用於實現你想要的瓷磚網格的基本示例:

tiles = [] 
column = [] 
for row in range(10): 
    for column in range(10):   #These dimensions mean that the screen is broken up into a grid of ten by ten smaller tiles for lighting. 
     tile = pygame.Surface((64, 64)) 
     tile.fill(pygame.Color(0, 0, 0)) 
     tile.set_alpha(game_alpha) 
     tile.convert_alpha() 
     column.append(tile) 
    tiles.append(column)    #this now gives you a matrix of surfaces to set alphas to 

def draw():       #this will draw the matrix on the screen to make a grid of tiles 
    x = 0 
    y = 0 
    for column in tiles: 
     for tile in column: 
      screen.blit(tile,(x,y)) 
      x += 64 
     y += 64 

def set_all(alpha): 
    for column in tiles: 
     for tile in column: 
      tile.set_alpha(alpha) 

def set_tile(x,y,alpha):  #the x and y args refer to the location on the matrix, not on the screen. So the tile one to the right and one down from the topleft corner, with the topleft coordinates of (64,64), would be sent as 1, 1 
    Xindex = 0 
    Yindex = 0 
    for column in tiles: 
     for tile in column: 
      if Xindex == x and Yindex == y: 
       tile.set_alpha(alpha)   #when we find the correct tile in the coordinates, we set its alpha and end the function 
       return 
      x += 1 
     y += 1 

這應該會給你你想要的。我還包括一些功能來訪問該瓷磚組。 Set_all會將整個屏幕的alpha值改變一定量,set_tile將只改變一個tile的alpha值,draw將繪製所有的tile。您可以通過重疊拼貼來獲得更精確的照明和漸變,並通過使tile類繼承pygame.Surface來更好地改善此模型,這將管理像tile的位置等事情。