Python 행맨 게임 구현

Python으로 Hangman 게임을 빌드하고 실행해 보세요. 문자 집합 검사, 남은 시도 횟수 카운터, 숨겨진 단어 문자열 교체를 살펴보세요.

에디터에서 사용해 보세요

개요

Hangman은 사용자 문자열, 변경 가능한 문자 목록 및 유효성 검사 루프를 처리하는 방법을 개발자에게 교육하는 단어 추측 게임입니다.

엔진은 미리 정의된 목록에서 임의의 단어를 선택합니다. 플레이어에게 단어 길이에 맞는 공백을 제공합니다. 추측할 때마다 문자가 드러나거나 남은 오류 수가 1씩 감소합니다.

Python에서는 불변 문자열 대신 문자 목록을 사용하여 이 게임 흐름을 관리하므로 페널티를 피하기 위해 이전에 추측한 문자를 추적하는 동시에 빠른 내부 표시가 가능합니다.

코드 및 실행 출력

모의 세션 입력이 포함된 표준 명령줄 행맨 게임 스크립트입니다.

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()` 함수를 사용하여 텍스트 파일에서 읽어 수천 개의 단어를 로드하거나 웹 API 요청 프레임워크를 사용하여 동적으로 가져올 수 있습니다.

관련 주제