9.7.2 生成矩阵

首先,是生成10*10的按钮矩阵:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
# 创建一个10x10的按钮矩阵
for i in range(10):
    for j in range(10):
        x, y = j * 30, i * 30 #x和y分别是小方块的坐标
        rec = canvas.create_rectangle(x, y, x + 30, y + 30, fill="#ccc", outline="gray",
                                      tags=("button_{}_{}".format(i, j),))
# 进入事件循环
root.mainloop()
canvas是作为一个整体布局的,里面再画100个小正方形
第8行代码,x和y是将要画的小方块的左上角x和y坐标,每个方块边长都是30,所以要乘以30。
效果如图:
接下来,把Java学习平台【环森编程】(codessp.cn)里最后的生成扫雷的部分,写成函数,generateMines,暂时不需要参数,返回一个10*10的二维列表,雷的数量是10个,类似这样:
0001910000
0001111110
0000112910
0000192110
0000111000
1100000122
9100000199
0111000000
1292100000
1939100000
然后用生成的矩阵更新按钮上面的文字,这一步相当于是扫雷的明牌,为后面写逻辑做准备。
import tkinter as tk
def generateMines():
  #代码省略,整一个模拟数据
  return [[0, 0, 0, 0, 0, 1, 1, 1, 0, 0], 
[0, 1, 1, 1, 0, 1, 9, 1, 0, 0], 
[1, 2, 9, 1, 1, 2, 2, 1, 0, 0], 
[9, 2, 1, 1, 1, 9, 2, 1, 0, 0], 
[1, 1, 0, 0, 1, 2, 9, 2, 1, 0], 
[1, 1, 1, 1, 1, 1, 2, 9, 1, 0], 
[9, 1, 1, 9, 1, 0, 2, 2, 2, 0], 
[2, 2, 1, 1, 1, 0, 1, 9, 1, 0], 
[9, 1, 0, 0, 0, 0, 1, 1, 1, 0], 
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0]]
root = tk.Tk()
mines = generateMines()  # 生成地雷矩阵
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
# 创建一个10x10的按钮矩阵
for i in range(10):
    for j in range(10):
        x, y = j * 30, i * 30
        rec = canvas.create_rectangle(x, y, x + 30, y + 30, fill="#ccc", outline="gray",
                                      tags=("button_{}_{}".format(i, j),))
        row, col = int(y // 30), int(x // 30)
        # 获取该行列上的地雷数
        mine_count = mines[row][col]
        x, y = x + 15, y + 15
        canvas.create_text(x, y, text=str(mine_count), font=("Arial", 12, "bold"), fill="black", anchor="center")
# 进入事件循环
root.mainloop()
第24行代码中的row和col是根据方块的坐标计算出是几行几列的方块,因为x和y是方块左上角的坐标,它们都是30的倍数,例如第一个方块是(0,0),第二个是(0,30),第二行的第一个方块是(30,0),以此类推
然后第27行是确保数字写在方块的中间,此时的x和y是文字的坐标,所以要各自加15(边长30的一半)
最后效果图: