一起玩Python程式:新手寫程式也可以這麼簡單!

流程控制(下) - 程式的重複魔法!

張傑帆

National Taiwan University

流程控制(下) - 程式的重複魔法

目錄

Alt1

🎯 學習目標

今天我們要成為魔法師,掌握重複的神奇力量!

🔧 技能解鎖清單:

  • while迴圈魔法 - 讓程式自動重複執行 🐍
  • for迴圈技巧 - 批量處理資料能力 💪
  • 流程控制法術 - break與continue的妙用 🎩
  • 巢狀迴圈藝術 - 處理複雜邏輯結構 🎯
  • 尋寶遊戲實作 - 整合迴圈打造完整遊戲 🏆

準備好體驗程式重複的魔法了嗎?

Let's loop! 🐍🔮

while迴圈的基本結構與應用

while迴圈就像是程式界的「復讀機」,只要條件成立就會一直重複執行!

🔄 while迴圈基本語法:

while 條件:
  # 重複執行的程式碼
  pass # 這裡的pass表示暫時不做任何事,while裡有東西時不寫pass

🕒 簡單範例 - 時鐘倒數:

count = 5

while count > 0:
  print(f"倒數: {count}")
  count -= 1

print("時間到!⏰")

🔄 範例 - 驗證使用者輸入:

輸入直到符合條件為止

# 要求使用者輸入一個介於1到10之間的數字
number = 0

while number < 1 or number > 10:
  number = int(input("請輸入一個1到10之間的數字: "))
  if number < 1 or number > 10:
    print("輸入無效,請再試一次!")

print(f"你輸入的數字是 {number},謝謝!")

💡 生活範例 - 猜數字遊戲:

輸入直到猜中為止

import random

secret_number = random.randint(1, 10)
guess = 0

while guess != secret_number:
  guess = int(input("猜一個1-10的數字: "))
  if guess < secret_number:
    print("太小了!再試一次 🔍")
  elif guess > secret_number:
    print("太大了!再試一次 🔍")

print(f"恭喜答對了!答案是 {secret_number} 🎉")

小練習 1

🎯 練習題目:簡易正數計時器

  • 請撰寫一個程式,從使用者輸入的數字開始正數,並在每秒顯示經過秒數。
  • 請從剛才倒數的範例開始修改,讓原本的54321,變成123...n
count = 5 # 請改成讓使用者輸入
# 使用while迴圈
while count > 0: # 請思考條件要怎麼設計
  print(f"經過: {count}")
  count -= 1
print("時間到!⏰")

💭 思考時間:

  • 如何設計條件?(while 後面的那個)
  • 如何設計控制變數?(count)
  • 當計數結束時,程式會輸出什麼?
  • 如果輸入0或負數,程式應該如何處理?(如何防呆)

休息時間

讓我們的大腦稍作休息,準備迎接更多迴圈魔法! ☕️

for迴圈與range()函式

for迴圈是處理序列資料的專家!配合range()函式更是威力無窮 💪

🔢 range()函式的三種用法:

# 用法1: range(結束值)
for i in range(5):
  print(i)  # 輸出: 0, 1, 2, 3, 4

# 用法2: range(開始值, 結束值)
for i in range(1, 6):
  print(i)  # 輸出: 1, 2, 3, 4, 5

# 用法3: range(開始值, 結束值, 步長)
for i in range(0, 10, 2):
  print(i)  # 輸出: 0, 2, 4, 6, 8

🧮 範例:計算1到N的總和

請寫一個程式,計算從1加到使用者輸入的數字N。

# 你的程式碼在這裡
n = int(input("請輸入一個正整數N: "))
total = 0

# 提示:使用for迴圈
# for i in range(1, n + 1):
#     total += i

print(f"1到{n}的總和是: {total}")

💭 思考時間:

  • 如果輸入0或負數會發生什麼?
  • 可以用公式直接計算總和嗎?哪種方法更好呢?

🎮 遊戲道具清單範例:

  • 簡單的與容器搭配使用
treasure_items = ["金幣", "魔法石", "生命藥水", "神秘地圖", "寶劍"]

print("🎒 你的寶物清單:")
for i in range(len(treasure_items)):
  print(f"{i+1}. {treasure_items[i]}")

# 或者更簡潔的寫法
for e in treasure_items:
  print(f"{treasure_items.index(e)+1}. {e}")

# 使用enumerate()函式,執行效率更高
for index, item in enumerate(treasure_items, start=1):
  print(f"{index}. {item}")

break與continue的流程控制

這兩個關鍵字是迴圈的遙控器,讓你完全掌控程式流程!

🛑 break - 緊急煞車:

# 尋找特定寶物
treasures = ["銅幣", "銀幣", "金幣", "鑽石", "紅寶石"]

for treasure in treasures:
  print(f"發現了 {treasure}")
  if treasure == "金幣":
    print("找到金幣了!停止搜尋 🏆")
    break  # 立即跳出迴圈
  print("不是目標,繼續尋找...")
else:
  print("沒有找到金幣 😢")
print("搜尋結束!")

⏭️ continue - 跳過這回合:

# 只收集有價值的寶物
items = ["石頭", "金幣", "樹枝", "鑽石", "垃圾", "紅寶石"]

valuable_items = []
for item in items:
  if item in ["石頭", "樹枝", "垃圾"]:
    print(f"跳過 {item}")
    continue  # 跳過後續程式碼,進入下一次迴圈
  
  valuable_items.append(item)
  print(f"收集了 {item} ✨")

print(f"總共收集到: {valuable_items}")

巢狀迴圈基礎概念

  • 巢狀迴圈就像是「迴圈中的迴圈」
  • 處理二維資料的神器!

🗺️ 寶藏地圖搜索範例:

# 5x3的寶藏地圖
treasure_map = [
  ["🌱", "🌱", "💎", "🌱", "🌱"],
  ["🌱", "⚡", "🌱", "🏆", "🌱"],
  ["🌱", "🌱", "🌱", "🌱", "💰"]
]

print("🗺 搜索寶藏地圖...")
treasures_found = []

for row in range(len(treasure_map)):
  for col in range(len(treasure_map[row])):
    current_item = treasure_map[row][col]
    
    if current_item != "🌱":  # 不是草地
      print(f"在位置 ({row+1}, {col+1}) 發現: {current_item}")
      treasures_found.append((row+1, col+1, current_item))

print(f"\n🎉 總共發現 {len(treasures_found)} 個寶藏!")

📊 九九乘法表範例:

print("📚 九九乘法表")
print("=" * 25)

for i in range(1, 10):
  for j in range(1, 10):
    result = i * j
    print(f"{i}×{j}={result:2d}", end="  ")
  print()  # 換行

尋寶冒險遊戲實作

現在讓我們整合所有學過的迴圈技巧
打造一個簡單的尋寶遊戲!🎮

🎯 遊戲設計架構:while迴圈製作遊戲主循環

import random

print("🏴 歡迎來到尋寶冒險世界!")
player_name = input("請輸入你的冒險者名字: ")
print(f"歡迎,勇敢的 {player_name}!")

health = 100
score = 0
inventory = []
game_running = True

while game_running and health > 0:
  print(f"\n📊 === {player_name} 的狀態 ===")
  print(f"❤  生命值: {health}")
  print(f"⭐ 分數: {score}")
  print(f"🎒 背包: {inventory}")

  print("\n🌍 你來到了一個神秘區域...")
  events = ["寶箱", "怪物", "商人", "陷阱", "神秘泉水"]
  event = random.choice(events)

  if event == "寶箱":
    treasures = [("金幣", 50), ("銀幣", 25), ("鑽石", 200), ("紅寶石", 150), ("魔法書", 300), ("神秘藥水", 100)]
    treasure, value = random.choice(treasures)
    print(f"✨ 你發現了 {treasure}!獲得 {value} 分!")
    inventory.append(treasure)
    score += value

遭遇怪物

  elif event == "怪物":
    monsters = ["哥布林", "骷髏兵", "野狼", "黑暗法師"]
    monster = random.choice(monsters)
    print(f"⚔ 遭遇 {monster}!準備戰鬥!")
    for round_num in range(1, 4):
      print(f"\n🥊{round_num} 回合")
      print("1. 攻擊  2. 防守  3. 逃跑")
      choice = input("請選擇 (1-3): ")
      if choice == "1":
        damage = random.randint(15, 30)
        print(f"💥 你對 {monster} 造成 {damage} 點傷害!")
        if random.random() > 0.3:
          print(f"🎉 你擊敗了 {monster}!獲得經驗值!")
          score += 75
          break
      elif choice == "2":
        print("🛡 你選擇防守,減少傷害!")
        damage = random.randint(5, 15)
      else:
        print("😰 你成功逃脫了!")
        break
      health -= damage
      print(f"💔 你受到 {damage} 點傷害!")
      if health <= 0:
        print("💀 你被擊敗了!遊戲結束!")
        game_running = False
        break

遇到商人、陷阱與神秘泉水

  elif event == "商人":
    print("🛒 你遇到了一位商人,但他今天沒有帶任何商品。")

  elif event == "陷阱":
    damage = random.randint(10, 30)
    print(f"💣 你踩到了陷阱!損失 {damage} 點生命值!")
    health -= damage

  elif event == "神秘泉水":
    heal = random.randint(20, 50)
    print(f"💧 你發現了一個神秘泉水,恢復了 {heal} 點生命值!")
    health += heal

  choice = input("\n🤔 要繼續探險嗎?(y/n): ").lower()
  if choice == 'n':
    game_running = False
    print("感謝遊玩!下次見!👋")

計分系統

if health > 0:
  base_score = score
  health_bonus = health * 2
  inventory_bonus = len(inventory) * 25
  special_items = ["魔法書", "神秘藥水", "鑽石"]
  special_bonus = sum(100 for item in inventory if item in special_items)
  total_score = base_score + health_bonus + inventory_bonus + special_bonus

  print(f"\n🏆 === 最終計分 ===")
  print(f"基礎分數: {base_score}")
  print(f"生命值獎勵: {health_bonus}")
  print(f"道具獎勵: {inventory_bonus}")
  print(f"特殊道具獎勵: {special_bonus}")
  print(f"總分: {total_score}")

  if total_score >= 1500:
    rank = "傳奇尋寶大師 🏆"
  elif total_score >= 1000:
    rank = "專業探險家 ⭐"
  elif total_score >= 500:
    rank = "新手冒險者 🌟"
  else:
    rank = "初學者 🔰"

  print(f"\n🎖 你的冒險等級: {rank}")
  print("\n💾 遊戲記錄已保存!")
  print(f"玩家: {player_name}")
  print(f"分數: {total_score}")
  print(f"等級: {rank}")
  print(f"道具數量: {len(inventory)}")
  print(f"剩餘生命: {health}")

🧠 運算思維總整理

讓我們回顧今天學到的程式重複魔法:

🔄 迴圈的核心概念

迴圈類型 適用情況 範例
while 條件式重複 遊戲主循環、使用者輸入驗證
for 次數明確重複 處理清單、數據批次操作
巢狀迴圈 二維數據處理 地圖搜索、表格生成

🎮 流程控制技巧

  • break: 緊急停止迴圈(找到目標就停止)
  • continue: 跳過當次迴圈(跳過無效數據)
  • 條件判斷: 在迴圈中做決策

💡 程式設計思維

  1. 分解問題: 將複雜遊戲拆成小功能
  2. 重複利用: 用迴圈處理相似操作
  3. 狀態管理: 追蹤遊戲中的各種數據
  4. 使用者體驗: 提供清楚的互動介面

本週總結 🎉

恭喜你!今天我們一起掌握了程式重複的神奇力量:

✅ 今日成就解鎖

  • 🔄 while迴圈大師 - 製作條件式重複邏輯
  • 🎯 for迴圈專家 - 批次處理數據能力
  • 🚦 流程控制高手 - 靈活運用break與continue
  • 🎮 遊戲開發者 - 整合迴圈打造完整遊戲
  • 💾 系統設計師 - 實作計分與存檔功能

🌟 下週預告

下次我們將學習容器與資料結構,探索如何有效地儲存與操作資料!

🎯 持續練習建議

  • 嘗試改進尋寶遊戲的功能
  • 練習不同類型的迴圈應用
    • for
    • while
    • 巢狀迴圈
  • 結合條件判斷與迴圈
  • 思考如何用迴圈解決問題

記住:程式設計就是化繁為簡的藝術!要盡可能的簡化! 🐍✨

作業:尋寶冒險遊戲升級版

選擇適合你程度的作業來挑戰:

📝 選項一:基礎練習 (適合初學者)

任務:完成上述的簡化版尋寶遊戲

  • 基礎任務清單:
  1. 用while迴圈製作遊戲主循環
  2. 玩家可以選擇「探索」或「結束遊戲」
  3. 探索時隨機獲得道具(用random模組)
  4. 顯示玩家目前的道具清單
  5. 計算並顯示總分

import random

player_items = []
total_score = 0
items = ["金幣", "銀幣", "鑽石", "藥水"]
item_values = {"金幣": 10, "銀幣": 5, "鑽石": 50, "藥水": 20}

# 你的程式碼:
# while True:
#     choice = input("選擇行動 (1)探索 (2)查看背包 (3)結束: ")
#     if choice == "1":  # 探索邏輯
#     elif choice == "2":  # 顯示背包
#     elif choice == "3":  # 結束遊戲

🔧 選項二:進階應用 (有點挑戰性)

任務:功能完整的RPG尋寶系統

必須包含功能:

  1. 角色系統:生命值、等級、經驗值
  2. 戰鬥系統:與怪物戰鬥,使用break/continue控制流程
  3. 道具系統:不同類型道具有不同效果
  4. 地圖探索:用巢狀迴圈實作3x3地圖

額外成就項目:

  • 美觀的遊戲介面
  • 創意的遊戲機制
  • 良好的程式碼註解

🚀 選項三:創意發揮 (自由度高)

任務:自由創作迴圈應用專案

可選主題:

  1. 學習管理系統:用迴圈管理課程、作業、成績
  2. 個人理財工具:記帳、預算分析、投資計算
  3. 健身追蹤程式:運動記錄、卡路里計算
  4. 小遊戲合集:猜數字、井字棋、簡單撲克
  5. 數據分析工具:讀取CSV、統計分析、圖表生成

祝你遊玩程式愉快!🐍✨

-----------------------------------------

圖片放大特效

table樣式

![Alt1](../images/1200px-National_Taiwan_University_logo.svg.png)![Alt2](../images/Python-logo-notext.svg.png) <style scoped> img[alt="Alt1"]{ background: rgba(255, 255, 255, 0); position: absolute; top: 10%; left: 10%; /* transform: translate(-50%, -50%); */ width: 200px; /* 調整圖片寬度 */ height: auto; /* 保持原始比例 */ padding:0; margin:0; z-index: 1; } img[alt="Alt2"]{ background: rgba(255, 255, 255, 0); position: absolute; top: 10%; left: 75%; /* transform: translate(-50%, -50%); */ width: 200px; /* 調整圖片寬度 */ height: auto; /* 保持原始比例 */ padding:0; margin:0; z-index: 2; } </style>

- [選項一:基礎練習](#選項一基礎練習-適合初學者) - [選項二:進階應用](#選項二進階應用-有點挑戰性) - [選項三:創意發揮](#選項三創意發揮-自由度高)

--- #### 💡 生活範例 - 計算平均分數: ```python print("📊 計算學生的平均分數") # 初始化變數 total_score = 0 student_count = 0 # 使用while迴圈輸入分數 while True: score = input("請輸入學生分數 (輸入'q'結束): ") if score.lower() == 'q': # 結束輸入 break try: score = float(score) total_score += score student_count += 1 except ValueError: print("⚠️ 請輸入有效的數字!") # 計算平均分數 if student_count > 0: average_score = total_score / student_count print(f"學生總數: {student_count}") print(f"平均分數: {average_score:.2f}") else: print("未輸入任何分數!") ```

--- # 小練習 3 #### 🧮 練習題目:費氏數列生成器 請寫一個程式,生成指定數量的費氏數列。 ```python # 你的程式碼在這裡 n = int(input("請輸入要生成的費氏數列項數: ")) # 提示:使用while迴圈 # a, b = 0, 1 # count = 0 # while count < n: # print(a, end=" ") # a, b = b, a + b # count += 1 ``` #### 💭 思考時間: - 費氏數列的遞推公式是什麼? - 如果輸入0或負數會發生什麼?

```python # 你的程式碼在這裡 start = int(input("請輸入倒數開始的秒數: ")) # 提示:使用while迴圈 # while start > 0: # print(f"剩餘: {start} 秒") # start -= 1 # print("倒數結束!🎉") ```

--- # 小練習 2 #### 🎲 練習題目:寶物篩選系統 建立一個程式來篩選有價值的寶物: ```python all_items = ["石頭", "金幣", "樹枝", "銀幣", "垃圾", "鑽石", "破布", "紅寶石"] valuable_items = ["金幣", "銀幣", "鑽石", "紅寶石"] # 任務1:使用for迴圈找出所有有價值的物品 print("🔍 搜尋有價值的寶物...") my_treasures = [] # 你的程式碼: # for item in all_items: # if item in valuable_items: # my_treasures.append(item) # print(f"發現寶物: {item} ✨") # 任務2:計算寶物價值 values = {"金幣": 100, "銀幣": 50, "鑽石": 500, "紅寶石": 300} total_value = 0 # 你的程式碼: # for treasure in my_treasures: # total_value += values[treasure] print(f"總價值: {total_value} 金幣 💰") ```

# 尋寶冒險遊戲實作 現在讓我們整合所有學過的迴圈技巧,打造一個簡單的尋寶遊戲!🎮 --- #### 🎯 遊戲設計架構: ```python import random class TreasureHunter: def __init__(self): self.player_name = "" self.health = 100 self.score = 0 self.inventory = [] self.game_running = True def start_game(self): print("🏴‍☠️ 歡迎來到尋寶冒險世界!") self.player_name = input("請輸入你的冒險者名字: ") print(f"歡迎,勇敢的 {self.player_name}!") # 遊戲主循環 while self.game_running and self.health > 0: self.show_status() self.explore_area() if self.score >= 1000: print("🎉 恭喜!你已經成為傳奇尋寶獵人!") break def show_status(self): print(f"\n📊 === {self.player_name} 的狀態 ===") print(f"❤️ 生命值: {self.health}") print(f"⭐ 分數: {self.score}") print(f"🎒 背包: {self.inventory}") ``` --- # while迴圈製作遊戲主循環 使用while迴圈打造遊戲的核心邏輯: ```python def explore_area(self): print("\n🌍 你來到了一個神秘區域...") # 隨機事件列表 events = ["寶箱", "怪物", "商人", "陷阱", "神秘泉水"] event = random.choice(events) if event == "寶箱": self.find_treasure() elif event == "怪物": self.fight_monster() elif event == "商人": self.meet_merchant() elif event == "陷阱": self.encounter_trap() elif event == "神秘泉水": self.find_spring() # 詢問是否繼續冒險 choice = input("\n🤔 要繼續探險嗎?(y/n): ").lower() if choice == 'n': self.game_running = False print("感謝遊玩!下次見!👋") def find_treasure(self): treasures = [ ("金幣", 50), ("銀幣", 25), ("鑽石", 200), ("紅寶石", 150), ("魔法書", 300), ("神秘藥水", 100) ] treasure, value = random.choice(treasures) print(f"✨ 你發現了 {treasure}!獲得 {value} 分!") self.inventory.append(treasure) self.score += value ``` --- # for迴圈處理道具清單 使用for迴圈來管理遊戲中的各種物品和操作: ```python def fight_monster(self): monsters = ["哥布林", "骷髏兵", "野狼", "黑暗法師"] monster = random.choice(monsters) print(f"⚔️ 遭遇 {monster}!準備戰鬥!") # 戰鬥回合 for round_num in range(1, 4): print(f"\n🥊 第 {round_num} 回合") # 玩家可選擇的行動 actions = ["攻擊", "防守", "使用道具"] print("選擇你的行動:") for i, action in enumerate(actions, 1): print(f"{i}. {action}") choice = input("請選擇 (1-3): ") if choice == "1": # 攻擊 damage = random.randint(15, 30) print(f"💥 你對 {monster} 造成 {damage} 點傷害!") if random.random() > 0.3: # 70%機率勝利 print(f"🎉 你擊敗了 {monster}!獲得經驗值!") self.score += 75 return elif choice == "2": # 防守 print("🛡️ 你選擇防守,減少傷害!") damage = random.randint(5, 15) else: # 使用道具 self.use_item_in_battle() continue # 怪物反擊 self.health -= damage print(f"💔 你受到 {damage} 點傷害!") if self.health <= 0: print("💀 你被擊敗了!遊戲結束!") return print("😰 戰鬥結束,你成功逃脫了!") ``` --- # 計分系統與遊戲存檔 實作完整的計分系統和存檔功能: ```python def calculate_final_score(self): """計算最終分數""" base_score = self.score health_bonus = self.health * 2 # 生命值獎勵 inventory_bonus = len(self.inventory) * 25 # 道具獎勵 # 特殊道具額外獎勵 special_items = ["魔法書", "神秘藥水", "鑽石"] special_bonus = 0 for item in self.inventory: if item in special_items: special_bonus += 100 total_score = base_score + health_bonus + inventory_bonus + special_bonus print(f"\n🏆 === 最終計分 ===") print(f"基礎分數: {base_score}") print(f"生命值獎勵: {health_bonus}") print(f"道具獎勵: {inventory_bonus}") print(f"特殊道具獎勵: {special_bonus}") print(f"總分: {total_score}") return total_score def save_game_record(self): """儲存遊戲記錄""" final_score = self.calculate_final_score() # 判定等級 if final_score >= 1500: rank = "傳奇尋寶大師 🏆" elif final_score >= 1000: rank = "專業探險家 ⭐" elif final_score >= 500: rank = "新手冒險者 🌟" else: rank = "初學者 🔰" print(f"\n🎖️ 你的冒險等級: {rank}") # 簡單的「存檔」功能 game_record = { "玩家": self.player_name, "分數": final_score, "等級": rank, "道具數量": len(self.inventory), "剩餘生命": self.health } print("\n💾 遊戲記錄已保存!") for key, value in game_record.items(): print(f"{key}: {value}") # 啟動遊戲 if __name__ == "__main__": game = TreasureHunter() game.start_game() game.save_game_record() ``` --- #### 🎯 遊戲設計架構: ```python import random def start_game(): print("🏴‍☠️ 歡迎來到尋寶冒險世界!") player_name = input("請輸入你的冒險者名字: ") print(f"歡迎,勇敢的 {player_name}!") health = 100 score = 0 inventory = [] game_running = True while game_running and health > 0: show_status(player_name, health, score, inventory) health, score, inventory, game_running = explore_area(health, score, inventory, game_running) if score >= 1000: print("🎉 恭喜!你已經成為傳奇尋寶獵人!") break save_game_record(player_name, health, score, inventory) ``` --- ```python def show_status(player_name, health, score, inventory): print(f"\n📊 === {player_name} 的狀態 ===") print(f"❤️ 生命值: {health}") print(f"⭐ 分數: {score}") print(f"🎒 背包: {inventory}") def explore_area(health, score, inventory, game_running): print("\n🌍 你來到了一個神秘區域...") events = ["寶箱", "怪物", "商人", "陷阱", "神秘泉水"] event = random.choice(events) if event == "寶箱": score, inventory = find_treasure(score, inventory) elif event == "怪物": health, score = fight_monster(health, score) elif event == "商人": print("🛒 你遇到了一位商人,但他今天沒有帶任何商品。") elif event == "陷阱": health = encounter_trap(health) elif event == "神秘泉水": health = find_spring(health) choice = input("\n🤔 要繼續探險嗎?(y/n): ").lower() if choice == 'n': game_running = False print("感謝遊玩!下次見!👋") return health, score, inventory, game_running ``` --- ```python def find_treasure(score, inventory): treasures = [ ("金幣", 50), ("銀幣", 25), ("鑽石", 200), ("紅寶石", 150), ("魔法書", 300), ("神秘藥水", 100) ] treasure, value = random.choice(treasures) print(f"✨ 你發現了 {treasure}!獲得 {value} 分!") inventory.append(treasure) score += value return score, inventory ``` --- ```python def fight_monster(health, score): monsters = ["哥布林", "骷髏兵", "野狼", "黑暗法師"] monster = random.choice(monsters) print(f"⚔️ 遭遇 {monster}!準備戰鬥!") for round_num in range(1, 4): print(f"\n🥊 第 {round_num} 回合") actions = ["攻擊", "防守", "逃跑"] for i, action in enumerate(actions, 1): print(f"{i}. {action}") choice = input("請選擇 (1-3): ") if choice == "1": # 攻擊 damage = random.randint(15, 30) print(f"💥 你對 {monster} 造成 {damage} 點傷害!") if random.random() > 0.3: print(f"🎉 你擊敗了 {monster}!獲得經驗值!") score += 75 return health, score elif choice == "2": # 防守 print("🛡️ 你選擇防守,減少傷害!") damage = random.randint(5, 15) else: # 逃跑 print("😰 你成功逃脫了!") return health, score health -= damage print(f"💔 你受到 {damage} 點傷害!") if health <= 0: print("💀 你被擊敗了!遊戲結束!") return health, score print("😰 戰鬥結束,你成功逃脫了!") return health, score ``` --- ```python def encounter_trap(health): damage = random.randint(10, 30) print(f"💣 你踩到了陷阱!損失 {damage} 點生命值!") health -= damage return health def find_spring(health): heal = random.randint(20, 50) print(f"💧 你發現了一個神秘泉水,恢復了 {heal} 點生命值!") health += heal return health ``` --- ```python def save_game_record(player_name, health, score, inventory): base_score = score health_bonus = health * 2 inventory_bonus = len(inventory) * 25 special_items = ["魔法書", "神秘藥水", "鑽石"] special_bonus = sum(100 for item in inventory if item in special_items) total_score = base_score + health_bonus + inventory_bonus + special_bonus print(f"\n🏆 === 最終計分 ===") print(f"基礎分數: {base_score}") print(f"生命值獎勵: {health_bonus}") print(f"道具獎勵: {inventory_bonus}") print(f"特殊道具獎勵: {special_bonus}") print(f"總分: {total_score}") if total_score >= 1500: rank = "傳奇尋寶大師 🏆" elif total_score >= 1000: rank = "專業探險家 ⭐" elif total_score >= 500: rank = "新手冒險者 🌟" else: rank = "初學者 🔰" print(f"\n🎖️ 你的冒險等級: {rank}") print("\n💾 遊戲記錄已保存!") print(f"玩家: {player_name}") print(f"分數: {total_score}") print(f"等級: {rank}") print(f"道具數量: {len(inventory)}") print(f"剩餘生命: {health}") if __name__ == "__main__": start_game() ```

**提交要求:** - 程式碼檔案 (.py) - 執行截圖 - 簡短心得(100字內)

5. **存檔功能**:將遊戲狀態寫入檔案

**範例架構:** ```python class AdvancedTreasureHunter: def __init__(self): self.level = 1 self.exp = 0 self.health = 100 self.max_health = 100 # ... 其他屬性 def explore_map(self): # 3x3地圖探索 game_map = [ ["?", "?", "?"], ["?", "P", "?"], # P代表玩家位置 ["?", "?", "?"] ] # 你的實作... def battle_system(self): # 戰鬥系統實作 pass ```

**評分標準:** - **創意性** (30%):概念新穎有趣 - **技術實作** (40%):正確使用while/for/巢狀迴圈 - **實用性** (20%):真的有解決問題 - **程式品質** (10%):程式碼清晰、有註解

**提交格式:** - 完整程式碼 - 使用說明文件 - 功能展示影片或截圖 - 設計理念說明(300字內) **截止時間:下週上課前** ⏰ **提交方式:上傳至課程平台** 📤