【问题标题】:surface.fill() updating rect in while loop?surface.fill() 在while循环中更新矩形?
【发布时间】:2019-03-16 06:06:01
【问题描述】:

下面有两个程序试图在黄色屏幕上画一个球。一个是我的表面对象在 while 循环之外填充,另一个是在 while 循环内部填充。

当我在 while 循环之外有 .fill() 时,当我尝试移动它时,我的图像会被重绘。因此,当图像下降时,它会在屏幕下方仅 10 像素处绘制一个重复的图像。

当我在 while 循环中有 .fill() 时,我的单个图像会更新并重新绘制到新位置。

这是为什么?

非尾随代码:

import pygame
import sys

length = 1200
width = 800


screen = pygame.display.set_mode((length, width))
screen_rect = screen.get_rect()

ball = pygame.image.load('ball.bmp')
ball_rect = ball.get_rect()
ball_rect.y = ball_rect.width
ball_rect.x = screen_rect.centerx


while True: 
    screen.fill((255, 255, 103))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                ball_rect.y += 15

    screen.blit(ball, ball_rect)
    pygame.display.flip()

尾随图像代码:

import pygame
import sys

length = 1200
width = 800


screen = pygame.display.set_mode((length, width))
screen_rect = screen.get_rect()
screen.fill((255, 255, 103))

ball = pygame.image.load('ball.bmp')
ball_rect = ball.get_rect()
ball_rect.y = ball_rect.width
ball_rect.x = screen_rect.centerx


while True: 


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                ball_rect.y += 15

    screen.blit(ball, ball_rect)
    pygame.display.flip()

【问题讨论】:

标签: pygame blit


【解决方案1】:

链接代码(图片)不产生你描述的效果。在左侧,screen 根本没有更新。在右侧,唯一的更新是黄色的screen.fill()

所以假设性地...

PyGame 程序可以被认为是一种动画。在主循环期间,通常有一个块用于处理用户输入、更新屏幕对象位置的调用和更新调用,即“重新绘制”屏幕。

此动画的每个“帧”均由背景构成,通常还包含一些叠加的对象。这些可能是玩家位图、战斗位图、比赛场地项目、文本分数和状态等。通常首先绘制背景,然后是覆盖的项目。绘制屏幕后,将计算对象的移动以进行下一次显示,然后重新绘制,然后一次又一次......

问题描述的第一种情况是屏幕更新的方式使得动画的前一个“帧”没有被清除,并且用户看到前一个和当前显示的合成。

第二种情况首先擦除整个显示,使用screen.fill()。从而删除前一帧的任何痕迹。这是典型的处理方式。

还有另一种方法。此方法跟踪屏幕更改的位置,并且仅重新绘制需要更新的特定区域。这种方法可能会提供更有效的输入-更新-绘制循环,因为它不会重新绘制未更改的项目。

【讨论】:

  • 左边的代码跟在我的图片后面,右边的代码不跟在图片后面。但我想我明白你在说什么。从本质上讲,每当任何覆盖的对象发生移动时,我都会重新绘制背景?
  • 另外 - 你描述的另一种方式是什么?
  • 是的,几乎每一帧 - 绘制背景,绘制游戏对象。重复。第三种方式使用通常称为“脏”矩形的概念。屏幕更新的部分被认为是“脏的”。这里有一个简短的教程 - n0nick.github.io/blog/2012/06/03/…
猜你喜欢
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多