Python 絞刑員遊戲實現

使用 Python 建置並運行 Hangman 遊戲。探索字元集檢查、剩餘嘗試計數器和隱藏字串替換。

在編輯器中嘗試

概述

Hangman 是一款猜詞遊戲,可訓練開發人員處理使用者字串、可變字元清單和驗證循環。

引擎從預定義清單中隨機選擇一個單字。它向玩家呈現與單字長度相符的空格。每猜測一次,字母就會被揭示出來,或者剩餘錯誤的數量就會減少一。

在Python中,我們使用字元列表而不是不可變的字串來管理這個遊戲流程,允許快速就地揭示,同時追蹤先前猜測的字元以避免處罰。

程式碼和執行輸出

具有模擬會話輸入的標準命令列 Hangman 遊戲腳本。

import random

def play_hangman():
    word_bank = ["python", "compiler", "terminal", "debugger", "variable"]
    word = random.choice(word_bank)
    guessed_word = ["_"] * len(word)
    guessed_letters = set()
    attempts_remaining = 6
    
    print("Welcome to Hangman!")
    print(f"Word length: {' '.join(guessed_word)}")
    
    # Mocking guess inputs for deterministic run
    mock_guesses = ["e", "o", "a", "t", "r", "n", "i", "m", "p", "c", "l"]
    
    for guess in mock_guesses:
        if attempts_remaining <= 0 or "_" not in guessed_word:
            break
            
        print(f"\nGuessing letter: '{guess}'")
        if guess in guessed_letters:
            print("You already guessed that!")
            continue
            
        guessed_letters.add(guess)
        
        if guess in word:
            for idx, char in enumerate(word):
                if char == guess:
                    guessed_word[idx] = guess
            print(f"Correct! Word state: {' '.join(guessed_word)}")
        else:
            attempts_remaining -= 1
            print(f"Incorrect! Attempts remaining: {attempts_remaining}")
            
    if "_" not in guessed_word:
        print(f"\nCongratulations! You guessed the word '{word}'!")
    else:
        print(f"\nGame Over! The word was '{word}'.")

# Seed random to ensure output matches the word 'compiler'
random.seed(35)
play_hangman()
端子輸出
Welcome to Hangman!
Word length: _ _ _ _ _ _ _ _

Guessing letter: 'e'
Correct! Word state: _ _ _ _ _ _ e _

Guessing letter: 'o'
Correct! Word state: _ o _ _ _ _ e _

Guessing letter: 'a'
Incorrect! Attempts remaining: 5

Guessing letter: 't'
Incorrect! Attempts remaining: 4

Guessing letter: 'r'
Correct! Word state: _ o _ _ _ l e r
... (guesses continue)
Congratulations! You guessed the word 'compiler'!

逐步實施

  • 學習條件字串解析演算法
  • 使用集合進行狀態追蹤以進行獨特的歷史查找
  • 建構互動終端教育遊戲

常見問題解答

為什麼要用一組猜測的字母?

檢查 Python 集合中的成員資格平均需要 O(1) 時間,而清單則需要 O(n) 時間。這確保了在驗證先前的猜測時更快的查找。

如何加載更大的單字清單?

您可以使用 Python 的「open()」函數讀取文字檔案來載入數千個單詞,或使用 Web API 請求框架動態取得它們。

相關主題