0% found this document useful (0 votes)
14 views3 pages

Code Pal Result

Download as txt, pdf, or txt
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 3

class TicTacToe:

"""
Class to handle the Tic Tac Toe game.

Attributes:
- board: list
Represents the game board as a list of strings.
- current_player: str
Represents the current player, either 'X' or 'O'.
"""

def __init__(self):
"""
Constructor to initialize the Tic Tac Toe game.

Initializes the game board as an empty 3x3 grid and sets the current player
as 'X'.
"""

# Initializing the game board as an empty 3x3 grid


self.board = [' ' for _ in range(9)]

# Setting the current player as 'X'


self.current_player = 'X'

def print_board(self):
"""
Prints the current state of the game board.
"""

print('---------')
for i in range(0, 9, 3):
print(f'| {self.board[i]} | {self.board[i+1]} | {self.board[i+2]} |')
print('---------')

def make_move(self, position: int):


"""
Makes a move on the game board at the specified position.

Parameters:
- position: int
The position on the game board where the move is to be made.

Returns:
- bool:
True if the move is valid and made successfully, False otherwise.
"""

# Checking if the position is valid and not already occupied


if position < 0 or position >= 9 or self.board[position] != ' ':
return False

# Making the move by updating the game board with the current player's
symbol
self.board[position] = self.current_player

# Switching to the next player


self.current_player = 'O' if self.current_player == 'X' else 'X'
return True

def check_winner(self):
"""
Checks if there is a winner in the game.

Returns:
- str:
The symbol of the winner if there is one, None otherwise.
"""

# Possible winning combinations


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
]

# Checking each winning combination


for combination in winning_combinations:
a, b, c = combination
if self.board[a] == self.board[b] == self.board[c] != ' ':
return self.board[a]

return None

def play_game(self):
"""
Plays the Tic Tac Toe game.

Alternates between players making moves until there is a winner or the game
ends in a draw.
"""

while True:
self.print_board()

# Getting the move from the current player


position = int(input(f"Player {self.current_player}, enter your move
(0-8): "))

# Making the move


if not self.make_move(position):
print("Invalid move. Try again.")
continue

# Checking if there is a winner


winner = self.check_winner()
if winner:
self.print_board()
print(f"Player {winner} wins!")
break

# Checking if the game ends in a draw


if ' ' not in self.board:
self.print_board()
print("It's a draw!")
break
# Switching to the next player

# Starting the Tic Tac Toe game


game = TicTacToe()
game.play_game()

You might also like