训练你的代码像小队长一样,
自动管理整支队伍!
For 循环就像一个训练有素的小队长!
他不需要你一个一个手动指挥士兵,而是能自动走到每个士兵面前,检查情况并下达命令。
while True: friends = hero.findFriends() # 小队长开始巡逻每个人: for friend in friends: enemy = friend.findNearestEnemy() if enemy: hero.command(friend, "attack", enemy) else: # 没有敌人就前进 # ...
每个游戏对象都有自己的位置信息 (.pos)。
就像你知道每个朋友坐在教室的哪个座位一样。
# 问:"你现在坐在哪里?" current_pos = friend.pos # 获取具体的 X 和 Y print("朋友在 X:", friend.pos.x) print("朋友在 Y:", friend.pos.y)
我们要告诉朋友:“从你现在的位置,向右走一小步!”
想向左走?那就减去 0.35!
# 创建一个新的目标位置 moveTo = { "x": friend.pos.x + 0.35, "y": friend.pos.y } hero.command(friend, "move", moveTo)
if-else 就像交通警察!
enemy = friend.findNearestEnemy() if enemy: # 🔴 发现敌人! hero.command(friend, "attack", enemy) else: # 🟢 安全通行 moveTo = {"x": friend.pos.x + 0.35, ...} hero.command(friend, "move", moveTo)
while True: 就像一个 24 小时工作的监控摄像头。
它不会只检查一次,而是永远在运行,不断地发现新情况并做出反应。
while True: # 永远重复! # 1. 扫描所有人 friends = hero.findFriends() # 2. 每个人做决定 for friend in friends: # ... 攻击或移动 # 3. 回到第一步,继续循环...
friend.findNearestEnemy()
每个士兵都有自己的“眼睛”,只看离自己最近的敌人。
x + 0.35
为什么要慢慢走?
1. 保持队形整齐
2. 避免跑太快被包围
"小明,去攻击!" "小红,去攻击!" "小刚,去攻击!" # 要一个一个喊...
children = [小明, 小红, 小刚]
for child in children:
child.去玩()
# 自动搞定所有人!