如何在Python/Python中复制对象?

2024-04-28 09:04:17 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在玩游戏平台。现在我有了一个玩家角色,一个保险杠和背景。玩家可以在水平或保险杠的地板上跑来跑去,当角色撞到边缘时,屏幕可以屏蔽。在

不过,我想要的是一种方法,有多个保险杠,而不必单独创建每个保险杠。这是一些相关的代码。在

这是在游戏的主循环之前创建保险杠。。。在

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。。。在

^{pr2}$

这是一些代码,以便玩家正确地降落在平台上。基本上,在最后一个循环迭代中,它会减慢玩家的速度,使其从保险杠坠落,从而使玩家的底部落在保险杠的顶部。在

    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

任何帮助都有用?!在


Tags: andthe代码rightmoveif屏幕top
1条回答
网友
1楼 · 发布于 2024-04-28 09:04:17

您需要为正在创建的对象创建一个类。在

例如:

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])

要同时创建对象

^{pr2}$

随着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]))

相关问题 更多 >