🗺️ 计算机科学 4
Loading...
👮‍♂️ 📜 🤖

For 循环练习

(For Loop Practice)

训练你的代码像小队长一样,
自动管理整支队伍!

For 循环:你的“自动小队长”

生动解释

For 循环就像一个训练有素的小队长

他不需要你一个一个手动指挥士兵,而是能自动走到每个士兵面前,检查情况并下达命令。

while True:
    friends = hero.findFriends()
    # 小队长开始巡逻每个人:
    for friend in friends:
        enemy = friend.findNearestEnemy()
        if enemy:
            hero.command(friend, "attack", enemy)
        else:
            # 没有敌人就前进
            # ...

📍 朋友在哪里?

🗺️

每个游戏对象都有自己的位置信息 (.pos)

就像你知道每个朋友坐在教室的哪个座位一样。

x: 横坐标 (左右)
y: 纵坐标 (上下)
# 问:"你现在坐在哪里?"
current_pos = friend.pos

# 获取具体的 X 和 Y
print("朋友在 X:", friend.pos.x)
print("朋友在 Y:", friend.pos.y)

➕ 计算下一步:向右走!

我们要告诉朋友:“从你现在的位置,向右走一小步!”

数学公式:
新位置 X = 旧位置 X + 0.35
(Y 保持不变)

想向左走?那就减去 0.35!

# 创建一个新的目标位置
moveTo = {
    "x": friend.pos.x + 0.35, 
    "y": friend.pos.y
}

hero.command(friend, "move", moveTo)

🚦 聪明的交通警察:If-Else

🚥

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

📹

while True: 就像一个 24 小时工作的监控摄像头。

它不会只检查一次,而是永远在运行,不断地发现新情况并做出反应。

while True: # 永远重复!
    # 1. 扫描所有人
    friends = hero.findFriends()
    
    # 2. 每个人做决定
    for friend in friends:
        # ... 攻击或移动
    
    # 3. 回到第一步,继续循环...

🧠 战术思维升级

👁️

个体感知

friend.findNearestEnemy()

每个士兵都有自己的“眼睛”,只看离自己最近的敌人。

🐌

缓慢推进

x + 0.35

为什么要慢慢走?
1. 保持队形整齐
2. 避免跑太快被包围

🎉 总结:游乐场管理员

👨‍🏫 传统方式 (累!)

"小明,去攻击!"
"小红,去攻击!" 
"小刚,去攻击!"
# 要一个一个喊...

🤖 智能方式 (For 循环)

children = [小明, 小红, 小刚]
for child in children:
    child.去玩()
# 自动搞定所有人!
For 循环让你从“微观管理”升级到“宏观指挥”! ✨