[파이썬] 행맨(hang man)

 

워드리스트에 정답을 미리 넣어두어야 작동합니다. 

워드리스트 중에 하나가 랜덤으로 나옵니다. 

챗GPT에게 단어리스트를 뽑아달라고 하면, 뽑아줍니다. 

예) 대한민국 초등학교 5학년 영어교과서에 나오는 영단어 100개

import random

# List of words for the game
word_list = ["america", "canada", "france", "germany", "japan", "korea", "australia", "england", "brazil", "india", "china", "russia", "italy", "spain", "mexico", "argentina"]


# Select a random word from the list
chosen_word = random.choice(word_list)

# Initialize variables
guessed_letters = []
max_attempts = 6
attempts = 0

# Create a display word with underscores for the unguessed letters
display_word = ["_" for letter in chosen_word]

def display_hangman(attempts):
    stages = [
        """
           --------
           |      |
           |
           |
           |
           |
        """,
        """
           --------
           |      |
           |      O
           |
           |
           |
        """,
        """
           --------
           |      |
           |      O
           |      |
           |
           |
        """,
        """
           --------
           |      |
           |      O
           |     /|
           |
           |
        """,
        """
           --------
           |      |
           |      O
           |     /|\\
           |
           |
        """,
        """
           --------
           |      |
           |      O
           |     /|\\
           |     /
           |
        """,
        """
           --------
           |      |
           |      O
           |     /|\\
           |     / \\
           |
        """
    ]
    return stages[attempts]

def print_display_word(display_word):
    print(" ".join(display_word))

print("Welcome to Hangman!")
while True:
    print(display_hangman(attempts))
    print_display_word(display_word)

    guess = input("Guess a letter: ").lower()

    if guess in guessed_letters:
        print("You already guessed that letter.")
    elif guess in chosen_word:
        for i in range(len(chosen_word)):
            if chosen_word[i] == guess:
                display_word[i] = guess
        guessed_letters.append(guess)
    else:
        guessed_letters.append(guess)
        attempts += 1

    if "_" not in display_word:
        print("Congratulations! You guessed the word: " + chosen_word)
        break

    if attempts >= max_attempts:
        print("You ran out of attempts. The word was: " + chosen_word)
        break
반응형