make a tic tac toe game in python
- User
make 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.
make 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:
def print_board(board):
"""Display the game board"""
print("\n | | ")
print(f" {board[0]} | {board[1]} | {board[2]} ")
print("___|___|___")
print(" | | ")
print(f" {board[3]} | {board[4]} | {board[5]} ")
print("___|___|___")
print(" | | ")
print(f" {board[6]} | {board[7]} | {board[8]} ")
print(" | | \n")
def check_winner(board):
"""Check if there's a winner"""
# Winning combinations
win_patterns = [
[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 pattern in win_patterns:
if board[pattern[0]] == board[pattern[1]] == board[pattern[2]] != ' ':
return board[pattern[0]]
return None
def is_board_full(board):
"""Check if the board is full"""
return ' ' not in board
def get_move(player, board):
"""Get a valid move from the player"""
while True:
try:
move = int(input(f"Player {player}, enter your move (1-9): ")) - 1
if 0 <= move <= 8 and board[move] == ' ':
return move
else:
print("Invalid move! That space is already taken or out of range.")
except ValueError:
print("Please enter a number between 1 and 9.")
def play_game():
"""Main game function"""
# Initialize the board
board = [' '] * 9
current_player = 'X'
print("Welcome to Tic-Tac-Toe!")
print("Positions are numbered 1-9 as shown below:")
print_board(['1', '2', '3', '4', '5', '6', '7', '8', '9'])
while True:
# Display current board
print_board(board)
# Get player move
move = get_move(current_player, board)
board[move] = current_player
# Check for winner
winner = check_winner(board)
if winner:
print_board(board)
print(f"Player {winner} wins!")
break
# Check for draw
if is_board_full(board):
print_board(board)
print("It's a draw!")
break
# Switch players
current_player = 'O' if current_player == 'X' else 'X'
def main():
"""Main function to run the game with replay option"""
while True:
play_game()
play_again = input("\nDo you want to play again? (yes/no): ").lower()
if play_again != 'yes' and play_again != 'y':
print("Thanks for playing!")
break
if __name__ == "__main__":
main()
This tic-tac-toe game includes:
To play, simply run the script and follow the prompts. Players take turns entering numbers 1-9 to place their marks on the board.