create an tic tac toe game
- User
create an tic tac toe game
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
create an tic tac toe game
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is a simple implementation of a Tic-Tac-Toe game in Python. This version allows two players to play against each other in the console.
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board, player):
# Check rows, columns, and diagonals for a win
for i in range(3):
if all([s == player for s in board[i]]): # Check rows
return True
if all([board[j][i] == player for j in range(3)]): # Check columns
return True
if board[0][0] == board[1][1] == board[2][2] == player: # Check diagonal \
return True
if board[0][2] == board[1][1] == board[2][0] == player: # Check diagonal /
return True
return False
def is_board_full(board):
for row in board:
if " " in row:
return False
return True
def tic_tac_toe():
board = [[" " for _ in range(3)] for _ in range(3)]
players = ["X", "O"]
turn = 0
while True:
print_board(board)
player = players[turn % 2]
print(f"Player {player}'s turn")
# Get move from player
while True:
try:
row = int(input("Enter row (0, 1, or 2): "))
col = int(input("Enter column (0, 1, or 2): "))
if board[row][col] == " ":
board[row][col] = player
break
else:
print("That spot is already taken. Try again.")
except (ValueError, IndexError):
print("Invalid input. Please enter row and column as 0, 1, or 2.")
if check_winner(board, player):
print_board(board)
print(f"Player {player} wins!")
break
elif is_board_full(board):
print_board(board)
print("It's a tie!")
break
turn += 1
if __name__ == "__main__":
tic_tac_toe()
tic_tac_toe.py).python tic_tac_toe.py).