python - pygame.display.update 更新整个屏幕

标签 python pygame

我正在创建一个带分屏的多人游戏。

我首先在左侧绘制第一个玩家(宇宙飞船、燃烧弹、背景中的星星(以半速滚动),最后是背景),然后更新屏幕的第一部分,第一个玩家。然后我在屏幕的另一部分为第二个玩家做同样的事情。

但是大部分图像在两个半屏之间重叠。 (见下图)

所以,基本上我需要使用 pygame.display.update() 更新屏幕的一部分,然后是另一部分。

但是该命令不起作用,并且更新了整个屏幕。一切都重叠。

我尝试了以下方法:

pygame.display.update(Rect((pos, 0), size))

pygame.display.update(Rect((pos, 0, size[0], size[1])))

pygame.display.update((pos, 0, size[0], size[1]))

pygame.display.update(pos, 0, size[0], size[1])

pygame.display.update((pos, 0), size)

但所有这些都在做完全相同的事情,而且它们没有按预期工作。

Rendering

最佳答案

当您使用 pygame.display.update() 时,有两种可选参数,单个矩形(默认为无)和矩形列表.如果没有传递参数,它会更新整个表面积 - 就像 display.flip() 一样。

update(rectangle=None) -> None
update(rectangle_list) -> None

要仅更新特定元素,如果要同时更新同一组,请创建这些元素的列表

background_rects = [star_rect, star_rect, star_rect, some_other_rect]
foreground_rects = [player_rect, enemy1_rect, enemy2_rect, bullet1_rect, bullet2_rect]
pygame.display.update(background_rects)
pygame.display.update(foreground_rects)

或使用单个元素多次调用 update(rect):

pygame.display.update(star1_rect)
pygame.display.update(star2_rect)
pygame.display.update(star3_rect)
pygame.display.update(character_rect)
pygame.display.update(enemy_rect)

文档链接:https://www.pygame.org/docs/ref/display.html#pygame.display.update

pygame 1.9.6 和 2.0.0.dev 分支的处理之间似乎存在一些差异(可能是无意的,因为文档中没有相关内容)- 下面是 MRE适用于 1.9.6,但不适用于 2.0.0.dev10 版本。在 1.9.6 中,更新显示的差异显而易见。如果您需要这个确切的功能,我建议您安装稳定 1.9.6 版本!

如果其他人想碰碰运气,这里是我测试过的 MRE:

import pygame
import time    
screen = pygame.display.set_mode((720, 480)) 

rect = pygame.Rect((10, 50), (32, 32))  
image = pygame.Surface((32, 32)) 
image.fill((0,100,0))

rect2 = pygame.Rect((10, 10), (32, 32)) 
image2 = pygame.Surface((32, 32)) 
image2.fill((100,100,0))

i = 0
while True:
    i += 1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
            
    screen.blit(image, rect)
    screen.blit(image2, rect2)
    rect.x += 1 # we update the position every cycle
    rect2.x += 1  # we update the position every cycle
    
    # but update the rect on screen at different times:
    if i < 10:
        pygame.display.update() # both
    elif i > 50 and i < 75:
        pygame.display.update(rect2) # only rect2 
    elif i >= 100:
        pygame.display.update(rect) # only rect

    time.sleep(0.1)

关于python - pygame.display.update 更新整个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63391103/

相关文章:

python - 如何调整pygame中的图像大小以到达屏幕的顶部/底部?

Python:几秒钟后将 bool 值从 True 更改为 False

python - 在 PyGame (SDL) 中使用 Cairo 时的字节顺序

python - pygame.mixer.music.pause 应该以我的方式工作吗?

python 遍历列表

python - pydantic从dict生成模型

python - 你将如何处理 python 游戏中的插值?

python - 在测试用例(单元测试)中,无法捕获 Django pre_save 信号

python - 为什么打印 -0.0?

python - 试图将 csv 的一部分提取到 numpy 数组