为了创建一个抽象的、滚动的城市天际线原型,我创建了一个生成随机矩形的类。这些矩形被添加到一个列表中,并从该列表中提取项目以在屏幕上绘制。矩形从屏幕右侧开始,向左滚动,直到离开视图平面并被丢弃。建筑物的移动是奇怪的颠簸,他们也在屏幕上的特定点向右移动几个像素。在
这个原型的视频相当精确,几乎没有视频捕捉延迟。注意建筑物之间的间隙,当它们进入显示区域的最右边三分之一时,间隙会突然缩小,就好像间隙左侧的建筑物突然向右移动了几个像素。差距越小,越明显。视频中的其他异常是来自录像机的,在应用程序中不存在。下面是一段很短的视频,清楚地展示了这种现象:https://www.youtube.com/watch?v=0cdhrezjcY8
大约1秒后,你会注意到后面层的建筑物之间有一个非常窄的间隙。在第四个空格中,目标消失在空格处。第二个,在右边有一个更大的间隙,它做着同样的事情,但是由于这个间隙更大,它并没有完全消失。我已经看过代码很多次了,但是看不出是什么导致了这种异常。我希望有人能告诉我是我做了什么,还是遇到了一些限制。在
我最初是线性编写这个程序,没有类或函数。我用一个生成层对象并处理所有生成和滚动的类重写了它。在这两种情况下,问题都存在。我想弄清楚为什么这些建筑不能顺利移动,真让我抓狂。我甚至用png图像而不是随机生成的矩形编写了这个版本。在该版本中,png滚动平滑而无缝:https://www.youtube.com/watch?v=Uiw_giAvbOo(视频有点不稳定,但实际程序播放平滑),因此问题仅限于这些随机矩形。在
以下是程序代码:https://www.refheap.com/73079
下面是类代码本身:
class Scroller():
def __init__(self, speed, color, heightMax):
# Speed of the layer scroll, the color of the layer and the maximum height for buildings
# set up the building parameters
self.buildingHeightMax = heightMax
self.buildingHeightMin = 100
self.buildingWidthMax = 125
self.buildingWidthMin = 75
self.buildings = []
self.layerspeed = speed
self.buildTime = True
self.buildCountdown = 10
self.color = color
def update(self):
# Check if it's time to build. If not, decrement counter
if self.buildTime == False:
self.buildCountdown -= 1
# If time is 0, time to build, reset counter to a new random time
if self.buildCountdown <= 0:
self.buildTime = True
self.buildCountdown = random.randint(3, self.layerspeed)
# create building if it's time
if self.buildTime:
# generate random width and height of building
buildingHeight = random.randint(self.buildingHeightMin, self.buildingHeightMax)
buildingWidth = random.randint(self.buildingWidthMin, self.buildingWidthMax)
buildingTop = WINDOWHEIGHT - buildingHeight
# This generates the building object from the above parameters
building = pygame.Rect(WINDOWWIDTH, buildingTop, buildingWidth, WINDOWHEIGHT)
self.buildTime = False
self.buildCountdown = random.randint(3, self.layerspeed * 5)
# add building to buildings list
self.buildings.append(building)
# move all buildings on layer at set speed
for building in self.buildings:
# if the building is off the screen, trash it. If not, move it to the
# right at the objects speed.
if building.right < 0:
self.buildings.remove(building)
else:
building.left -= self.layerspeed
# draw the Front buildings
for i in range(len(self.buildings)):
pygame.draw.rect(windowSurface, self.color, self.buildings[i])
你的问题很可能在于:
您正在迭代的同一个列表中使用
remove
,这将使它跳过下一个构建。所以不是右边的那栋楼走得快,是左边那栋楼跳过了移动。在你可以通过这个简单的例子看到:
^{pr2}$尝试一下,您将看到不仅}也将被跳过。在
4
不会被打印,而且{可能一个好的方法是首先遍历所有的建筑物,看看哪些建筑物需要拆除,然后拆除所有建筑物,最后移动所有剩下的建筑物。
您可能想check this link寻求一些好的建议。在
您还更新了两次倒计时,第一次在第47行,然后在第58行。有什么原因吗?在
相关问题 更多 >
编程相关推荐