[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
def clearBoard(self):
for row, col in self.label.keys():
self.board[row][col] = Empty
self.label[(row, col)].config(text=' ')

Similarly, picking a move, at least in random mode, is simply a matter of picking a
nonempty slot in the board array and storing the machine’s mark there and in the GUI
(degree is the board’s size):


def machineMove(self):
row, col = self.pickMove()
self.board[row][col] = self.machineMark
self.label[(row, col)].config(text=self.machineMark)

def pickMove(self):
empties = []
for row in self.degree:
for col in self.degree:
if self.board[row][col] == Empty:
empties.append((row, col))
return random.choice(empties)

Finally, checking for an end-of-game state boils down to inspecting rows, columns, and
diagonals in the two-dimensional list-of-lists board in this scheme:


Figure 11-27. An alternative layout


PyToe: A Tic-Tac-Toe Game Widget | 765
Free download pdf