如何将 rect 传递给 pygame.display.update() 以更新窗口的特定区域? [英] How do I pass a rect into pygame.display.update() to update a specific area of the window?

查看:30
本文介绍了如何将 rect 传递给 pygame.display.update() 以更新窗口的特定区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

On the documentation page for pygame.display.update(), it says you can pass a rect into the method to update part of the screen. However, all of the examples I see just pass an existing rect from an image or shape in the program. How can I tell it to update an area on the screen directly? For example, when drawing a rectangle, I could use a rect argument of (100,200,30,40). This would draw a rectangle with a top at 200, a left at 100, a width of 30, and a height of 40. How can I pass a similar argument into pygame.display.update()? I tried pygame.display.update((100,200,30,40)), but this updates the entire window.

解决方案

Just define a rect and pass it to pygame.display.update() to update only this specific region of the display. You can also pass a list of 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()

这篇关于如何将 rect 传递给 pygame.display.update() 以更新窗口的特定区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆