Python Basic _ 10-3. 파이썬 게임 완성

WONY_yoon·2025년 10월 9일
post-thumbnail

Python Hangman 완성해보기

# Chapter10-3  
# Hangman 미니 게임 제작 (3)  
# 사운드 및 힌트 기능 추가, 최종 완성 버전  

import time
import csv
import random
import os
import platform

# 사운드 재생 함수
def play_sound(sound_path):
    # Windows용 사운드 실행
    if platform.system() == 'Windows':
        import winsound
        winsound.PlaySound(sound_path, winsound.SND_FILENAME)
    # macOS용 사운드 실행
    else:
        os.system(f'afplay {sound_path}')

# 처음 인사
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)

# 단어 리스트 초기화
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 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()
        play_sound('sound/good.wav')  # 성공 사운드
        print('Congratulations, you guessed the word!')
        break

    print()
    print()
    # 힌트 제공
    print('Hint : {}'.format(q[1].strip()))

    # 문자 입력
    guess = input('Guess a character: ')
    guesses += guess

    # 정답 단어에 없는 문자 입력 시
    if guess not in word:
        turns -= 1
        print('Oops! Wrong guess!')
        print('You have', turns, 'more guesses remaining!')

        # 기회를 모두 소진했을 경우
        if turns == 0:
            play_sound('sound/bad.wav')  # 실패 사운드
            print('💀 You failed the hangman game. Bye!')

0개의 댓글