I'll create a Python script for a Tic-Tac-Toe game that allows two human players to play against each other in the console. Here's a comprehensive implementation:
def print_board(board):
"""Print the current state of the board."""
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_winner(board, player):
"""Check if the current 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)]) or \
all([board[i][2-i] == player for i in range(3)]):
return True
return False
def is_board_full(board):
"""Check if the board is completely filled."""
return all(cell != " " for row in board for cell in row)
def play_tic_tac_toe():
"""Main game function."""
# Initialize the board
board = [[" " for _ in range(3)] for _ in range(3)]
# Players
current_player = "X"
while True:
# Print current board
print_board(board)
# Get player move
print(f"Player {current_player}'s turn")
while True:
try:
row = int(input("Enter row (0-2): "))
col = int(input("Enter column (0-2): "))
# Validate move
if 0 <= row <= 2 and 0 <= col <= 2 and board[row][col] == " ":
break
else:
print("Invalid move. Try again.")
except ValueError:
print("Please enter valid numbers.")
# Make the move
board[row][col] = current_player
# Check for winner
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} 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():
print("Welcome to Tic-Tac-Toe!")
while True:
play_tic_tac_toe()
play_again = input("Do you want to play again? (yes/no): ").lower()
if play_again != 'yes':
break
print("Thanks for playing!")
if __name__ == "__main__":
main()
This Tic-Tac-Toe script includes several key features:
Board Representation: A 3x3 grid represented as a nested list
Player Turns: Alternating between X and O
Move Validation:
Checks for valid row and column inputs
Prevents overwriting existing moves
Win Checking:
Checks rows, columns, and diagonals
Determines winner immediately
Draw Detection: Checks if board is completely filled
Replay Option: Allows multiple games
User-Friendly Interface: Clear instructions and board display
How to play:
Run the script
Players take turns entering row and column (0-2)
First player to get 3 in a row (horizontal, vertical, diagonal) wins
Game ends in a draw if board fills without a winner
Enjoy the game! Feel free to ask if you want any modifications or explanations about the code.