
행맨 게임 플레이하는 곳 : hangmanwordgame.com
순서도를 통해 복잡한 문제를 단순하게 만들기
🔍 유의 사항
- 리스트에 관한 정보 : Google for Education > Python Lists
- 랜덤으로 골라진 단어는 변수 chosen_word에 저장
- 사용자가 추측한 글자 letter는 변수 guess에 저장
- guess가 chosen_word의 각 글자와 일치하는지 하나씩 확인
- 출력한 결과물의 경우 리스트에서 랜덤으로 골라진 단어는 "baboon" 임을 알 수 있음
⌨️ 작성한 코드
#Step 1
word_list = ["aardvark", "baboon", "camel"]
#TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word.
import random
chosen_word = random.choice(word_list)
#TODO-2 - Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowercase.
guess = input("Guess a letter : ").lower()
#TODO-3 - Check if the letter the user guessed (guess) is one of the letters in the chosen_word.
for letter in chosen_word:
if letter == guess:
print("right")
else:
print("wrong")
🔍 유의 사항
- chosen_word의 글자 수만큼의 빈칸("_")을 리스트 display로 생성
- guess가 chosen_word의 각 글자와 일치하는지 하나씩 확인해서
- 일치한다면, 빈칸을 guess로 변경
- 불일치한다면, 빈칸을 그대로 둠
- 테스팅 코드는 chosen_word가 무엇인지 출력 → 편하게 디버그하기 위한 용도
⌨️ 작성한 코드
#Step 2
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 = []
for letter in chosen_word:
display.append("_")
print(display)
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", "_", "_"].
i = 0
for letter in chosen_word:
if letter == guess:
display[i] = letter
i += 1
else:
i += 1
#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)
🖍️ 답안
#TODO-1
display = []
word_length = len(chosen_word)
for _ in range(len(chosen_word)):
display += "_"
print(display)
guess = input("Guess a letter: ").lower()
#TODO-2
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
🔍 유의 사항
- 유저가 모든 단어를 맞출 때까지(display 리스트에 빈칸이 없어질 때까지) while문으로 글자 맞추기 반복
- 오답에 대한 조치는 다음 단계에서
- not 연산자 활용
- in 연산자 활용
valueincollection- 특정 요소가 리스트 안에 있는지 확인할 때 사용 가능
- True/False 값 반환
⌨️ 작성한 코드
#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.
while "_" in display:
guess = input("Guess a letter: ").lower()
#Check guessed letter
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)
print("You win!")
🖍️ 답안
#TODO-1
end_of_game = False
while not end_of_game:
guess = input("Guess a letter: ").lower()
#Check guessed letter
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)
#Check if there are no more "_" left in 'display'. Then all letters have been guessed.
if "_" not in display:
end_of_game = True
print("You win.")
🔍 유의 사항
- 행맨의 목숨은 변수 lives에 저장되며, 초기값은 6
- 리스트 stages에 남은 목숨에 따른 아스키 아트가 문자열로 저장됨
- 틀린 글자를 입력할 때마다 알맞은 아스키 아트를 출력해야 함
- 이기는 경우 뿐만 아니라 지는 경우(lives = 0) 또한 종료 조건으로 넣어야 함
- 플로우 차트
⌨️ 작성한 코드
#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)
#TODO-1: - Create a variable called 'lives' to keep track of the number of lives left.
#Set 'lives' to equal 6.
lives = 6
#Testing code
print(f'Pssst, the solution is {chosen_word}.')
#Create blanks
display = []
for _ in range(word_length):
display += "_"
while not end_of_game:
guess = input("Guess a letter: ").lower()
#Check guessed letter
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
#TODO-2: - If guess is not a letter in the chosen_word,
#Then reduce 'lives' by 1.
#If lives goes down to 0 then the game should stop and it should print "You lose."
if guess not in chosen_word:
lives -= 1
if lives == 0:
end_of_game = True
print("You lose.")
#Join all the elements in the list and turn it into a String.
print(f"{' '.join(display)}")
#Check if user has got all letters.
if "_" not in display:
end_of_game = True
print("You win.")
#TODO-3: - print the ASCII art from 'stages' that corresponds to the current number of 'lives' the user has remaining.
print(stages[lives])
[ 출력 결과 ]
Pssst, the solution is baboon.
Guess a letter: q
_ _ _ _ _ _
+---+
| |
O |
|
|
|
=========
Guess a letter: w
_ _ _ _ _ _
+---+
| |
O |
| |
|
|
=========
Guess a letter: e
_ _ _ _ _ _
+---+
| |
O |
/| |
|
|
=========
Guess a letter: r
_ _ _ _ _ _
+---+
| |
O |
/|\ |
|
|
=========
Guess a letter: t
_ _ _ _ _ _
+---+
| |
O |
/|\ |
/ |
|
=========
Guess a letter: y
You lose.
_ _ _ _ _ _
+---+
| |
O |
/|\ |
/ \ |
|
=========
🔍 유의 사항
- 복잡하거나 긴 코드를 따로 다른 파일에 저장
- 📄 hangman_words.py 의 word_list 에 많은 양의 단어 저장
- 방법1 (파일 전체를 import)
가져오기 :importhangman_words
사용하기 :hangman_words.word_list- 방법2 (파일에서 필요한 것만 import)
가져오기 :fromhangman_wordsimportword_list
사용하기 :word_list- 📄 hangman_art.py 에 stages와 게임 로고의 아스키 아트 저장
fromhangman_artimportlogo, stages- 유저 편의성 개선
- 이미 입력한 글자를 또 입력했을 경우, 이미 시도했던 글자라고 알려주기
- chosen_word에 없는 글자를 입력했을 경우, 단어에 들어있지 않은 글자라고 알려주기
- from replit import clear : replit 모듈의 clear()
- 입력할 때마다 계속 밑으로 스크롤하면서 찾지 않아도 되도록 개선하기
- 글자를 입력할 때마다 콘솔창에 있던 이전 내용이 초기화됨
📄 hangman_words.py
word_list = [
'abruptly', 'absurd', 'abyss', 'affix', 'askew', 'avenue', 'awkward', 'axiom', 'azure',
'bagpipes', 'bandwagon', 'banjo', 'bayou', 'beekeeper', 'bikini', 'blitz', 'blizzard', 'boggle', 'bookworm', 'boxcar', 'boxful', 'buckaroo', 'buffalo', 'buffoon', 'buxom', 'buzzard', 'buzzing', 'buzzwords',
'caliph', 'cobweb', 'cockiness', 'croquet', 'crypt', 'curacao', 'cycle',
'daiquiri', 'dirndl', 'disavow', 'dizzying', 'duplex', 'dwarves',
'embezzle', 'equip', 'espionage', 'euouae', 'exodus',
'faking', 'fishhook', 'fixable', 'fjord', 'flapjack', 'flopping', 'fluffiness', 'flyby', 'foxglove', 'frazzled', 'frizzled', 'fuchsia', 'funny',
'gabby', 'galaxy', 'galvanize', 'gazebo', 'giaour', 'gizmo', 'glowworm', 'glyph', 'gnarly', 'gnostic', 'gossip', 'grogginess',
'haiku', 'haphazard', 'hyphen',
'iatrogenic', 'icebox', 'injury', 'ivory', 'ivy', 'jackpot', 'jaundice',
'jawbreaker', 'jaywalk', 'jazziest', 'jazzy', 'jelly', 'jigsaw', 'jinx', 'jiujitsu', 'jockey', 'jogging', 'joking', 'jovial', 'joyful', 'juicy', 'jukebox', 'jumbo',
'kayak', 'kazoo', 'keyhole', 'khaki', 'kilobyte', 'kiosk', 'kitsch', 'kiwifruit', 'klutz', 'knapsack',
'larynx', 'lengths', 'lucky', 'luxury', 'lymph',
'marquis', 'matrix', 'megahertz', 'microwave', 'mnemonic', 'mystify',
'naphtha', 'nightclub', 'nowadays', 'numbskull', 'nymph',
'onyx', 'ovary', 'oxidize', 'oxygen',
'pajama', 'peekaboo', 'phlegm', 'pixel', 'pizazz', 'pneumonia', 'polka', 'pshaw', 'psyche', 'puppy', 'puzzling',
'quartz', 'queue', 'quips', 'quixotic', 'quiz', 'quizzes', 'quorum',
'razzmatazz', 'rhubarb', 'rhythm', 'rickshaw',
'schnapps', 'scratch', 'shiv', 'snazzy', 'sphinx', 'spritz', 'squawk', 'staff', 'strength', 'strengths', 'stretch', 'stronghold', 'stymied', 'subway', 'swivel', 'syndrome',
'thriftless', 'thumbscrew', 'topaz', 'transcript', 'transgress', 'transplant', 'triphthong', 'twelfth', 'twelfths',
'unknown', 'unworthy', 'unzip', 'uptown',
'vaporize', 'vixen', 'vodka', 'voodoo', 'vortex', 'voyeurism',
'walkway', 'waltz', 'wave', 'wavy', 'waxy', 'wellspring', 'wheezy', 'whiskey', 'whizzing', 'whomever', 'wimpy', 'witchcraft', 'wizard', 'woozy', 'wristwatch', 'wyvern',
'xylophone',
'yachtsman', 'yippee', 'yoked', 'youthful', 'yummy',
'zephyr', 'zigzag', 'zigzagging', 'zilch', 'zipper', 'zodiac', 'zombie',
]
📄 hangman_art.py
아스키 아트 로고 저장
⌨️ 작성한 코드
#Step 5
import random
from hangman_words import word_list
from hangman_art import logo, stages
#TODO-1: - Update the word list to use the 'word_list' from hangman_words.py
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
end_of_game = False
lives = 6
#TODO-3: - Import the logo from hangman_art.py and print it at the start of the game.
print(logo)
#Testing code
#print(f'Pssst, the solution is {chosen_word}.')
#Create blanks
display = []
for _ in range(word_length):
display += "_"
while not end_of_game:
guess = input("Guess a letter: ").lower()
#TODO-4: - If the user has entered a letter they've already guessed, print the letter and let them know.
if guess in display:
print(f"The letter {guess} is already tried.")
#Check guessed letter
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
#Check if user is wrong.
if guess not in chosen_word:
#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.
print(f"The letter {guess} is not in the word. You lose one life.")
lives -= 1
if lives == 0:
end_of_game = True
print(f"You lose. The answer was {chosen_word}")
#Join all the elements in the list and turn it into a String.
print(f"{' '.join(display)}")
#Check if user has got all letters.
if "_" not in display:
end_of_game = True
print("You win.")
#TODO-2: - Import the stages from hangman_art.py and make this error go away.
print(stages[lives])
[ 출력결과 ]
_
| |
| |__ __ _ _ __ __ _ _ __ ___ __ _ _ __
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
__/ |
|___/
Guess a letter: ❚e
The letter e is not in the word. You lose one life.
_ _ _ _ _ _
+---+
| |
O |
|
|
|
=========
Guess a letter: ❚a
The letter a is not in the word. You lose one life.
_ _ _ _ _ _
+---+
| |
O |
| |
|
|
=========
Guess a letter: ❚o
The letter o is not in the word. You lose one life.
_ _ _ _ _ _
+---+
| |
O |
/| |
|
|
=========
Guess a letter: ❚u
The letter u is not in the word. You lose one life.
_ _ _ _ _ _
+---+
| |
O |
/|\ |
|
|
=========
Guess a letter: ❚i
_ _ _ i _ _
+---+
| |
O |
/|\ |
|
|
=========
Guess a letter: ❚i
The letter i is already tried.
_ _ _ i _ _
+---+
| |
O |
/|\ |
|
|
=========
Guess a letter: ❚s
s _ _ i _ _
+---+
| |
O |
/|\ |
|
|
=========
Guess a letter: ❚t
s _ _ i t _
+---+
| |
O |
/|\ |
|
|
=========
Guess a letter: ❚y
The letter y is not in the word. You lose one life.
s _ _ i t _
+---+
| |
O |
/|\ |
/ |
|
=========
Guess a letter: ❚l
The letter l is not in the word. You lose one life.
You lose. The answer was spritz
s _ _ i t _
+---+
| |
O |
/|\ |
/ \ |
|
=========