Multiplayer Tic-Tac-Toe

pythonCopy codeclass TicTacToe:
    def __init__(self):
        self.board = [' ' for _ in range(9)]  # 3x3 board
        self.current_player = 'X'

    def print_board(self):
        print("\n")
        for i in range(3):
            print(f" {self.board[i*3]} | {self.board[i*3+1]} | {self.board[i*3+2]} ")
            if i < 2:
                print("---|---|---")
        print("\n")

    def is_winner(self):
        # Check rows, columns, and diagonals for a win
        winning_combinations = [
            (0, 1, 2), (3, 4, 5), (6, 7, 8),  # rows
            (0, 3, 6), (1, 4, 7), (2, 5, 8),  # columns
            (0, 4, 8), (2, 4, 6)               # diagonals
        ]
        for a, b, c in winning_combinations:
            if self.board[a] == self.board[b] == self.board[c] != ' ':
                return True
        return False

    def is_draw(self):
        return ' ' not in self.board

    def make_move(self, position):
        if self.board[position] == ' ':
            self.board[position] = self.current_player
            if self.is_winner():
                self.print_board()
                print(f"Player {self.current_player} wins!")
                return True
            elif self.is_draw():
                self.print_board()
                print("It's a draw!")
                return True
            else:
                self.current_player = 'O' if self.current_player == 'X' else 'X'
            return False
        else:
            print("Invalid move! Try again.")
            return False

def main():
    game = TicTacToe()
    
    while True:
        game.print_board()
        try:
            move = int(input(f"Player {game.current_player}, enter your move (1-9): ")) - 1
            if move < 0 or move > 8:
                print("Invalid input! Enter a number between 1 and 9.")
                continue
            if game.make_move(move):
                break
        except ValueError:
            print("Invalid input! Please enter a number.")

if __name__ == "__main__":
    main()

Step 2: Running the Tic-Tac-Toe Game

  1. Open your terminal (or command prompt).
  2. Navigate to the directory where you saved tic_tac_toe.py.
  3. Run the script using the command:bashCopy codepython tic_tac_toe.py

How It Works

  • Game Board: The board is represented as a list of strings, with ‘ ‘ indicating empty spaces.
  • Player Turns: Players alternate turns, with ‘X’ and ‘O’ representing the two players.
  • Move Validation: The game checks if the chosen position is valid and not already taken.
  • Winning Conditions: The game checks for winning combinations after each move.
  • Draw Condition: If the board is full without a winner, it announces a draw.

Example Gameplay

  1. The board is displayed in a 3×3 grid.
  2. Players take turns entering their moves by specifying a number from 1 to 9 corresponding to the board positions.
  3. The game announces the winner or if it’s a draw.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *