프로그램
[파이썬] 문제 : tkinter 가위,바위,보 게임
오디세이99
2023. 5. 6. 03:19
728x90
반응형
from random import *
import tkinter as tk
root = tk.Tk() # tkinter 설정
score = [0,0]
def select(sc, human_choice): # 버튼 클리시 인수 넘어 옴
lst = ['가위','바위','보']
computer_choice = choice(lst) # 램덤하게 리스트에서 하나를 선택. ramdon.choice()
c = computer_choice # 변수명이 길어서 짧은 변수로 변경
h = human_choice
ci = lst.index(c) # 해당 요소의 인덱스를 구함
hi = lst.index(h)
win = ''
if (ci == 1 and hi == 0) or (ci == 2 and hi == 1) or (ci == 0 and hi == 2): # 컴퓨터 승리 조건
win = '컴퓨터 승리'
sc[1] += 1
comp_score["text"] = "컴퓨터 점수 : " + str(sc[1])
elif (ci == 1 and hi == 2) or (ci == 2 and hi == 0) or (ci == 0 and hi == 1): # 휴먼 승리 조건
win = '사용자 승리'
sc[0] += 1
user_score["text"] = "사용자 점수 : " + str(sc[0])
else:
win = '무승부'
result["text"] = f"사용자={hi}, 컴퓨터={ci} : {win}" # 결과 보여주는 Label의 text 변경
return sc
root.geometry('400x200')
frame = tk.Frame(root) # tkinter 위젯들을 포함할 틀(Frame) 설정
frame.pack(pady = 10) # 좌우 여백 10 설정
title = tk.Label(frame, text = "가위 바위 보 게임") # 결과용 Label
title.grid(row=1, column=2)
b1 = tk.Button(frame, text='가위', bg='orange', width=10, command=lambda: select(score, '가위')) # 버튼 추가. 클릭시 함수 select() 실행. 이때 인수 '가위' 넘겨 줌. 이때 lambda를 사용해야 인수 넘겨 줋 수 있음
b1.grid(row=2, column=1)
b2 = tk.Button(frame, text='바위', bg='yellow', width=10, command=lambda: select(score, '바위'))
b2.grid(row=2, column=2)
b3 = tk.Button(frame, text='보', bg='skyblue', width=10, command=lambda: select(score, '보'))
b3.grid(row=2, column=3)
user_score = tk.Label(frame, text = "사용자 점수 : ") # 결과용 Label
user_score.grid(row=3, column=2)
comp_score = tk.Label(frame, text = "컴퓨터 점수 : ") # 결과용 Label
comp_score.grid(row=4, column=2)
result = tk.Label(frame, text = "") # 결과용 Label
result.grid(row=5, column=2)
root.mainloop()
728x90
반응형