我正在學習 Python 并決定升級一個版本的 hangman 游戲,該游戲在我觀看的其中一門課程中用作示例,代碼如下所示:import randomword_dictionary = { 1: "mouse", 2: "house", 3: "show", 4: "see", 5: "leave", 6: "shower", 7: "showcase", 8: "coding", 9: "elephant", 10: "apartment",}random_number = random.randint(1, 10)random_word = word_dictionary[random_number]secret_word = random_wordword_len = len(secret_word)guess = Nonetip = 0tip_num = Nonetip_previous = Nonetip_position = Nonetip_model_formula = "_"*word_lentip_model_list = list(tip_model_formula)send_tip = Noneprint("Word has", word_len, " letters")while guess != secret_word: guess = input("Enter your guess: ") if guess != secret_word: print("Wrong answer! Try again!") tip += 1 if tip == 5: tip_num = random.randint(0, word_len) tip_position = secret_word[tip_num] tip_model_list[tip_num] = tip_position send_tip = "".join(tip_model_list) tip_previous = tip_num print("here's a tip:\n" + send_tip) if tip == 10: tip_num = random.randint(0, word_len) while tip_num == tip_previous: tip_num = random.randint(0, word_len) tip_position = secret_word[tip_num] tip_model_list[tip_num] = tip_position send_tip = "".join(tip_model_list) tip_previous = tip_num print("here's a tip:\n" + send_tip)(這樣做是從字典中隨機選擇一個單詞作為秘密單詞,讓玩家對其進行猜測,每嘗試 5 次,玩家獲得 1 個小費,即單詞的一個字母,嘗試 16 次后,您輸了并且必須重新啟動)。我不知道為什么會隨機發生這種情況,并且一直試圖找出一個小時但沒有成功。感謝您提前提供幫助。
1 回答

猛跑小豬
TA貢獻1858條經驗 獲得超8個贊
你的錯誤在這里:
tip_num = random.randint(0, word_len) tip_position = secret_word[tip_num]
randint
返回其第一個和第二個參數之間的數字,包括兩個。這意味著它可以返回 的結果word_len
,這是 的結束后的結果secret_word
。
添加回答
舉報
0/150
提交
取消