
Python Hangman 테스트해보기
# Chapter10-2
# Hangman 미니 게임 제작 (2)
# CSV 파일을 이용한 단어 불러오기 및 최종 테스트
import time
import csv # CSV 파일 처리
import random # 랜덤 단어 선택
# import winsound # (선택) 사운드 효과용 — Windows 전용
# 처음 인사
name = input('What is your name? ')
print('Hi, ' + name + ', Time to play hangman game!')
print()
time.sleep(1) # 대기 시간 (로딩 연출용)
print('Start Loading...')
print()
time.sleep(0.5)
# CSV 단어 리스트 불러오기
words = []
# CSV 파일 로드
with open('resource/word_list.csv', 'r') as f:
reader = csv.reader(f)
for c in reader: # 헤더를 건너뛰고 단어 추가
words.append(c)
# 리스트 섞기
random.shuffle(words)
# 무작위 단어 선택
q = random.choice(words)
# 정답 단어 (공백 제거)
word = q[0].strip()
# 추측 문자 저장 변수
guesses = ''
# 남은 기회
turns = 7
# 핵심 while 루프
# 기회가 남아있는 동안 게임 실행
while turns > 0:
# 실패 횟수 초기화
failed = 0
# 지금까지 추측한 문자 표시
print(guesses)
# 정답 단어의 각 문자 확인
for char in word:
if char in guesses:
print(char, end=' ') # 맞춘 문자 출력
else:
print('_', end=' ') # 틀린 문자는 밑줄로 표시
failed += 1
# 모든 글자를 맞춘 경우
if failed == 0:
print()
print()
print('🎉 Congratulations, you guessed the word!')
break
print()
print()
# 사용자 입력 (한 글자씩)
guess = input('Guess a character: ')
guesses += guess
# 입력 문자가 정답에 없는 경우
if guess not in word:
turns -= 1
print('Oops! Wrong guess!')
print('You have', turns, 'more guesses!')
# 기회를 모두 소진한 경우
if turns == 0:
print('💀 You failed the hangman game. Bye!')