May-21-2024, 03:24 AM
(This post was last modified: May-21-2024, 01:07 PM by deanhystad.)
In connect4, every win contains the last move. Starting from the last play, count consecutive markers vertically, horizontally and along both diagonals. Again this is made simpler using a combination of data and algorithm.
def gameOver(self, column, row): """Did the last move end the game? Search the row, column and diagonals starting at the last marker looking for 4 contiguous markers. Return True if found. """ marker = self.board[row][column] for dx, dy in ((1, 0), (0, 1), (1, 1), (1, -1)): count = 0 # Count contiguous markers starting at row, column try: r, c = row, column while self.board[r][c] == marker: count += 1 r, c = r + dx, c + dy except IndexError: pass # Count contiguous markers in the other direction. try: r, c = row - dx, column - dy while self.board[r][c] == marker: count += 1 r, c = r - dx, c - dy except IndexError: pass if count >= 4: return True # Found a winner! return FalseThis same algorithm can be used for tic-tac-toe.