《笨辦法學 python3》系列練習計劃——35.分支和函數

題目

我們已經學會了 if 語句、函數還有列表。現在我們需要搞清楚本題代碼實現的是什麼功能。

加分練習

  1. 把這個遊戲的地圖畫出來,把自己的路線也畫出來。
  2. 改正你所有的錯誤,包括拼寫錯誤。
  3. 爲不懂的地方寫註解。
  4. 爲遊戲添加更多元素。通過怎樣得方式可以簡化並且擴展遊戲的功能呢?
  5. 這個 gold_room 遊戲使用了奇怪的方式讓你鍵入一個數字。這種方式會導致什麼樣的 bug ?你可以用比檢查 0、1 更好的方式判斷輸入是否是數字嗎? int() 這個函數可以給你一些頭緒。

我的答案

35.0 基礎練習 + 35.2除錯 + 35.3 註解

# sys.exit 用於結束程序
from sys import exit

# 進入黃金房間後的邏輯
def gold_room():
    print("This room is full of gold. How much do you take?")

    # 如果輸入不包含 0 或 1 則死
    next = input("> ")
    if "0" in next or "1" in next:
        how_much = int(next)
    else:
        dead("Man, learn to type a number.")

    # 如果輸入的數字大於等於 50 則死
    if how_much < 50:
        print("Nice, you're not greedy, you  win!")
        exit(0)
    else:
        dead("You greedy bastard!")

# 實現熊房間的邏輯
def bear_room():
    print("There is a bear hear.")
    print("The bear has a bunch of honey.")
    print("The fat bear is in front of another door.")
    print("How are you going to move the bear?")
    bear_moved = False

    # 如果熊離開後直接開門就用不到 while 循環了.
    while True:
        next = input("> ")

        if next == "take honey":
            dead("The bear looks at you then slaps your face off.")
        elif next == "taunt bear" and not bear_moved:
            print("The bear has moved from the door. You can go through it now.")
            bear_moved = True
        elif next == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif next == "open door" and bear_moved:
            gold_room()
        else:
            print("I got no idea what that means.")

# 惡魔房邏輯
def cthulhu_room():
    print("Here you see the great evil Cthulhu.")
    print("He, it, whatever stares at you and you go insane.")
    print("Do you flee your life or eat your head?")

    next = input("> ")

    # 二選一,否則惡魔放循環
    if "flee" in next:
        start()
    elif "head" in next:
        dead("Well that was tasty!")
    else:
        cthulhu_room()

# 慘死函數
def dead(why):
    print(why, "Good job")
    exit(0)

# 啓動函數
def start():
    print("You are in a dark room.")
    print("There is a door to your right and left.")
    print("Which one do you take?")

    next = input("> ")

    if next == "left":
        bear_room()
    elif next == "right":
        cthulhu_roome()
    else:
        dead("You stumble around the room until you starve.")

# 開始遊戲
start()

這裏寫圖片描述

目測這款遊戲想打通關可不容易,讓我們來些攻略吧

35.1 遊戲地圖(攻略)

我發現自己似乎不太擅長畫流程圖啊
這裏寫圖片描述

35.4 添加元素

比較方便的方法還是想辦法寫函數吧,不過因爲文本量比大所以感覺仍然不是很方便。

35.5 gold_room 的 bug

可以直接改這樣

    next = input("> ")
    how_much = int(next)

不過如果 next 不是數字文本的話就會出錯,不知道在當前知識進度下有沒有其他好辦法。

返回目錄

《笨辦法學 python3》系列練習計劃——目錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章