【问题标题】:pygame-How to replace an image with an other onepygame-如何用另一个图像替换图像
【发布时间】:2016-08-11 19:51:23
【问题描述】:

我有这样的代码:

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

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

【问题讨论】:

  • 使用一个全局的image,然后根据需要重新设置该值,同时连续传输。

标签: python python-3.x pygame


【解决方案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()

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

【讨论】:

  • 非常感谢,你很有帮助!
  • @StamKaly 没问题 :) 只有一个问题:我见过很多人使用 gameDisplay 作为变量名。你从哪里学来的?您是否正在学习一些教程?
  • 谢谢!这是另一个很好的教程,我认为你会从检查中受益。有一些较长的停顿,因为它实际上不是一个 youtube 教程,而是一个录制的研讨会。不过还是很棒的。 youtube.com/…
【解决方案2】:

要在屏幕上显示更改,请使用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()

【讨论】:

  • 它只是在旧按钮上绘制新按钮,它不会替换它
猜你喜欢
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多