# coding:utf-8
import random
import tkinter as tk
import tkinter.messagebox as tmsg
def ButtonClick():
b = editbox1.get()
#判斷是否為4位數
isok = False
if len(b) != 4:
tmsg.showerror("錯誤", "請填4個數字")
else:
kazuok = True
for i in range(4):
if (b[i] <"0") or (b[i] > "9") :
tmsg.showerror("錯誤", "不是數字")
kazuok = False
break
if kazuok :
isok = True
if isok :
# 當輸入為4位數
# hit 判定
hit = 0
for i in range(4):
if a[i] == int(b[i]):
hit = hit + 1
# blow 判定
blow = 0
for j in range(4):
for i in range(4):
if (int(b[j]) == a[i]) and (a[i] != int(b[i])) and (a[j] != int(b[j])):
blow = blow + 1
break
#當 hit==4
if hit == 4:
tmsg.showinfo("猜中了", "恭喜。猜中了")
# 終了
root.destroy()
else:
# hit and blow 的題示
tmsg.showinfo("提示", "Hit " + str(hit) + "/" + "Blow " + str(blow))
adpated from python 入門教室
# 取亂數
a = [random.randint(0, 9),
random.randint(0, 9),
random.randint(0, 9),
random.randint(0, 9)]
root = tk.Tk()
root.geometry("400x150")
root.title("猜數字遊字")
label1 = tk.Label(root, text="輸入數字", font=("Helvetica", 14))
label1.place(x = 20, y = 20)
label2=tk.Label(root,text=a,font=("Helvetica",14))
label2.place(x=20,y=120)
editbox1 = tk.Entry(width = 4, font=("Helvetica", 28))
editbox1.place(x = 120, y = 60)
button1 = tk.Button(root, text = "確定", font=("Helvetica", 14), command=ButtonClick)
button1.place(x = 220, y = 60)
root.mainloop()
沒有留言:
張貼留言