Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 51 additions & 53 deletions Main.py
Original file line number Diff line number Diff line change
@@ -1,105 +1,103 @@
'''
Tic Tac Toe
Repo owner: Md. Fahim Bin Amin
Description: A console based Tic Tac Toe game
-------------------------------------------------------------
'''
"""
Tic Tac Toe (Enhanced Version for Pull Request)
Repo Owner: Md. Fahim Bin Amin
Description: A console-based Tic Tac Toe game with improved UX and error handling
----------------------------------------------------------------------------------
"""

import random


class TicTacToe:

def __init__(self):
self.board = []

def create_board(self):
# Initialize an empty 3x3 board with dashes '-'
self.board = [['-' for _ in range(3)] for _ in range(3)]

def get_random_first_player(self):
# Randomly choose which player goes first (0 for 'O', 1 for 'X')
return random.randint(0, 1)
return random.choice(['X', 'O'])

def fix_spot(self, row, col, player):
# Mark the spot on the board with the player's symbol
self.board[row][col] = player

def has_player_won(self, player):
# Check if the player has won in rows, columns, or diagonals
n = len(self.board)
for i in range(n):
# Check rows
if all(self.board[i][j] == player for j in range(n)):
return True

# Check columns
if all(self.board[j][i] == player for j in range(n)):
# Check rows and columns
for i in range(n):
if all(self.board[i][j] == player for j in range(n)) or \
all(self.board[j][i] == player for j in range(n)):
return True

# Check diagonals
if all(self.board[i][i] == player for i in range(n)):
return True
if all(self.board[i][n - i - 1] == player for i in range(n)):
if all(self.board[i][i] == player for i in range(n)) or \
all(self.board[i][n - i - 1] == player for i in range(n)):
return True

return False

def is_board_filled(self):
# Check if the board is completely filled with symbols
return all(self.board[i][j] != '-' for i in range(3) for j in range(3))
return all(cell != '-' for row in self.board for cell in row)

def swap_player_turn(self, player):
# Swap player turn between 'X' and 'O'
return 'X' if player == 'O' else 'O'

def show_board(self):
# Display the current state of the board
print("Current Board:")
for row in self.board:
print(' '.join(row))
print(' | '.join(row))
print()

def start(self):
self.create_board()
player = 'X' if self.get_random_first_player() == 1 else 'O'
player = self.get_random_first_player()
game_over = False

print("🎮 Welcome to Tic Tac Toe!")
print("Players take turns entering row and column numbers (1 to 3).")
print("Enter as: row col → e.g., 2 3\n")

while not game_over:
self.show_board()
print(f"Player {player}'s turn")

try:
self.show_board()
print(f'Player {player} turn')
row_col = input('Enter row and column (e.g., 1 3): ').split()

# Get user input for row and column to fix the spot
row, col = list(map(int, input('Enter row & column numbers to fix spot: ').split()))
print()
if len(row_col) != 2:
raise ValueError("Please enter exactly two numbers separated by space.")

# Convert to 0-based index for internal board representation
row, col = map(int, row_col)
row -= 1
col -= 1

# Check if the spot is valid and not already taken
if 0 <= row < 3 and 0 <= col < 3 and self.board[row][col] == '-':
self.fix_spot(row, col, player)

# Check if the current player has won
if self.has_player_won(player):
print(f'Player {player} wins the game!')
game_over = True
elif self.is_board_filled():
print('Match Draw!')
game_over = True
else:
player = self.swap_player_turn(player)
if not (0 <= row < 3 and 0 <= col < 3):
raise ValueError("Row and column must be between 1 and 3.")

if self.board[row][col] != '-':
raise ValueError("This spot is already taken. Try another.")

self.fix_spot(row, col, player)

if self.has_player_won(player):
self.show_board()
print(f"🎉 Player {player} wins the game!")
game_over = True
elif self.is_board_filled():
self.show_board()
print("It's a Draw! 🤝")
game_over = True
else:
print('Invalid spot. Try again!')
player = self.swap_player_turn(player)

except ValueError as err:
print(err)

print()
self.show_board()
print(f"⚠️ {err}\n")
except Exception as e:
print(f"Unexpected error: {e}")
break


if __name__ == '__main__':
tic_tac_toe = TicTacToe()
tic_tac_toe.start()
game = TicTacToe()
game.start()