我正在使用pygame创建一个小场景。现在,我正在使用线路。
我有一系列线条被绘制到屏幕上,当从阵列中删除一条线时,我希望线条从屏幕上消失。
我发现的问题是线条在屏幕上绘制并保持静止。我找不到重置屏幕的方法(我使用JPEG作为背景)。
有没有办法从屏幕上删除绘制的线条?
由于
答案 0 :(得分:4)
虽然看起来效率不高,但我认为最简单也是最好的方法是重绘一切。在许多游戏中,即使没有3D卡,屏幕也会在每一帧都重新绘制(请记住旧的Doom游戏吗?)。因此,即使在python中,在背景上绘制几行也会非常快。
我会想象这样的事情:
import pygame
import random
SCREEN_WIDTH = 320
SCREEN_HEIGHT = 200
class Line(object):
def __init__(self, start_pos, end_pos, color, width):
object.__init__(self)
self.start_pos = start_pos
self.end_pos = end_pos
self.color = color
self.width = width
def CreateRandomLine():
rnd = random.randrange
start_pos = (rnd(SCREEN_WIDTH), rnd(SCREEN_HEIGHT))
end_pos = (rnd(SCREEN_WIDTH), rnd(SCREEN_HEIGHT))
color = (rnd(255), rnd(255), rnd(255))
width = rnd(10) + 1
return Line(start_pos, end_pos, color, width)
def DrawScene(screen_surface, background_image, lines):
screen_surface.blit(background_image, (0, 0))
for line in lines:
pygame.draw.line(screen_surface, line.color, \
line.start_pos, line.end_pos, line.width)
pygame.init()
screen_surface = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
background_image = pygame.Surface(((SCREEN_WIDTH, SCREEN_HEIGHT)))
background_image.fill((200, 100, 200)) # I kinda like purple.
# Alternatively, if you have a file for your background:
# background_image = pygame.image.load('background.png')
# background_image.convert()
lines = []
for i in range(10):
lines.append(CreateRandomLine())
for frame_id in range(10):
del lines[0] # Remove the oldest line, the one at index 0.
lines.append(CreateRandomLine()) # Add a new line.
DrawScene(screen_surface, background_image, lines)
pygame.display.flip()
pygame.time.wait(1000) # Wait one second between frames.
此脚本在背景上显示随机线条。有10帧,每帧持续一秒。在每个帧之间,第一行从行列表中删除,并添加一个新行。
只需删除pygame.time.wait并查看它的速度:D。
答案 1 :(得分:1)
如果您使用screen.fill([0,0,0]),它将填写背景(或您设置为背景的任何内容)。
这将删除图像上绘制的任何线条,基本上删除在背景上绘制的任何内容。
答案 2 :(得分:0)
您可能需要运行命令来更新显示,如the documentation中所述。更新完整显示表面的命令是:
pygame.display.update()
有可能将一个参数传递给函数只更新所需的部分,这样会更有效率,但如果没有完整的代码,我就无法告诉你那个参数会是什么。