Created
September 5, 2023 01:20
-
-
Save charlieoneill11/cbe1c698af91573dcf1d6fb1575a8c1d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TicTacToe: | |
def __init__(self): | |
# Initialise an empty board | |
self.board = ['-' for _ in range(9)] | |
self.current_player = 'X' # X will start | |
def make_move(self, position): | |
"""Make a move on the board.""" | |
if self.board[position] == '-': | |
self.board[position] = self.current_player | |
self.switch_player() | |
return True | |
else: return False # illegal move | |
def switch_player(self): | |
"""Switch the current player.""" | |
self.current_player = 'O' if self.current_player == 'X' else 'X' | |
def check_winner(self): | |
"""Check if there is a winner.""" | |
# Rows, columns, diagonals | |
winning_positions = [ | |
[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 positions in winning_positions: | |
values = [self.board[pos] for pos in positions] | |
if values[0] == values[1] == values[2] and values[0] != '-': | |
return values[0] | |
return None # No winner yet | |
def is_draw(self): | |
"""Check if the game is a draw.""" | |
return all(cell != '-' for cell in self.board) | |
def get_board_string(self): | |
"""Get the current board state as a string.""" | |
return ''.join(self.board) | |
def get_legal_moves(self): | |
"""Get the positions of all legal moves.""" | |
return [i for i, cell in enumerate(self.board) if cell == '-'] | |
def pretty_print_board(self): | |
"""Pretty-print the board.""" | |
for i in range(0, 9, 3): | |
print(f"{self.board[i]} | {self.board[i+1]} | {self.board[i+2]}") | |
if i < 6: | |
print("- "*5) | |
# Test the pretty_print_board method | |
tic_tac_toe = TicTacToe() | |
print("Initial board:") | |
tic_tac_toe.pretty_print_board() | |
# Make some moves | |
tic_tac_toe.make_move(0) | |
tic_tac_toe.make_move(4) | |
tic_tac_toe.make_move(8) | |
print("\nBoard after some moves:") | |
tic_tac_toe.pretty_print_board() | |
Initial board: | |
- | - | - | |
- - - - - | |
- | - | - | |
- - - - - | |
- | - | - | |
Board after some moves: | |
X | - | - | |
- - - - - | |
- | O | - | |
- - - - - | |
- | - | X |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment