@unixdude I like your tic-tac-toe It’s perfect
Try this one by (Gemini flash 2.0) I fixed some errors.
import os
def clear_screen():
"""Clears the terminal screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def draw_board(board):
"""Draws the Tic-Tac-Toe board."""
clear_screen()
print("---------")
for i in range(3):
print(f"| {board[i][0]} | {board[i][1]} | {board[i][2]} |")
print("---------")
def check_win(board, player):
"""Checks if a player has won."""
# Check rows
for row in board:
if all(cell == player for cell in row):
return True
# Check columns
for col in range(3):
if all(board[row][col] == player for row in range(3)):
return True
# Check diagonals
if all(board[i][i] == player for i in range(3)):
return True
if all(board[i][2 - i] == player for i in range(3)):
return True
return False
def check_draw(board):
"""Checks if the game is a draw."""
return all(cell != " " for row in board for cell in row)
def get_move(board, player):
"""Gets the player's move."""
while True:
try:
move = int(input(f"Player {player}, enter your move (1-9): ")) - 1
row, col = divmod(move, 3)
if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == " ":
return row, col
else:
print("Invalid move. Try again.")
except (ValueError, IndexError):
print("Invalid input. Enter a number between 1 and 9.")
def tic_tac_toe():
"""Plays a game of Tic-Tac-Toe."""
board = [[" " for _ in range(3)] for _ in range(3)]
players = ["X", "O"]
current_player = 0
while True:
draw_board(board)
row, col = get_move(board, players[current_player])
board[row][col] = players[current_player]
if check_win(board, players[current_player]):
draw_board(board)
print(f"Player {players[current_player]} wins!")
break
elif check_draw(board):
draw_board(board)
print("It's a draw!")
break
current_player = 1 - current_player # Switch players
if __name__ == "__main__":
tic_tac_toe()