python實現帶界面的井字棋小遊戲

今天我們用python+tkinter安裝帶界面的井字棋,效果如圖所示

Tkinter Python 的標準 GUI 庫。Python 使用 Tkinter 可以快速的創建 GUI 應用程序。由於 Tkinter 是內置到 python 的安裝包中、隻要安裝好 Python 之後就能 import Tkinter 庫、而且 IDLE 也是用 Tkinter 編寫而成、對於簡單的圖形界面 Tkinter 還是能應付自如。

pip install tkinter

1、首先安裝tkinter

root= Tk()
root.title('井字棋')

digits = [1,2,3,4,5,6,7,8,9]
mark = '' “
count = 0
panels = ["panel"]*10

2、初始化窗口

Label(root,text="player1 : X",font="times 15").grid(row=0,column=1)
Label(root,text="player2 : O",font="times 15").grid(row=0,column=2)

button1=Button(root,width=15,font=('Times 16 bold'),height=7,command=lambda:checker(1))
button1.grid(row=1,column=1)
button2=Button(root,width=15,height=7,font=('Times 16 bold'),command=lambda:checker(2))
button2.grid(row=1,column=2)

button3=Button(root,width=15,height=7,font=('Times 16 bold'),command=lambda: checker(3))
button3.grid(row=1,column=3)
button4=Button(root,width=15,height=7,font=('Times 16 bold'),command=lambda: checker(4))
button4.grid(row=2,column=1)

button5=Button(root,width=15,height=7,font=('Times 16 bold'),command=lambda: checker(5))
button5.grid(row=2,column=2)
button6=Button(root,width=15,height=7,font=('Times 16 bold'),command=lambda: checker(6))
button6.grid(row=2,column=3)

button7=Button(root,width=15,height=7,font=('Times 16 bold'),command=lambda: checker(7))
button7.grid(row=3,column=1)
button8=Button(root,width=15,height=7,font=('Times 16 bold'),command=lambda: checker(8))
button8.grid(row=3,column=2)

button9=Button(root,width=15,height=7,font=('Times 16 bold'),command=lambda: checker(9))
button9.grid(row=3,column=3)


root.mainloop()

3、定義按鈕

很明顯上面的井字棋就是9個按鈕。這裡定義9個按鈕。

def win(panels,sign):
 return ((panels[1] == panels[2] == panels [3] == sign)
   or (panels[1] == panels[4] == panels [7] == sign)
   or (panels[1] == panels[5] == panels [9] == sign)
   or (panels[2] == panels[5] == panels [8] == sign)
   or (panels[3] == panels[6] == panels [9] == sign)
   or (panels[3] == panels[5] == panels [7] == sign)
   or (panels[4] == panels[5] == panels [6] == sign) 
   or (panels[7] == panels[8] == panels [9] == sign))

4、檢查獲勝的條件

檢查獲勝的條件,上面其中一種情況都是獲勝的。

def checker(digit):
 global count, mark, digits
 if digit==1 and digit in digits:
  digits.remove(digit)
  if count%2==0:
   mark ='X'
   panels[digit]=mark
  elif count%2!=0:
   mark = 'O'
   panels[digit]=mar
  button1.config(text = mark)
  count = count+1
  sign = mark
  if(win(panels,sign) and sign=='X'):
   msg.showinfo("Result","Player1 wins")
   root.destroy()
  elif(win(panels,sign) and sign=='O'):
   msg.showinfo("Result","Player2 wins")
   root.destroy()

最後這裡是點擊下棋,然後用win函數判斷是否結束比賽贏得棋局。

到此這篇關於python實現帶界面的井字棋的小遊戲的文章就介紹到這瞭,更多相關python實現帶界面的井字棋內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: