用Python编写的五子棋程序1.0版
生活随笔
收集整理的這篇文章主要介紹了
用Python编写的五子棋程序1.0版
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
作為一個Python初學者,
在學習了相關知識后,
又參考了一些代碼,
自己也編了個五子棋的程序,
目前只能實現人人對戰,
即雙方輪流下,
執黑先走,鼠標左鍵走棋,右鍵悔棋。
請多指教!
代碼如下:
"""判斷輸贏函數 """ def checkWin(x,y):flag = Falsecount = 1 #保存共有相同顏色多少棋子相連color =map[x][y]#橫向判斷i =1while color == map[x + i][y]: #向右判斷count += 1i += 1i=1while color == map[x - i][y]: #向左判斷count += 1i += 1if count >= 5:flag = True#縱向判斷i2 = 1count2 = 1while color == map[x][y + i2]: # 向上判斷count2 += 1i2 += 1i2 = 1while color == map[x][y - i2]: # 向下判斷count2 += 1i2 += 1if count2 >= 5:flag = True#右上和左下判斷i3 = 1count3 = 1while color == map[x + i3][y + i3]: # 右上判斷count3 += 1i3 += 1i3 = 1while color == map[x - i3][y - i3]: # 左下判斷count3 += 1i3 += 1if count3 >= 5:flag = True#右下和左上判斷i4 = 1count4 = 1while color == map[x + i4][y - i4]: # 右下判斷count4 += 1i4 += 1i3 = 1while color == map[x - i4][y + i4]: # 左上判斷count4 += 1i4 += 1if count4 >= 5:flag = Truereturn flag"""走棋函數 """ def callback(event):global turnx = (event.x)//40y = (event.y)//40print("click at",x,y,turn)if map[x][y] != "":showinfo(title= "提示",message = "已有棋子!")else:img1 = pics[turn]id = cv.create_image((x * 40 + 20, y * 40 + 20),image = img1)back.append((id,x,y))cv.pack()map[x][y] = str(turn)print_map()if checkWin(x,y):if turn == 0:showinfo(title= "提示",message = "黑方贏了!")else:showinfo(title= "提示",message = "白方贏了!")# 換下一方走棋if turn == 0:turn = 1else:turn = 0"""悔棋函數 """ def huiqi(event):global turnif len(back) == 0:showinfo(title= "提示",message = "已沒有任何棋子!")returnm = back.pop()id = m[0]x = m[1]y = m[2]map[x][y] = ''cv.delete(id) # 刪除棋子#換上一方走棋if turn == 0:turn = 1else:turn = 0"""繪制棋盤函數 """ def drawQipan():for i in range(0,15):cv.create_line(20,20+40*i,580,20+40*i,width = 2)for i in range(0,15):cv.create_line(20+40*i,20,20+40*i,580,width = 2)cv.pack"""輸出走棋信息 """ def print_map():for i in range(0, 15):for j in range(0, 15):print(map[i][j],end='')print('w')"""主函數 """ from tkinter import * from tkinter.messagebox import *turn = 0 map = [[""for y in range(15)]for x in range(15)] root = Tk()pics = [PhotoImage(file = 'F:\\Python_study\\practice\\blacK.gif'),PhotoImage(file = 'F:\\Python_study\\practice\\white.gif')] #調取棋子圖片 格式為gifroot.title("五子棋v1.0") back = [] cv = Canvas(root,bg = 'green',width = 610,height = 610) #棋盤 drawQipan() cv.bind("<Button-1>",callback) #走棋 cv.bind("<Button-3>",huiqi) #悔棋 cv.pack() root.mainloop()棋子圖片:
程序運行如下:
在主函數調取棋子圖片時,
老是出錯,
后來在論壇求助后,
得到網友“陳年椰子”的提醒和指教,
完美解決問題,
如下:求助貼
本程序也得以完成,
在此再次感謝。
總結
以上是生活随笔為你收集整理的用Python编写的五子棋程序1.0版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 读经典《C程序设计语言》(The C P
- 下一篇: 数据通信网的交换方式