如何在Python/Pygame中复制对象?
我正在玩一个用Pygame制作的平台游戏。目前我有一个玩家角色、一个挡板和背景。玩家可以在关卡的地面或挡板上跑动,当角色跑到边缘时,屏幕会跟着移动。
不过,我想要一种方法,可以创建多个挡板,而不需要一个个单独去做。这里有一些相关的代码。
这段代码是在游戏的主循环之前创建挡板的...
bumper = pygame.image.load("bumper.png") #load bumper pic
bumperbounds = bumper.get_clip() #create boundaries for bumper
bumperbounds = bumperbounds.move (200, 250) #move the bumper to starting location
这段代码是让挡板阻止玩家掉下去的。它只是把“着陆”这个值设为1...
if playerbounds.left <= bumperbounds.right and playerbounds.right >= bumperbounds.left and playerbounds.bottom <= bumperbounds.top + 30 and playerbounds.bottom >= bumperbounds.top and gravity >=0: #if player lands on top of the bumper
landed = 1 #set player to landed
这段代码是为了让玩家正确地落在平台上。基本上,它在最后一次循环时减慢玩家的下落速度,这样玩家正好以自己的下落速度落在挡板的顶部。
if playerbounds.left <= bumperbounds.right and playerbounds.right >= bumperbounds.left and playerbounds.bottom <= bumperbounds.top and gravity > bumperbounds.top-playerbounds.bottom: #to land exactly on the top of the bumper
gravity = bumperbounds.top-playerbounds.bottom
这段代码是为了在屏幕滚动时移动挡板。这只是向右移动,向左的方式基本上是一样的。
if xacc > 0:#if player is moving right
if playerx >= width * .8 and screenx < levelwidth - playerbounds.width:#if the screen is scrolling
screenx = screenx + xacc
bumperbounds = bumperbounds.move(-xacc, 0) #bumper moves on the screen
skybounds = skybounds.move(-xacc / 10, 0)
groundbounds = groundbounds.move(-xacc * 2, 0)
else:
playerbounds = playerbounds.move(xacc, 0)
playerx += xacc
xacc -= 1
这段代码只是显示挡板在循环结束时出现在屏幕上的样子。
screen.blit(bumper,bumperbounds) #displays the bumper on the screen
任何帮助都很有用?!
1 个回答
4
你需要为你正在创建的对象建立一个类。
比如说:
class Leaf:
def __init__(self):
self.leafimage = pygame.image.load('fallingleaf.jpg').convert()
self.leafrect = self.leafimage.get_rect()
xpos = random.randint(0, 640)
self.leafrect.midtop = (xpos, 0)
def move(self):
self.leafrect = self.leafrect.move([0, 1])
如果你想同时创建多个对象,
leaves = []
for i in range(5):
leaves.append(Leaf())
可以通过改变xpos的值来实现:
class Leaf:
def __init__(self,xpos):
self.leafimage = pygame.image.load('fallingleaf.jpg').convert()
self.leafrect = self.leafimage.get_rect()
self.leafrect.midtop = (xpos, 0)
def move(self):
self.leafrect = self.leafrect.move([0, 1])
To create objects at the same time,
leaves = []
xpos= [20 30 40 50 60]
for i in range(5):
leaves.append(Leaf(xpos[i]))