如何保存 pygame 屏幕的一部分并将其 blit 到另一个位置?

How do I save a section of a pygame screen and blit it to another location?

我正在制作一个带有滚动图形的程序,我只需要移动屏幕的一部分。

如果我这样做:

import pygame

screen = pygame.display.set_mode((300, 300))

sub = screen.subsurface((0,0,20,20))

screen.blit(sub, (30,40))

pygame.display.update()

它给出了错误消息:pygame.error:表面在 blit 期间不能被锁定

我认为这意味着 child 被锁定在其 parent 表面或其他东西上,但我还能怎么做呢?

screen.subsurface 创建一个表面,它参考原始表面。来自文档:

Returns a new Surface that shares its pixels with its new parent.

为避免未定义的行为,表面被锁定。您必须 .copy the surface, before you can .blit 它的来源:

sub = screen.subsurface((0,0,20,20)).copy()
screen.blit(sub, (30,40))

只是不要直接绘制到屏幕表面。为你的 game/UI 的每个部分创建一个 Surface,并将每个部分 blit 到屏幕。

import pygame

def main():
    pygame.init()
    screen = pygame.display.set_mode((640, 480))

    # create two parts: a left part and a right part
    left_screen = pygame.Surface((400, 480))
    left_screen.fill((100, 0, 0))

    right_screen = pygame.Surface((240, 480))
    right_screen.fill((200, 200, 0))

    x = 100
    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return

        # don't draw to the screen surface directly
        # draw stuff either on the left_screen or right_screen
        x += 1
        left_screen.fill(((x / 10) % 255, 0, 0))

        # then just blit both parts to the screen surface
        screen.blit(left_screen, (0, 0))
        screen.blit(right_screen, (400, 0))

        pygame.display.flip()

if __name__ == '__main__':
    main()