pygame.display.update()更新整个屏幕

时间:2020-08-13 08:27:55

标签: python pygame

我创建了带有分屏的多人游戏。

我在左边绘制了第一个玩家(航天飞机,火弹,星星(滚动半滚动)和背景),然后更新了屏幕的第一部分。我对第二个玩家也一样。 但是大多数效果(例如星星)

x = -(self.scrollX / 2 % size[0])
y = -(self.scrollY / 2 % size[1])
screen.blit(self.stars_image,
            (int(x + pos), int(y)))

screen.blit(self.stars_image,
            (int(x + size[0] + pos), int(y)))

screen.blit(self.stars_image,
            (int(x + pos), int(y + size[1])))

screen.blit(self.stars_image,
            (int(x + size[0] + pos), int(y + size[1])))
# size is a tuple which contains the size allowed to the player
# pos is the x position of the part of the screen allowed to the player.

)从屏幕退出。

所以我需要使用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

1 个答案:

答案 0 :(得分:3)

使用pygame.display.update()时,有两种可选参数,即单rect(默认为None)和rect列表。如果未传递任何参数,则它将更新整个表面区域,就像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)