Here’s a simple Python script to create a Tic-Tac-Toe game that you can play in the terminal:
pythonCopy codedef 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 row in board:
if all([spot == player for spot in row]):
return True
for col in range(3):
if all([board[row][col] == player for row in range(3)]):
return True
if board[0][0] == board[1][1] == board[2][2] == player:
return True
if board[0][2] == board[1][1] == board[2][0] == player:
return True
return False
def check_tie(board):
for row in board:
if any([spot == " " for spot in row]):
return False
return True
def tic_tac_toe():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
while True:
print_board(board)
print(f"Player {current_player}'s turn")
row = int(input("Enter row (0, 1, 2): "))
col = int(input("Enter column (0, 1, 2): "))
if board[row][col] != " ":
print("Spot already taken, try again.")
continue
board[row][col] = current_player
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
if check_tie(board):
print_board(board)
print("It's a tie!")
break
current_player = "O" if current_player == "X" else "X"
if __name__ == "__main__":
tic_tac_toe()
How it works:
- print_board(board): This function prints the current state of the Tic-Tac-Toe board.
- check_winner(board, player): This function checks whether the given player (
X
orO
) has won by checking rows, columns, and diagonals. - check_tie(board): This function checks if the game is a tie by ensuring there are no empty spaces left on the board.
- tic_tac_toe(): The main function to run the game. It handles player turns, checks for wins and ties, and updates the board.
To play:
- Run the script.
- Enter the row and column numbers (0, 1, 2) when prompted to make your move.
- The game alternates between Player X and Player O until there’s a winner or a tie.
Leave a Comment