RenPy怪物收集游戏开发:如何创建不覆盖的怪物对象?
嘿,我懂你现在的困扰——用单独的Slot1、Slot2这种变量根本没法通过索引动态访问,导致循环找空位的逻辑完全跑不起来,还容易出现覆盖问题对吧?咱们来一步步把代码改对:
问题根源
你当前的代码有两个核心问题:
- 用独立变量代替列表:你定义的是
Slot1、Slot2这种单独的变量,不是Python列表,所以Slot[X]这种写法根本不生效,自然没法动态修改目标槽位。 - 语法错误拖后腿:比如
__init__方法末尾没加冒号、while Counter = 0用了赋值号=而不是比较号==、还用了Python关键字is当变量名(这会直接报错)。
修改后的完整代码
我们把槽位改成列表存储,同时修复语法问题,就能实现循环找空位的逻辑了:
1. 修复怪物类定义
init python: class Monster: # 修复语法:括号后加冒号,替换关键字is为slot_status def __init__(self, species, hp, slot_status): self.type = species self.health = hp self.slot_status = slot_status # 0=空位,1=已占用,状态标记更清晰
2. 初始化怪物槽位列表
把原来的Slot1、Slot2换成一个列表,这样就能通过索引访问每个槽位:
label start: # 初始化3个空位的槽位列表,slot_status=0表示空位 $ monster_slots = [Monster("Null", 0, 0) for _ in range(3)] # 你的后续代码继续...
3. 捕获怪物的逻辑(循环找空位)
用for循环遍历列表找第一个空位,逻辑更简洁:
label Caught: # 假设Species和HP已经在调用此标签前赋值完成 $ found_empty_slot = False # 遍历所有槽位找空位 for slot in monster_slots: if slot.slot_status == 0: # 给空位赋值新怪物的属性 slot.type = Species slot.health = HP slot.slot_status = 1 # 标记为已占用 $ found_empty_slot = True break # 没找到空位的提示 if not found_empty_slot: "You have too many Monsters"
如果你更习惯用while循环,也可以这么写:
label Caught: $ current_index = 0 $ found_empty_slot = False while current_index < len(monster_slots): if monster_slots[current_index].slot_status == 0: # 直接替换成新的怪物对象 monster_slots[current_index] = Monster(Species, HP, 1) $ found_empty_slot = True break $ current_index += 1 if not found_empty_slot: "You have too many Monsters"
额外优化建议
如果想更直观地区分空位,也可以给Monster类加个is_empty属性,或者直接用self.type == "Null"来判断空位,这样状态标记会更易懂。
内容的提问来源于stack exchange,提问作者Lord Tzeentch
相关产品推荐
相关产品推荐

