2

我在我的游戏中创建了一个日夜循环,方法是在屏幕上绘制一个矩形并让它的 alpha 不断变化。但是,我显然想为游戏添加一些光照。有没有办法使用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))
4

1 回答 1

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。您可以通过重叠瓷砖来进一步改进此模型以获得更精确的照明和渐变,并通过创建一个瓷砖类来继承 pygame.Surface,这将管理诸如瓷砖位置之类的事情。

于 2014-01-05T22:29:01.977 回答