a tic tac toe game in python
- User
a tic tac toe game in python
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
a tic tac toe game in python
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a complete tic tac toe game in Python:
class TicTacToe:
def __init__(self):
self.board = [[' ' for _ in range(3)] for _ in range(3)]
self.current_player = 'X'
def display_board(self):
print("\n 0 1 2")
for i in range(3):
print(f"{i} {self.board[i][0]} | {self.board[i][1]} | {self.board[i][2]}")
if i < 2:
print(" -----------")
def make_move(self, row, col):
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
return True
return False
def check_winner(self):
# Check rows
for row in self.board:
if row[0] == row[1] == row[2] != ' ':
return row[0]
# Check columns
for col in range(3):
if self.board[0][col] == self.board[1][col] == self.board[2][col] != ' ':
return self.board[0][col]
# Check diagonals
if self.board[0][0] == self.board[1][1] == self.board[2][2] != ' ':
return self.board[0][0]
if self.board[0][2] == self.board[1][1] == self.board[2][0] != ' ':
return self.board[0][2]
return None
def is_board_full(self):
for row in self.board:
if ' ' in row:
return False
return True
def switch_player(self):
self.current_player = 'O' if self.current_player == 'X' else 'X'
def play(self):
print("Welcome to Tic Tac Toe!")
print("Players will take turns. Enter row and column (0-2) to make a move.")
while True:
self.display_board()
print(f"\nPlayer {self.current_player}'s turn")
try:
row = int(input("Enter row (0-2): "))
col = int(input("Enter column (0-2): "))
if row not in range(3) or col not in range(3):
print("Invalid input! Please enter numbers between 0 and 2.")
continue
if self.make_move(row, col):
winner = self.check_winner()
if winner:
self.display_board()
print(f"\nPlayer {winner} wins!")
break
if self.is_board_full():
self.display_board()
print("\nIt's a draw!")
break
self.switch_player()
else:
print("That position is already taken! Try again.")
except ValueError:
print("Invalid input! Please enter numbers only.")
except KeyboardInterrupt:
print("\nGame interrupted. Goodbye!")
break
if __name__ == "__main__":
game = TicTacToe()
game.play()
This tic tac toe game features:
To play, run the script and follow the prompts. Players enter row and column coordinates (0-2) to place their mark. The game continues until someone wins or the board fills up resulting in a draw.