Language/Python

[Section7] 게임 프로젝트(행맨)

HeeWorld 2025. 1. 14. 23:46

[udemy] Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복을 통해 학습하고 있습니다.

 

1단계: 무작위 단어 고르고 정답 확인하기

 

# TODO-1 - word_list에서 단어를 랜덤하게 선택하여 choose_word라는 변수에 할당 후 출력
# TODO-2 - 사용자에게 문자를 추측하고 변수에 답을 쓸 수 있도록 요청 (소문자 사용)
# TODO-3 - 사용자가 추측한 글자가 선택한 단어의 글자 중 하나인지 확인하고 맞다면 "Right", 틀리다면 "Wrong"을 출력

 

TODO-1 [Code]

# TODO-1

import random

word_list = ["aardvark", "baboon", "camel"]

choose_word = ""

for word in range(1):
    choose_word += random.choice(word_list)

print(choose_word)

# 강사님 코드

chosen_word = random.choice(word_list)
print(chosen_word)

 

→ for문과 range를 사용해 랜덤하게 단어 하나가 choose_word에 들어가 출력되게 만듦.

 

TODO-2 [Code]

# TODO-1

import random

word_list = ["aardvark", "baboon", "camel"]

choose_word = ""

for word in range(1):
    choose_word += random.choice(word_list)

print(choose_word)

# TODO-2

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

 

→ guess라는 변수를 만들어 사용자에게 문자 하나를 받게 만듦(받는 문자는 다 소문자가 되게함).

 

TODO-3 [Code]

# TODO-1

import random

word_list = ["aardvark", "baboon", "camel"]

choose_word = ""

for word in range(1):
    choose_word += random.choice(word_list)

print(choose_word)

# TODO-2

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

# TODO-3

for letter in choose_word:
    if letter == guess:
        print("Right!")
    else:
        print("Wrong!")

 

→ 사용자에게 받은 문자 변수와 랜덤으로 선택된 단어들을 하나씩 letter에 넣어 비교하여 True, False 구문함.

 

 

2단계: 빈칸을 맞춘 글자로 바꾸기

 

# TODO-4: 선택된 단어와 동일한 수의 _를 만들기

# TODO-5: 사용자가 사용한 단어를 알맞게 배치하고 나머지는 _가 되도록 만들기

 

TODO-4 [Code]

# TODO-1

import random

word_list = ["aardvark", "baboon", "camel"]

choose_word = ""

for word in range(1):
    choose_word += random.choice(word_list)

print(choose_word)

# TODO-4

placeholder = ""

for word in chosen_word:
    placeholder += "_"

print(placeholder)

# TODO-2

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

# TODO-3

for letter in choose_word:
    if letter == guess:
        print("Right!")
    else:
        print("Wrong!")

 

→ placeholder라는 변수를 하나 만들어서 랜덤으로 선택된 단어만큼 _(언더바)를 만들어 출력함.

 

TODO-5 [Code]

# TODO-1

import random

word_list = ["aardvark", "baboon", "camel"]

choose_word = ""

for word in range(1):
    choose_word += random.choice(word_list)

print(choose_word)

# TODO-4

placeholder = ""

for word in chosen_word:
    placeholder += "_"

print(placeholder)

# TODO-2

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

# TODO-(3)5

display = ""

for letter in choose_word:
    if letter == guess:
        display += letter
    else:
        display += "_"
        
print(display)

 

→ display라는 변수를 만들어 랜덤 단어를 하나씩 for문으로 돌려 letter와 guess가 True라면 display 변수에 해당 단어를 저장하고, False라면 _를 저장하게 만듦.

 

 

3단계: 플레이어가 이겼는지 확인하기

 

# TODO-6: While을 사용하여 사용자가 단어를 다시 추측할 수 있도록 만들기

# TODO-7: for문을 업데이트하여 문자를 맞췄을 때마다 이전에 맞춘 문자와 새로운 문자 모두 출력되도록 만들기

 

TODO-6/7 [Code]

import random
word_list = ["aardvark", "baboon", "camel"]

chosen_word = random.choice(word_list)
print(chosen_word)

placeholder = ""
word_length = len(chosen_word)
for position in range(word_length):
    placeholder += "_"
print(placeholder)

# TODO 6/7

game_over = False
new_letter = []

while not game_over:
    guess = input("Guess a letter: ").lower()
    display = ""

    for letter in chosen_word:
        if letter == guess:
            display += letter
            new_letter.append(letter)
        elif letter in new_letter:
            display += letter
        else:
            display += "_"

    print(display)

    if "_" not in display:
        game_over = True
        print("You Win.")

 

→ game_over라는 변수를 만들고, new_letter라는 리스트 형태의 변수를 새로 만듦.

- while문을 사용하여 game_over가 아닌 경우 문자를 받는 걸로 시작함.

- for문을 사용해서 랜덤 단어만큼 반복하고, 만약 단어에 있는 문자와 입력한 문자가 같으면 display 변수에 문자를 추가하고, new_letter 변수에 문자를 추가함.

- 그 다음 단어에 있는 문자가 new_letter 변수에 있다면, display 변수에 letter를 추가하고, 아닌 경우 "_"를 추가함.

- 마지막으로 만약 display에 _가 없다면, game_over는 True로 바꾸고 "You Win." 출력하며 while문이 끝남.

 

* game_over라는 변수 없이 while을 True 또는 not False로 하면 진짜 무한 루프에 빠져버림.

 

 

4단계: 플레이어의 남은 목숨 세기

 

# TODO-8: 남은 목숨을 확인하기 위한 lives라는 변수를 만들기 (생명은 6개)

# TODO-9: 만약 사용자가 추측한 글자가 랜덤으로 선택된 단어에 포함되지 않을 경우 목숨을 하나 줄이고, 목숨이 0이 되면 게임이 멈추고 "You lose."를 출력하게 만들기

# TODO-10: stages에서 행맨 ASCII 그림이 출력되도록 만들기(현재 사용자가 가지고 있는 목숨과 동일)

 

TODO-8 [Code]

# TODO-8

lives = 6

 

→ while문 밖에 lives라는 변수를 만들어줌.

 

TODO-9 [Code]

# TODO-9

    if guess not in chosen_word:
        lives -= 1
        if lives == 0:
            game_over = True
            print("You lose.")

 

→ 기존 if문에 추가하면 if문이 굉장히 지저분해질 수 있으니 별도의 if 문으로 빼서 작성함.

- guess로 받은 문자가 랜덤 단어에 들어있지 않으면 lives(목숨)을 하나씩 빼고, 만약 lives(목숨)이 0이되면 게임이 끝나게함.

 

TODO-10 [Code]

# TODO-10

print(stages[lives])

 

→ 강사님이 친절하시게 행맨 그림을 lives와 맞춰서 해놓으셔서 그냥 print로 목숨 개수에 맞춰 그림이 출력되게 하면 됨.

 

 

5단계: 유저 경험 개선시키기

 

# TODO-11: hanman_words.py의 word_list를 사용하여 단어 목록을 업데이트 

# TODO-12: hanman_art.py를 사용하여 코드 업데이트

# TODO-13: hanman_art.py에서 로고를 가져와 게임 시작 시 출력하기

# TODO-14: 사용자가 이미 추측한 문자를 입력하면, '이미 추측한 문자이다' 같은 말을 넣어주기

# TODO-15: 사용자가 추측한 문자가 랜덤 단어에 없는 문자이면 '해당 문자는 단어에 없습니다' 같은 말을 넣어주기

# TODO-16: 사용자의 목숨이 몇 개 남았는지 알려주기

# TODO-17: 목숨을 다 잃었을 때, 랜덤 단어가 무엇이었는지 알려주기

 

TODO-11 [Code]

# TODO-1: - Update the word list to use the 'word_list' from hangman_words.py

import hangman_words

word_list = hangman_words.word_list


# 강사님 Code

from hanman_words import word_list

 

TODO-12 [Code]

# TODO-2: - Update the code below to use the stages List from the file hangman_art.py

import hangman_art

    print(hangman_art.stages[lives])
    
# 강사님 Code

from hangman_art import stages

 

TODO-13 [Code]

# TODO-3: - Import the logo from hangman_art.py and print it at the start of the game.

print(hangman_art.logo)


# 강사님 Code

from hangman_art import stages, logo

print(logo)

 

TODO-14 [Code]

    # TODO-4: - If the user has entered a letter they've already guessed, print the letter and let them know.

    if guess in correct_letters:
        print(f"You've already guessed {guess}.")

 

TODO-15 [Code]

    # TODO-5: - If the letter is not in the chosen_word, print out the letter and let them know it's not in the word.
    #  e.g. You guessed d, that's not in the word. You lose a life.

    if guess not in chosen_word:
        print("That's not in the word. You lose a life.")

 

TODO-16 [Code]

# TODO-6: - Update the code below to tell the user how many lives they have left.
    print(f"**************************** {lives} LIVES LEFT****************************")

 

TODO-17 [Code]

# TODO 7: - Update the print statement below to give the user the correct word they were trying to guess.
            print(f"***********************YOU LOSE**********************\n The word is {chosen_word}.")

 

 

[전체 Code]

import random
import hangman_words
import hangman_art

word_list = hangman_words.word_list

lives = 6

print(hangman_art.logo)

chosen_word = random.choice(word_list)
print(chosen_word)

placeholder = ""
word_length = len(chosen_word)
for position in range(word_length):
    placeholder += "_"
print("Word to guess: " + placeholder)

game_over = False
correct_letters = []

while not game_over:
   
    print(f"**************************** {lives} LIVES LEFT****************************")
    guess = input("Guess a letter: ").lower()


    if guess in correct_letters:
        print(f"You've already guessed {guess}.")

    display = ""

    for letter in chosen_word:
        if letter == guess:
            display += letter
            correct_letters.append(guess)
        elif letter in correct_letters:
            display += letter
        else:
            display += "_"

    print("Word to guess: " + display)
    

    if guess not in chosen_word:
        print("That's not in the word. You lose a life.")

    if guess not in chosen_word:
        lives -= 1

        if lives == 0:
            game_over = True
          
            print(f"***********************YOU LOSE**********************\n The word is {chosen_word}.")

    if "_" not in display:
        game_over = True
        print("****************************YOU WIN****************************")

    
    print(hangman_art.stages[lives])

 

 

p.s 이번에 진짜 재미있게 실습함 🫶🏻 오늘을 넘기고 게시글 쓸 뻔했는데 00시 전에 완료