如何使用pygame为子画面设置多个位置?

问题描述 投票:0回答:1

我正在创建一系列迷宫,玩家必须在其中收集5个硬币(即黄色精灵)。到目前为止,我已经设置了所有迷宫墙,并且我的游标精灵也正常工作。但是,当我尝试将5个精灵放置到迷宫中时,一次似乎不能超过一个。下面是迷宫的房间1。我有代码block.rect.x = 50和block.rect.y = 520来放置第一个精灵,但是当我尝试添加更多坐标时,我仍然只能得到一个精灵。我尝试过:

block.rect.x = (50, 100)
block.rect.y = (520, 120)   

这不起作用。任何建议都欢迎!谢谢!

class Room1(Room):
    """This creates all the walls in room 1"""

    def __init__(self):
        super().__init__()
        # Make the walls. (x_pos, y_pos, width, height)

        # This is a list of walls. Each is in the form [x, y, width, height]
        walls = [[0, 0, 20, 250, WHITE],
                 [0, 350, 20, 250, WHITE],
                 [780, 0, 20, 250, WHITE],
                 [780, 350, 20, 250, WHITE],
                 [20, 0, 760, 20, WHITE],
                 [20, 580, 760, 20, WHITE],
                 [100, 20, 20, 500, BLUE],
                 [200, 80, 20, 500, PURPLE],
                 [300, 20, 20, 500, BLUE],
                 [400, 80, 20, 500, PURPLE],
                 [500, 20, 20, 500, BLUE],
                 [600, 80, 20, 500, PURPLE],
                 [700, 20, 20, 500, BLUE],
                 ]

        # Loop through the list. Create the wall, add it to the list
        for item in walls:
            wall = Wall(item[0], item[1], item[2], item[3], item[4])
            self.wall_list.add(wall)

    for i in range(5):
        # This represents a block
        block = Block(YELLOW, 20, 15)

        ****# Set a location for the block
        block.rect.x = 50
        block.rect.y = 520****

        # Add the block to the list of objects
        block_list.add(block)
        all_sprites_list.add(block)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

score = 0
python-3.x pygame location sprite pygame-surface
1个回答
0
投票

创建5个职位的列表。例如:

block_positions = [(50, 520), (70, 520), (90, 520), (110, 520), (130, 520)]

遍历列表并创建Block对象:

for pos in block_positions :
    # This represents a block
    block = Block(YELLOW, 20, 15)

    block.rect.topleft = pos;

    # Add the block to the list of objects
    block_list.add(block)
    all_sprites_list.add(block)

注意,我建议将位置参数添加到Blocks的构造函数中。block.rect.topleft = posblock.rect.x = pos[0]block.rect.y = pos[1]相同。参见pygame.Rect

© www.soinside.com 2019 - 2024. All rights reserved.