在Python中如何使用for循环为多个实例调用相同的class属性?

2024-09-25 02:37:03 发布

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

我正在尝试使用for循环来检查用户是否在我的pygame中单击了一个库存槽。我已经创建了名称为“slot1”、“slot2”、“slot3”等的插槽,一直到“slot13”。我的问题是:如何在每次迭代的“slot”后面添加数字?你知道吗

if event.type == pg.MOUSEBUTTONDOWN and event.button == 3:
    for i in range(14):
        if mouse_click and inventory_state and slot+str(i).collidepoint(pos):
            inventory.equip_item(inventory.items[i])

Tags: and名称eventforif检查用户库存pygame
2条回答

欢迎来到Tripti社区。对于高达13的范围,您可以将i的值存储在一个变量中,每次都附加“slot”。我想那会解决你的问题的!你知道吗

不要将插槽存储在不同的变量中,而是存储在一个列表中。然后可以遍历此列表:

for i in range(13):
    if mouse_click and inventory_state and slots[i].collidepoint(pos):
        inventory.equip_item(inventory.items[i])

相关问题 更多 >