五子棋,井字棋............."/>
python3 tkinter 五子棋,井字棋.............
import tkinter
import tkinter.messagebox# 创建主窗口
root = tkinter.Tk(className='五子棋')
root.resizable(0,0)global status,btn_list,who,bg_color,maxrow,maxcolumn,win_count# 最大行
maxrow = 10# 最大列
maxcolumn = 10# 胜利条件
win_count = 5# 背景色
bg_color = 'Goldenrod'# 棋盘状态
status = []
for i in range(maxrow):status_r = []for j in range(maxcolumn):status_r.append('空')status.append(status_r)# 棋盘具体组件
btn_list=[]# 当前执棋者
who = '黑'# 判断是否有胜者
def hasWinner(i,j):global status,win_countcount = 1x,y = j,iwhile y-1 >= 0:y -= 1if status[y][x] == status[i][j]:count += 1else:breakx,y = j,iwhile y+1 < maxrow:y += 1if status[y][x] == status[i][j]:count += 1else:breakif count >= win_count:return Truecount = 1x,y = j,iwhile x-1 >= 0:x -= 1if status[y][x] == status[i][j]:count += 1else:breakx,y = j,iwhile x+1 < maxcolumn:x += 1if status[y][x] == status[i][j]:count += 1else:breakif count >= win_count:return Truecount = 1x,y = j,iwhile x-1 >= 0 and y-1 >= 0:x -= 1y -= 1if status[y][x] == status[i][j]:count += 1else:breakx,y = j,iwhile x+1 < maxcolumn and y+1 < maxrow:x += 1y += 1if status[y][x] == status[i][j]:count += 1else:breakif count >= win_count:return Truecount = 1x,y = j,iwhile x+1 < maxcolumn and y-1 >= 0:x += 1y -= 1if status[y][x] == status[i][j]:count += 1else:breakx,y = j,iwhile x-1 >= 0 and y+1 < maxrow:x -= 1y += 1if status[y][x] == status[i][j]:count += 1else:breakif count >= win_count:return Truereturn False# 点击回调函数
def onClick(x,y,root):global status,btn_list,who,bg_color,maxrow,maxcolumnif status[y][x] == '空':status[y][x] = who# 棋子颜色btn_list[y][x]['bg'] = 'Black' if who == '黑' else 'Snow'if hasWinner(y,x):tkinter.messagebox.showinfo('游戏结束',who+'胜了',parent=root)for i in range(maxrow):for j in range(maxcolumn):btn_list[i][j]['bg'] = bg_colorstatus[i][j] = '空'who = '黑'else:who = '黑' if who == '白' else '白'# 组件类
class MyButton(tkinter.Button):def __init__(self,root,x,y):tkinter.Button.__init__(self,root,bg=bg_color,width=3,height=1,cursor='hand2',borderwidth=3,command=lambda: onClick(x,y,root))# 初始化组件
for i in range(maxrow):btn=[]for j in range(maxcolumn):but = MyButton(root,j,i)but.grid(row=i,column=j)btn.append(but)btn_list.append(btn)# 加入消息循环
root.mainloop()
更多推荐
python3 tkinter 五子棋,井字棋.............
发布评论