Python Forum
My first python game : Tic-Tac-Toe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
My first python game : Tic-Tac-Toe
#6
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 False
This same algorithm can be used for tic-tac-toe.
Reply


Messages In This Thread
RE: My first python game : Tic-Tac-Toe - by deanhystad - May-21-2024, 03:24 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  From python game in terminal to a website game using bottle Njanez 0 3,935 Aug-13-2021, 01:11 PM
Last Post: Njanez

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020