像俄罗斯套娃一样:
循环里面 再套 循环
Outer Loop (外层): 像一天的时间(早到晚)。
Inner Loop (内层): 像这一天里吃的每一顿饭。
while 外层条件: # 🌞 比如:游戏的主循环 ... while 内层条件: # 🔄 比如:遍历这一波的怪物 ... ...
我们用 coinIndex 像手指一样,从 0 开始,一个一个检查列表里的硬币。
len(coins) 是队伍的长度。
while True: coins = hero.findItems() coinIndex = 0 # 👇 内层循环:遍历硬币列表 while coinIndex < len(coins): coin = coins[coinIndex] # ... 检查硬币的代码写在这里 ... coinIndex += 1 # 👈 手指移向下一个
coin = coins[coinIndex] # 🏷️ 检查:价值等于 3 吗? if coin.value == 3: # 是金币!走过去捡起来! hero.moveXY(coin.pos.x, coin.pos.y) # 铜币(1) 和 银币(2) 会被忽略
coin.value 就像贴在硬币上的价格标签。
适用于:不知道有多少个,反正捡完为止。
coin = hero.findNearestItem() # 当 coin 存在 (不是 None) while coin: hero.moveXY(coin.pos.x, coin.pos.y) # ⚠️ 关键:必须重新找下一个! # 如果不更新 coin,hero 会以为还在原来的位置 coin = hero.findNearest(hero.findItems())
While (娃娃机里还有娃娃):
1. 抓一个。
2. 看看里面还有没有。
适用于:打怪。只要它还有一口气,就不要停。
While (对手还没倒下):
1. 出拳攻击。
2. (攻击会导致血量下降)
enemy = hero.findNearest(hero.findEnemies()) if enemy: # 只要血量大于 0,就一直打 while enemy.health > 0: hero.attack(enemy) # 每次攻击,enemy.health 都会变小 # 直到变成 0,循环自动停止
while i < len(items): ...
逐个检查,配合 if 进行过滤。
while enemy.health > 0: ...
盯着一个目标,直到状态改变(消失或死亡)。