pygame - 如何用另一个替换图像

时间:2016-08-11 19:51:23

标签: python python-3.x pygame

我有这样的代码:

width = 100
height = 50
gameDisplay.blit(button, (width, height))
pygame.display.update()
while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            # replace the button's image with another

是否有任何功能或某些东西可以让我用另一个替换图像?

2 个答案:

答案 0 :(得分:1)

你不能'替换'你画的任何东西。你所做的是你在现有的图像上绘制新图像。通常,您清除屏幕并在每个循环中重绘图像。这是伪代码,说明典型的游戏循环是什么样的。我将 screen 用作变量名而不是 gameDisplay ,因为 gameDisplay 违反了PEP-8命名约定。

while True:
    handle_time()  # Make sure your programs run at constant FPS.
    handle_events()  # Handle user interactions.
    handle_game_logic()  # Use the time and interactions to update game objects and such.

    screen.fill(background_color)  # Clear the screen / Fill the screen with a background color.
    screen.blit(image, rect)  # Blit an image on some destination.  Usually you blit more than one image using pygame.sprite.Group.
    pygame.display.update()  # Or 'pygame.display.flip()'.

对于您的代码,您可能应该执行以下操作:

rect = pygame.Rect((x_position, y_position), (button_width, button_height))
while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            button = new_button  # Both should be a pygame.Surface.

    gameDisplay.fill(background_color, rect)  # Clear the screen.
    gameDisplay.blit(button, rect)
    pygame.display.update()

如果您只想更新图片所在的区域,可以在更新方法pygame.display.update(rect)内传递 rect

答案 1 :(得分:0)

要在屏幕上显示更改,请使用pygame.display.update()

您的代码应如下所示

width = 100
height = 50
gameDisplay.blit(button, (width, height))
while True:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            gameDisplay.blit(new_button, (width, height))
            pygame.display.update()