Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.6 kB
3
Indexable
Never
class TicTacToe:
    def __init__(self):
        self.board = {'1': ' ', '2': ' ', '3': ' ',
                      '4': ' ', '5': ' ', '6': ' ',
                      '7': ' ', '8': ' ', '9': ' '}

    def print_board(self):
        print(f" {self.board['1']} | {self.board['2']} | {self.board['3']}")
        print(" - + - + -")
        print(f" {self.board['4']} | {self.board['5']} | {self.board['6']}")
        print(" - + - + -")
        print(f" {self.board['7']} | {self.board['8']} | {self.board['9']}")

    def check_winner(self):
        winning_conditions = [
            (self.board['1'], self.board['2'], self.board['3']),
            (self.board['4'], self.board['5'], self.board['6']),
            (self.board['7'], self.board['8'], self.board['9']),
            (self.board['1'], self.board['4'], self.board['7']),
            (self.board['2'], self.board['5'], self.board['8']),
            (self.board['3'], self.board['6'], self.board['9']),
            (self.board['1'], self.board['5'], self.board['9']),
            (self.board['3'], self.board['5'], self.board['7']),
        ]
        for condition in winning_conditions:
            if condition[0] == condition[1] == condition[2] != ' ':
                return condition[0]  # Return the winning mark
        return None  # No winner found

    def run(self):
        turn = 'X'  # Start with player X
        count = 0
        while True:
            game.print_board()
            print(f"It is Player {turn}'s turn. Please enter the block to move to (1-9):")
            move = input()

            # Check if the move position is valid (between 1 and 9)
            if move not in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
                print("Invalid input. Please enter a number between 1 and 9.")
                continue

            # Check if the position is already occupied
            if self.board[move] != ' ':
                print("That block is already filled. Please choose another one.")
                continue

            # Update the game board
            self.board[move] = turn

            count += 1

            # Check for winner or tie
            winner = self.check_winner()
            if winner is not None:
                game.print_board()
                print(f"Game Over. Player {winner} wins!")
                break
            elif count == 9:
                game.print_board()
                print("It's a tie!")
                break

            # Switch turns after each valid move
            turn = 'O' if turn == 'X' else 'X'

game = TicTacToe()
game.run()
Leave a Comment