Python ハングマン ゲームの実装

Python で Hangman ゲームを構築して実行します。文字セットのチェック、残りの試行カウンタ、および隠し単語文字列の置換を調べます。

エディターで試してみる

概要

Hangman は、ユーザー文字列、可変文字リスト、および検証ループの処理について開発者を訓練する単語推測ゲームです。

エンジンは、事前定義されたリストからランダムな単語を選択します。単語の長さに一致する空白スペースがプレーヤーに表示されます。推測するたびに文字が明らかになるか、残りの間違いの数が 1 つ減ります。

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 リクエスト フレームワークを使用して動的に取得することもできます。

関連トピック