(编辑:jimmy 日期: 2024/11/15 浏览:2)
python实现棋盘覆盖图形界面,供大家参考,具体内容如下
一、解决方案和关键代码
工具: python tkinter库
问题描述:
解决方法:递归与分治法
算法关键代码
def chessBoard(tr,tc,dr,dc,size): global tile global board if (size==1): return 0 tile+=1 t=tile s=size//2 #the upper left corner if (dr<tr+s and dc<tc+s): chessBoard(tr,tc,dr,dc,s) else: board[tr+s-1,tc+s-1]=t chessBoard(tr,tc,tr+s-1,tc+s-1,s) #the upper right corner if (dr<tr+s and dc>=tc+s): chessBoard(tr,tc+s,dr,dc,s) else: board[tr+s-1,tc+s]=t chessBoard(tr,tc+s,tr+s-1,tc+s,s) #the lower left corner if (dr>=tr+s and dc<tc+s): chessBoard(tr+s,tc,dr,dc,s) else: board[tr+s,tc+s-1]=t chessBoard(tr+s,tc,tr+s,tc+s-1,s) #the lower right corner if (dr>=tr+s and dc>=tc+s): chessBoard(tr+s,tc+s,dr,dc,s) else: board[tr+s,tc+s]=t chessBoard(tr+s,tc+s,tr+s,tc+s,s)
画棋盘关键代码:
def drawboard(canvas1,board,colors,startx=50,starty=50,cellwidth=50): width=2*startx+len(board)*cellwidth height=2*starty+len(board)*cellwidth canvas1.config(width=width,height=height)#布置画布 for i in range(len(board)): for j in range(len(board)): index=board[i][j] if index== 0: color='white'#特殊方格显示为白色 else: color=colors[6*index]#为了间隔开颜色 cellx=startx+i*50 celly=starty+j*50 canvas1.create_rectangle(cellx,celly,cellx+cellwidth,celly+cellwidth,fill=color,outline="black")#画方格 canvas1.update()
二、数据测试
特殊方格坐标为(1,1),棋盘大小为(2^2*2^2)
特殊方格坐标为(2,2),棋盘大小为(2^3*2^3)
完整代码下载链接点这里
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。