Problem Statement
Without a clear and efficient way to check if a player has won, games can become slow or incorrect, causing poor user experience and frustration. Naive win checking can lead to redundant computations and delayed game responses.
This diagram shows the flow from a player's move to updating the game state, then checking the win condition, and finally deciding if the game ends or continues.
### Before: Naive win checking after every move by scanning entire board class Game: def __init__(self): self.board = [[None]*3 for _ in range(3)] def make_move(self, x, y, player): self.board[x][y] = player if self.check_win(): print(f"Player {player} wins!") def check_win(self): # Check all rows, columns, diagonals for i in range(3): if self.board[i][0] == self.board[i][1] == self.board[i][2] != None: return True if self.board[0][i] == self.board[1][i] == self.board[2][i] != None: return True if self.board[0][0] == self.board[1][1] == self.board[2][2] != None: return True if self.board[0][2] == self.board[1][1] == self.board[2][0] != None: return True return False ### After: Optimized win checking by tracking last move class Game: def __init__(self): self.board = [[None]*3 for _ in range(3)] self.rows = [0]*3 self.cols = [0]*3 self.diag = 0 self.anti_diag = 0 def make_move(self, x, y, player): val = 1 if player == 'X' else -1 self.board[x][y] = player self.rows[x] += val self.cols[y] += val if x == y: self.diag += val if x + y == 2: self.anti_diag += val if abs(self.rows[x]) == 3 or abs(self.cols[y]) == 3 or abs(self.diag) == 3 or abs(self.anti_diag) == 3: print(f"Player {player} wins!")