본문 바로가기
프로그램/Python 1000제

Python 286제] 파이썬 EXPRESS CHAPTER 10. 도전문제 p472

by 건티 2024. 5. 30.
728x90

출처 : 반크_독도2023

 

참고풀이]

from tkinter import *
import random

word_list = ["account", "bird", "cat", "dog", "east", "first", "grass", "help", "insect", "join",
             "key", "leaf", "man", "north", "oven", "part", "regular", "school", "silk", "time", "walk"]
word = random.choice(word_list)
count = 0
guess = ""

 

#label2에 발생된 단어의 수만큼 *를 표시한다.
Str="*"*len(word)

def answer():
    global word, guess, count, Str

    guess = entry1.get()
    count += 1
    
    if count<=11:
        #입력된 문자가 발생된 단어에 포함되었는지 체크하여
        #Str에 포함된 문자로 교환한다.
        if guess in word:
            S1=" ".join(Str)
            S=list(S1.split())
            for i in range(len(word)):
                if guess==word[i]:
                    S[i]=guess
            Str="".join(S)
            S.clear()
        if Str not in word: #if guess != word:
            if 12 - count > 0:
                label3.config(text=f"틀렸음! {12 - count}번의 기회가 남았음!")
                label2.config(text=Str)
        else:
            label3.config(text="사용자 승리")
            label2.config(text=Str)
    else:
        label3.config(text="")
        label2.config(text=f"사용자 패배. 정답은 {word}")

    entry1.delete(0,END)
        
window = Tk()
window.title("Hangman")

label1 = Label(window, text="단어를 추측하시오:", width=25)
label1.grid(row=0, column=0)

entry1 = Entry(window, width=30, bg="yellow")
entry1.grid(row=0, column=1, columnspan=3, padx=5, pady=5)

button1 = Button(window, text="눌러서 확인하시오", command=answer)
button1.grid(row=1, column=2)

label3 = Label(window, text="")
label3.grid(row=2, column=0)

label2 = Label(window, text=Str)
label2.grid(row=2, column=2)

window.mainloop()

 

참고풀이 결과]

시작창)

 

실행창)

 

 

결과창)

 

 

 

 

 

 

대한민국의 아름다운 영토, 독도의 가을

 

반응형

댓글