python3 tkinter 五子棋,井字棋.............

编程入门 行业动态 更新时间:2024-10-24 04:47:19

python3 tkinter <a href=https://www.elefans.com/category/jswz/34/1769950.html style=五子棋,井字棋............."/>

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 五子棋,井字棋.............

本文发布于:2023-07-28 17:14:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260018.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:五子   tkinter   井字棋

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!