> 백엔드 개발 > 파이썬 튜토리얼 > Python으로 행맨 게임을 만드는 방법: 단계별 가이드

Python으로 행맨 게임을 만드는 방법: 단계별 가이드

Patricia Arquette
풀어 주다: 2024-10-04 06:09:29
원래의
1017명이 탐색했습니다.

How to Build a Hangman Game in Python: A Step-by-Step Guide

Hangman is a classic word-guessing game that’s fun and a great project for beginner programmers.

In this article, we’ll learn how to build a simple version of the Hangman game in Python.

By the end, you'll understand how to use Python’s basic control structures, functions, and lists to create this game.


What is Hangman?

The goal of Hangman is to guess a secret word by suggesting letters one at a time.

The player can make only a limited number of incorrect guesses before the game ends.

For each incorrect guess, a part of the "hangman" figure is drawn, and if the full figure is drawn before the word is guessed, the player loses.

Let’s break this down and build the game step by step.


Step 1: Plan the Game

Let's plan the game and its key features:

  • The game randomly selects a word.
  • The player guesses one letter at a time.
  • The player has a limited number of incorrect guesses.
  • The game displays the word with the correctly guessed letters and blanks for the remaining letters.

The game will have the following components:

  • Word selection
  • Player input (guess)
  • Update the display of the word
  • Track the number of incorrect guesses

Step 2: Import Required Libraries

We'll use the random module to randomly select a word from a list.


import random


로그인 후 복사

Step 3: Define the Word List

Next, define a list of words that the game will randomly choose from.

You can add more words to make the game more interesting.


word_list = ['python', 'java', 'hangman', 'programming', 'computer']


로그인 후 복사

Step 4: Define Functions for the Game

Function 1: Randomly Select a Word

We need a function to randomly pick a word from our word list.


def get_random_word(word_list):
    return random.choice(word_list)


로그인 후 복사

Function 2: Display the Current State of the Word

As the player guesses letters, we need to show the correctly guessed letters and placeholders (_) for the unguessed letters.


def display_word(word, guessed_letters):
    display = ''
    for letter in word:
        if letter in guessed_letters:
            display += letter + ' '
        else:
            display += '_ '
    return display.strip()


로그인 후 복사

Function 3: Check if the Player Won

This function checks whether all letters of the word have been guessed.


def is_word_guessed(word, guessed_letters):
    for letter in word:
        if letter not in guessed_letters:
            return False
    return True


로그인 후 복사

Function 4: Display Hangman

To display a hangman figure in a text-based game, you can use ASCII art to represent the different stages of the hangman.


def display_hangman(wrong_guesses):
    stages = [
        """
           -----
           |   |
           O   |
          /|\\  |
          / \\  |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
          /|\\  |
          /    |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
          /|\\  |
               |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
          /|   |
               |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
           |   |
               |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
               |
               |
               |
        --------
        """,
        """
           -----
           |   |
               |
               |
               |
               |
        --------
        """
    ]
    # Reverse the list to display the stages in the correct order
    stages.reverse()
    return stages[wrong_guesses]


로그인 후 복사

Step 5: The Main Game Loop

Now we can put together the main loop of the game. This loop will:

  • Keep track of the guessed letters and incorrect guesses.
  • Allow the player to input guesses.
  • Update the game state based on the guess.
  • End the game when the player wins or loses.

Complete Code Example:


import random


# Function to get a random word from the list
def get_random_word(word_list):
    return random.choice(word_list)


# Function to display the current state of the word
def display_word(word, guessed_letters):
    display = ''
    for letter in word:
        if letter in guessed_letters:
            display += letter + ' '
        else:
            display += '_ '
    return display.strip()


# Function to check if the word has been guessed
def is_word_guessed(word, guessed_letters):
    for letter in word:
        if letter not in guessed_letters:
            return False
    return True


# Function to display the hangman figure
def display_hangman(wrong_guesses):
    stages = [
        """
           -----
           |   |
           O   |
          /|\\  |
          / \\  |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
          /|\\  |
          /    |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
          /|\\  |
               |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
          /|   |
               |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
           |   |
               |
               |
        --------
        """,
        """
           -----
           |   |
           O   |
               |
               |
               |
        --------
        """,
        """
           -----
           |   |
               |
               |
               |
               |
        --------
        """
    ]
    # Reverse the list to display the stages in the correct order
    stages.reverse()
    return stages[wrong_guesses]


# Main function to play the game
def play_hangman():
    word_list = ['python', 'java', 'hangman', 'programming', 'computer']
    word = get_random_word(word_list)
    guessed_letters = []
    attempts = 6
    wrong_guesses = 0

    print("Welcome to Hangman!")
    print("Guess the word!")

    # Main game loop
    while wrong_guesses < attempts:
        print(display_hangman(wrong_guesses))
        print(display_word(word, guessed_letters))
        guess = input("Enter a letter: ").lower()

        # Check if the guess is valid
        if len(guess) != 1 or not guess.isalpha():
            print("Please enter a single letter.")
            continue

        # Check if the letter has already been guessed
        if guess in guessed_letters:
            print("You have already guessed that letter.")
            continue

        guessed_letters.append(guess)

        # Check if the guess is in the word
        if guess in word:
            print(f"Good guess! {guess} is in the word.")
        else:
            wrong_guesses += 1
            print(f"Sorry, {guess} is not in the word.")
            print(f"You have {attempts - wrong_guesses} attempts left.")

        # Check if the word is fully guessed
        if is_word_guessed(word, guessed_letters):
            print(f"Congratulations! You've guessed the word: {word}")
            break
    else:
        print(display_hangman(wrong_guesses))
        print(f"Game over! The word was: {word}")


# Run the game
if __name__ == "__main__":
    play_hangman()


로그인 후 복사

Explanation

  • get_random_word(): Randomly selects a word from the list of words.
  • display_word(): Creates a string that represents the current state of the word, showing the correctly guessed letters and placeholders for unguessed ones.
  • is_word_guessed(): Checks if the player has guessed all the letters in the word.
  • display_hangman(wrong_guesses): This function takes the number of incorrect guesses as an argument and returns the corresponding ASCII art for that stage.
  • play_hangman(): The main function that controls the game. It handles user input, keeps track of the player's guesses, and determines if the player has won or lost.

Key Variables:

  • guessed_letters: A list to store the letters that the player has guessed.
  • wrong_guesses: Tracks how many incorrect guesses the player has made. attempts: The maximum number of incorrect guesses allowed.
  • stages: This list contains ASCII art representations of the hangman figure at different stages of completion. Each stage corresponds to a different number of incorrect guesses.

Step 6: Running the Game

To run the game, simply execute the Python script, assuming you created a file main.py:


python main.py


로그인 후 복사

The game will prompt you to enter letters, and it will display the word with correctly guessed letters as you progress.

If you run out of attempts, the game ends, and you lose, like this:


           -----
           |   |
           O   |
          /|\  |
          / \  |
               |
        --------

Game over! The word was: programming


로그인 후 복사

If you guess the word correctly, you win, like this:


           -----
           |   |
               |
               |
               |
               |
        --------

j a _ a
Enter a letter: v
Good guess! v is in the word.
Congratulations! You've guessed the word: java



로그인 후 복사

Conclusion

This simple Hangman game demonstrates the use of control structures, functions, lists, and basic input/output in Python.

As you build this project, you can add more features such as:

  • Ajout de catégories de mots.
  • Donner des conseils.
  • Ajout d'un système de notation.

C'est un excellent projet à développer à mesure que vous apprenez des concepts Python plus avancés.

위 내용은 Python으로 행맨 게임을 만드는 방법: 단계별 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿