【问题标题】:How do I move multiple identical rectangles in a list separately?如何分别移动列表中的多个相同矩形?
【发布时间】:2019-06-01 16:35:19
【问题描述】:

我试图以给定的速率生成无限数量的敌人,并让它们向玩家移动。但是,我只能设法让两个生成,一个用于它们生成的每个原始矩形。这是因为移动覆盖了它们生成的矩形,因此任何进一步的敌人只会在前两个中的一个之上生成。这是使用 move_ip() 函数,我认为这可能是问题所在,但尝试仅使用 move() 会导致根本没有移动。

def main():
global DISPLAYSURF, FPSCLOCK

pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))
pygame.display.set_caption ('Ronin')
checkForQuit()

enemies = []
playerX = 730



enemyImage = pygame.image.load('enemyidle.png')
enemySurf = pygame.transform.scale(enemyImage, (PLAYERWIDTH, PLAYERHEIGHT))
leftRect = pygame.Rect(0, 735, PLAYERWIDTH, PLAYERHEIGHT)
rightRect = pygame.Rect(1500, 735, PLAYERWIDTH, PLAYERHEIGHT)
moveLeft = moveRight = moveUp = moveDown = False
enemycounter = 0

while True:

    checkForQuit()




    #Draw the background
    DISPLAYSURF.blit(backgroundSurf, backgroundRect)

    #draw the player
    DISPLAYSURF.blit(playerSurf, playerRect)


    #time the enemy spawn and draw the enemies


    enemy = random.choice([leftRect, rightRect])

    if enemycounter < ENEMYSPAWNRATE:
            enemycounter += 1
    if enemycounter == ENEMYSPAWNRATE:
            enemycounter = 0
            enemies.append(enemy)

    enemyAI(enemies, playerRect)

    for e in enemies:
        DISPLAYSURF.blit(enemySurf, e)



    pygame.display.update()
    FPSCLOCK.tick(FPS)






def enemyAI(enemies, playerRect):
    for e in enemies:
        if e.left > playerRect.right:
            e.move_ip(-1 * PLAYERSPEED +5, 0)
        if e.right < playerRect.left:
            e.move_ip(PLAYERSPEED -5, 0)



main()    

我可以在调试器中看到,添加到敌人列表中的每个新敌人都与前两个现有敌人之一具有相同的坐标。但我希望它们出现在由 leftRect 或 rightRect 指定的原始坐标处。

【问题讨论】:

    标签: python pygame 2d-games


    【解决方案1】:

    你大部分是正确的。您的问题在于创建两个矩形,然后将每个敌人分配到这两个矩形之一。

    因为enemy = random.choice(...)leftRectrightRect 创建了一个别名,并且因为您是enemies.append(enemy),所以您有一个包含相同两个矩形的别名的列表。

    在随机选择矩形后尝试制作一个.copy()

    startLocations = (leftRect, rightRect)
    
    def new_enemy():
        """Return a new enemy rect randomly in one of the start locations"""
        return random.choice(startLocations).copy()
    
    while True:
    
        # ... as before ...
    
        #time the enemy spawn and draw the enemies
        if enemycounter < ENEMYSPAWNRATE:
            enemycounter += 1
        else:
            enemycounter = 0
            enemies.append(new_enemy())
    
        enemyAI(enemies, playerRect)
    
        # ... as before ...
    

    【讨论】:

    • 谢谢你,这有效。我能够将 .copy() 添加到敌人 = random.choice(leftRect, rightRect) 的末尾。
    猜你喜欢
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 2012-01-02
    • 2021-02-06
    • 2018-02-22
    相关资源
    最近更新 更多