我通过在屏幕上画一个矩形并不断地改变它来在我的游戏中创建了一个日子和一个周期。但是,我显然想为游戏添加一些照明。有没有办法使用pygame将矩形的特定部分的alpha设置为0?或者是否可能采用另一种方式来处理整个照明事件?
这就是我日光周期的工作方式(非常糟糕,夜晚更长,但仅限于测试):
#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 :(得分: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的位置之类的东西。