[Python] Hangman 게임하기

‍허진·2023년 2월 27일
0

Programming

목록 보기
3/10
post-thumbnail

> 과제 요구사항

Hangman 게임을 진행할 수 있는 코드이다.
코드를 실행하면 로딩된 단어의 개수, 맞춰야하는 단어의 알파벳 글자 수가 출력된다.
그리고 입력할 때마다 남은 기회와 입력할 수 있는 알파벳을 표시해준다.
'?'를 입력하면 기회를 3번 차감하고 힌트를 하나 얻을 수 있다.

> 출력 예시


[그림 - 정답 예시]

> 코드

import random
from typing import List

WORDLIST_FILENAME = "words.txt"

def load_words():
    """
    returns: list, a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def choose_word(wordlist):
    """
    wordlist (list): list of words (strings)

    returns: a word from wordlist at random
    """
    return random.choice(wordlist)

all_words_list = load_words()
secret_word = choose_word(all_words_list)

def ListToString(str_list):
    result=''
    for s in str_list:
        result+=s
    return result

guess_word=[]
for i in secret_word:
    guess_word.append('_')


chance=10
alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
save=list(secret_word)
save=list(set(save))
print('Welcome to Hangman !')
print('Let\'s guess a {} letter word.'.format(len(secret_word)))
while(True):

    if chance<1:
        print('Ooops! Not enough guess left for : ',ListToString(guess_word))
        print('--------------------')
        print('The secret word is \'{}\''.format(secret_word))
        break


    flag2=0
    for i in guess_word:
        if i=='_':
            flag2=1
        
    if flag2==0:
        print('--------------------')
        print('Good Job!  You won with score of {}.'.format(4*chance + 3*len(secret_word)))
        break

    print('--------------------')
    print('You currently have {} guesses left.'.format(chance))
    print('Available letters:  ',ListToString(alphabet))
    tmp=input('Please guess a letter:   ')

    try:
        alphabet.remove(tmp)

        chance-=1
        j=0
        flag=0
        for i in secret_word:
            if i == tmp:
                flag=1
                guess_word[j]=tmp
            j+=1

        if flag==1:
            print('Good guess:  ',ListToString(guess_word))
            save.remove(tmp)
            
        else:
            print('Sorry. That letter is not in my word :  ',ListToString(guess_word))
    

    except:
        cmpr=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
        if tmp in cmpr:
            print('You already guessed letter \'{}\'. Please input other letter :  '.format(tmp),ListToString(guess_word))
        elif tmp=='?':
            if chance>2:
                tmp2=random.choice(save)
                alphabet.remove(tmp2)
                k=0
                for i in secret_word:
                    if i == tmp2:
                        guess_word[k]=tmp2
                    k+=1
                print('Letter {} is revealed : '.format(tmp2),ListToString(guess_word))
                chance-=3

            else:
                print('You don\'t have enough guesses. Please input a letter.',ListToString(guess_word))

        else:
            print('Nope.  That is not a valid letter :  ',ListToString(guess_word))

> 추가 첨부파일

https://drive.google.com/file/d/1r8HUq550amFLUv3sWkYOAXROlvCVpBnv/view?usp=share_link

words.txt 파일. 55900 개의 단어를 포함하고 있다.

profile
매일 공부하기 목표 👨‍💻 

0개의 댓글