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 请求框架动态获取它们。

相关主题