###### tags: `Python`,`game`
# Python Tkinter 猜數字遊戲(幾A幾B)
記得在國中階段時,哈電族這個東西當時很夯,除了拿來當翻譯機外,莫過於上課拿來打發一下時間,跟同學對戰一下猜數字幾A幾B,比看看誰最先猜中那4個數字!!
什麼~沒聽過哈電族,來來來,丟溪伊,丟溪伊!!!不只幫你查單字,還能發音給你聽!!
怕睡過頭,還可以設定鬧鐘給你逼逼逼!!!

**廢話不多說
今天就來拆解遊戲邏輯啦!!!來人------給我上------code!**
```python=
"""
xAxB Tkinter version
"""
import tkinter as tk
import random
import tkinter.messagebox
def _ABgame():
global answer
while True:
answer=random.sample(range(0,10),4) ##隨機產生0-9四個數字的list
if len(answer)==4:
break
return answer
def _hit1(): #送出猜數字後的結果
global answer,count
a = b = i =0 #判別幾a幾b
user=enter.get() #由enter鍵送出得到4個數字
for i in range(4):
if int(user[i]) == answer[i]: #位置對數字也對
a = a+1
elif int(user[i]) in answer: #位置不對數字對
b = b+1
show=user+" -->"+str(count)+" . "+str(a)+"A"+str(b)+"B" #視窗提示info
listbox.insert(tk.END, show)
if a==4:
listbox.insert(tk.END,r"<< 恭喜~~天才如你啊!!! \\\^_____^/// >>")
if count==6:
listbox.insert(tk.END,r"<< 我的字典裡沒有放棄兩字!! >>")
if count==10 and a!=4:
listbox.insert(tk.END,r"<< 再撐一下,就差一步了! >>")
count=count+1
enter.delete(0,tk.END) #enter清空,再讓使用者輸入新數字
def _hit2(): #再玩一次
global answer,count
count=1
answer=_ABgame() #重回主程式
listbox.delete(0,tk.END) #清空listbox的資訊
def _hit3(): #是否離開
que=tk.messagebox.askokcancel("Hint","不再給自己一次機會嗎???")
if que:
win1.destroy() #視窗關閉
win1 = tk.Tk()
win1.title("一起玩猜數字遊戲吧!!!")
win1.geometry("600x650")#視窗大小
#主程式
a = b = 0
answer = _ABgame()
count = 1 #計算次數
lbL = tk.Label(win1,text="遊戲開始!!",fg="Black",bg="BurlyWood", font=("Arial", 22),bd=5, width=80, height=2)
lbL2 = tk.Label(win1,text="請輸入4個(範圍:0~9)數字",fg="Maroon",bg="BurlyWood", font=("Arial", 16), width=80, height=2)
#6.放置標籤(設定顯示位置),預設為TOP,pack是把label放到視窗上面去
lbL.pack()
lbL2.pack()
#待使用者輸入
enter=tk.Entry(win1,font=("Arial",15),bd=4, width=35, bg="OldLace") #bd邊框
enter.pack()
#介面有三個buttom,分別對應hit1,hit2,hit3
btN1 = tk.Button(win1, text="送出答案", font=("Arial", 15),fg="Maroon",bg="BurlyWood", width=35, height=1, command=_hit1)
btN1.pack()
btN2 = tk.Button(win1, text="太好玩了,我要再玩一次", font=("Arial", 15),fg="Maroon",bg="BurlyWood", width=35, height=1, command=_hit2)
btN2.pack()
btN3 = tk.Button(win1, text="結束遊戲", font=("Arial", 15),fg="Maroon",bg="BurlyWood", width=35, height=1, command=_hit3)
btN3.pack()
sbar=tk.Scrollbar(win1)
sbar.pack(side=tk.RIGHT,fill=tk.Y) #加入右邊卷軸
#設定listbox的格式
listbox=tk.Listbox(win1,bd=4,width=80,height=16,font=("Arial", 15),fg="Chocolate",bg="BlanchedAlmond",highlightcolor="Maroon",yscrollcommand=sbar.set)
listbox.pack(side=tk.BOTTOM, fill=tk.BOTH)
sbar.config(command=listbox.yview)
win1.mainloop()
```


