study

[파이썬] 7강 행맨 게임(for문, while문, if else 조건문 등)

kmk_sweetlife 2024. 3. 25. 11:21
반응형

7강 요약

7강에서는 1~6강에서 배운 내용에 대해 100% 활용하여 '행맨'게임을 만드는 과제를 진행했다. (너무 어려웠다 ㅠㅠ)

if else 조건문, for/while 반복문을 비롯하여 random함수, import 모듈 등 다양한 문법과 개념을 익혔기 때문에 앞으로 이를 잘 활용하려면 다양한 실습과제를 진행해봐야 하는데 그 첫단추가 행맨 게임이다. 처음에는 순서도로 흐름을 파악한 후, 아주 단순한 방식으로 게임에 접근한 후 점차 로직을 세분화해나가는 방향으로 과제를 진행해서 이해하기 쉬웠다. 안젤라 선생님 짱...b

 

1. 순서도로 흐름 파악하기 (중요한 단계만 짚음) 

 

 

 

 

1) 게임에서 유추할 단어 무작위 추출

 

 

 

2) 무작위 추출된 단어의 알파벳 갯수만큼 언더바('_') 채우기 

(ex. _ _ _ _ _ _) 

 

3) 사용자로부터 문자 입력 받기

  3-1) 이미 입력한 문자면 다시 3)으로 리턴 

  3-2) 단어에 해당 문자가 존재한다면, 언더바를 해당 문자로 치환

  3-3) 단어에 해당 문자가 없다면, 행맨의 목숨이 하나씩 감소함

           (아스키아트 이용하여 목숨 상태 보여주기) 

 

 4) 게임 종료 여부 판단

   4-1) 목숨이 사라지기전 모든 빈칸('_')이 채워졌다면 사용자 승

   4-2) 빈칸이 남아있고, 행맨의 목숨이 끝났다면 사용자 패 

 

 

 

 

 

 

 

 

 

 

2. 단어 무작위로 추출 & 사용자로부터 입력받은 문자가 맞는지 확인

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)

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

for letter in chosen_word:
  if letter == guess:
    print("True")
  else:
    print("False")

 

3. 무작위로 추출된 단어의 문자 개수만큼 "_"를 채워넣고, 유추한 문자가 맞다면 "_" 대신 해당 문자를 채워넣는다. 

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

#TODO-1: - Create an empty List called display.
#For each letter in the chosen_word, add a "_" to 'display'.
#So if the chosen_word was "apple", display should be ["_", "_", "_", "_", "_"] with 5 "_" representing each letter to guess.

display = []
word_length = len(chosen_word)
for _ in range(word_length):
  display.append("_")
  
guess = input("Guess a letter: ").lower()

#TODO-2: - Loop through each position in the chosen_word;
#If the letter at that position matches 'guess' then reveal that letter in the display at that position.
#e.g. If the user guessed "p" and the chosen word was "apple", then display should be ["_", "p", "p", "_", "_"].

for position in range(word_length):
  letter = chosen_word[position]
  if letter == guess :
    display[position] +=letter

#TODO-3: - Print 'display' and you should see the guessed letter in the correct position and every other letter replace with "_".
#Hint - Don't worry about getting the user to guess the next letter. We'll tackle that in step 3.

print(display)

 

4. (여기서부터 어려워짐..) 빈칸이 모두 채워질때까지 게임을 지속한다. (while loop 활용)

#Step 3

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

#Create blanks
display = []
for _ in range(word_length):
    display += "_"

#TODO-1: - Use a while loop to let the user guess again. The loop should only stop once the user has guessed all the letters in the chosen_word and 'display' has no more blanks ("_"). Then you can tell the user they've won.

end_of_game = False

while not end_of_game:
  guess = input("Guess a letter: ").lower()
  for position in range(word_length):
      letter = chosen_word[position]
      print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
      if letter == guess:
          display[position] = letter
  
  print(display)

  if "_" not in display:
    end_of_game = True
    print("You win.")

 

5. 행맨의 목숨개수를 설정해두고, 한정된 횟수만큼만 게임이 진행되도록 설정

ㄴ 게임의 흥미를 돋우기 위해 아스키아트를 활용해 남은 목숨의 개수가 변할때마다 행맨의 상태를 보여줌 ㅋㅋ

#Step 4

import random

stages = ['''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========
''', '''
  +---+
  |   |
      |
      |
      |
      |
=========
''']

end_of_game = False
word_list = ["ardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
lives = 6

print(f'Pssst, the solution is {chosen_word}.')

display = []
for _ in range(word_length):
    display += "_"

while not end_of_game:
    guess = input("Guess a letter: ").lower()
    for position in range(word_length):
        letter = chosen_word[position]
        if letter == guess:
            display[position] = letter
    if guess not in chosen_word:
      lives -= 1
      if lives == 0:
        end_of_game = True
        print("You Lose")
    print(f"{' '.join(display)}")
    if "_" not in display:
        end_of_game = True
        print("You win.")
    print(stages[lives])

 

6. 유저 경험 개선

- 게임 시작 시 로고를 보여주거나, 이미 입력한 문자를 또 입력하는 패턴을 방지하는 등의 서비스 개선

import random
from hangman_art import stages, logo
from hangman_words import word_list
from replit import clear

print(logo)
game_is_finished = False
lives = len(stages) - 1

chosen_word = random.choice(word_list)
word_length = len(chosen_word)

display = []
for _ in range(word_length):
    display += "_"

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

    #Use the clear() function imported from replit to clear the output between guesses.
    clear()

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

    for position in range(word_length):
        letter = chosen_word[position]
        if letter == guess:
            display[position] = letter
    print(f"{' '.join(display)}")

    if guess not in chosen_word:
        print(f"You guessed {guess}, that's not in the word. You lose a life.")
        lives -= 1
        if lives == 0:
            game_is_finished = True
            print("You lose.")
    
    if not "_" in display:
        game_is_finished = True
        print("You win.")

    print(stages[lives])

 

! 느낀점

  • 위에 배운 개념들을 손에 익을때까지 제대로 숙지하고 있지 않으면 앞으로 진행될 강의들은 점점 더 따라가기 힘들것이라는 생각이 들었다. for문, while문, if/else 문을 실습할 수 있는 다른 사이트를 좀 찾아봐야겠다. 
  • 반복문이나 조건문을 실행하기 전에, 변수로 정의하고 시작하는 것이 중요하다. 마치 서비스를 기획할 때 또는 데이터베이스의 새로운 테이블이나 컬럼을 생성할때와 같은 이치다. 어떤 데이터가 특정한 조건에서 돌아가길 원한다면, 어디에서부터 시작하고 어디에서 끝내야 할지 지정해줘야 한다.