如何将rect传递给pygame.display.update()以更新窗口的特定区域?

时间:2018-02-09 18:11:19

标签: python-3.x pygame pygame-surface

pygame.display.update() (100,200,30,40)上,它表示您可以将rect传递给方法以更新部分屏幕。但是,我看到的所有示例都只是从程序中的图像或形状传递现有的rect。如何告诉它直接更新屏幕上的区域?例如,在绘制矩形时,我可以使用pygame.display.update()的rect参数。这将绘制一个矩形,顶部为200,左边为100,宽度为30,高度为40.我如何将类似的参数传递给pygame.display.update((100,200,30,40))?我尝试了jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env; if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) { return -1; } return JNI_VERSION_1_6; } ,但这会更新整个窗口。

1 个答案:

答案 0 :(得分:2)

只需定义rect并将其传递给pygame.display.update()即可仅更新显示的此特定区域。您还可以传递一系列rects。

import random

import pygame as pg
from pygame.math import Vector2


# A simple sprite, just to have something moving on the screen.
class Ball(pg.sprite.Sprite):

    def __init__(self, screen_rect):
        super().__init__()
        radius = random.randrange(5, 31)
        self.image = pg.Surface((radius*2, radius*2), pg.SRCALPHA)
        pg.draw.circle(self.image, pg.Color('dodgerblue1'), (radius, radius), radius)
        pg.draw.circle(self.image, pg.Color('dodgerblue3'), (radius, radius), radius-2)
        self.rect = self.image.get_rect(center=screen_rect.center)
        self.vel = Vector2(random.uniform(-2, 2), random.uniform(-2, 2))
        self.pos = Vector2(self.rect.center)
        self.screen_rect = screen_rect
        self.lifetime = 350

    def update(self):
        self.pos += self.vel
        self.rect.center = self.pos

        self.lifetime -= 1
        if not self.screen_rect.contains(self.rect) or self.lifetime <= 0:
            self.kill()


def main():
    screen = pg.display.set_mode((800, 600))
    screen.fill((20, 40, 70))
    pg.display.update()
    screen_rect = screen.get_rect()
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    # Pass this rect to `pg.display.update` to update only this area.
    update_rect = pg.Rect(50, 50, 500, 400)

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        all_sprites.add(Ball(screen_rect))
        all_sprites.update()

        screen.fill((20, 50, 90))
        all_sprites.draw(screen)

        # Update only the area that we specified with the `update_rect`.
        pg.display.update(update_rect)
        clock.tick(60)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

enter image description here