noughts / tictactoe.py
dalyk34
Adding files
22ae33a
class TicTacToe:
def __init__(self):
self.board = [" "] * 9 # 3x3 board as a flat list
def get_board(self):
return [self.board[i:i+3] for i in range(0, 9, 3)]
def make_move(self, move, player):
# Check if the move is valid
if self.board[move] != " ":
return False, self.get_board()
self.board[move] = player
if self.check_win(player):
return True, self.get_board()
if " " not in self.board:
raise Exception("It's a draw!")
return True, self.get_board()
def check_win(self, player):
win_conditions = [
[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 condition in win_conditions:
if all(self.board[i] == player for i in condition):
return True
return False