如果将标签存储在 中board
,则可以使用以下命令访问其背景颜色
board[i][j]['bg']
你可以改变背景颜色
board[i][j].config(bg=...)
甚至
board[i][j]['bg'] = ...
既然你想访问 上一个点的邻居board
,那么使用for-loop
s 是很自然的,例如:
for ii in range(i - 1, i + 2):
for jj in range(j - 1, j + 2):
或者,等效但嵌套较少使用itertools.product:
import itertools as IT
for ii, jj in IT.product(range(i - 1, i + 2), range(j - 1, j + 2)):
现在您可以使用 访问邻居board[ii][jj]
,记住它ii
或者jj
可能是一个越界索引。我们可以使用if
-statement 来处理越界索引:
if ii<0 or ii>=rows or jj<0 or jj>=cols: continue
使用上面的两个想法,您可以使用collections.Counter计算红色、绿色和灰色方块的数量:
import collections
collections.Counter(
board[i][j]['bg'] for i, j in IT.product(range(rows), range(cols)))
import Tkinter as tk
import itertools as IT
import collections
cols, rows = 3, 3
board = [[None] * cols for _ in range(rows)]
other = {'green': 'red', 'red': 'green'}
player = 'red'
def on_click(event, i, j):
global player
board[i][j]['bg'] = player
for ii, jj in IT.product(range(i - 1, i + 2), range(j - 1, j + 2)):
if ii<0 or ii>=rows or jj<0 or jj>=cols: continue
neighbor = board[ii][jj]
if neighbor['bg'] != 'grey' and (ii, jj) != (i, j):
neighbor['bg'] = other[neighbor['bg']]
check_for_winner()
player = other[player]
def check_for_winner():
s = score()
if s['red'] + s['green'] == cols*rows:
# every box filled
winner = max(s, key=s.get)
print('Winner is: {}'.format(winner))
root.after(1, flash_winner, winner, 'blue')
def score():
return collections.Counter(
board[i][j]['bg'] for i, j in IT.product(range(rows), range(cols)))
def flash_winner(winner, altcolor):
for i, j in IT.product(range(rows), range(cols)):
if board[i][j]['bg'] == winner:
board[i][j]['bg'] = altcolor
root.after(250, flash_winner, altcolor, winner)
root = tk.Tk()
for i, j in IT.product(range(rows), range(cols)):
board[i][j] = L = tk.Label(root, text=' ', bg='grey')
L.grid(row=i, column=j, padx=3, pady=3)
L.bind('<Button-1>', lambda e, i=i, j=j: on_click(e, i, j))
root.mainloop()