0% found this document useful (0 votes)
7 views3 pages

Tic Tac Toe

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

Tic Tac Toe

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

# Initialize the board as a list of 9 empty strings

board = [" " for _ in range(9)]

def print_board():
"""Prints the current state of the Tic-Tac-Toe board."""
print(f"| {board[0]} | {board[1]} | {board[2]} |")
print("-------------")
print(f"| {board[3]} | {board[4]} | {board[5]} |")
print("-------------")
print(f"| {board[6]} | {board[7]} | {board[8]} |")

def player_move(player_char):
"""Allows a player to make a move."""
while True:
try:
move = int(input(f"Player {player_char}, enter your move (1-9): ")) - 1
if 0 <= move <= 8 and board[move] == " ":
board[move] = player_char
break
else:

print("Invalid move. That spot is either taken or out of bounds. Try again.")

except ValueError:
print("Invalid input. Please enter a number between 1 and 9.")

def check_win(player_char):
"""Checks if the given player has won."""
winning_combinations = [
(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 combo in winning_combinations:
if board[combo[0]] == board[combo[1]] == board[combo[2]] == player_char:
return True
return False

def check_tie():
"""Checks if the game is a tie (board is full and no winner)."""
return " " not in board

def play_game():
"""Manages the main game loop."""
current_player = "X"
game_over = False

while not game_over:


print_board()
player_move(current_player)

if check_win(current_player):
print_board()
print(f"Player {current_player} wins!")
game_over = True
elif check_tie():
print_board()
print("It's a tie!")
game_over = True
else:
current_player = "O" if current_player == "X" else "X"

# Start the game


if __name__ == "__main__":
play_game()

Explanation:
 board list: Represents the 3x3 Tic-Tac-Toe board. Each element corresponds to a cell,
initialized with a space (" ").
 print_board(): Displays the current state of the board in a readable format.
 player_move(player_char): Prompts the current player to enter their move (a number from
1 to 9). It validates the input to ensure it's a valid, empty cell before placing the player's
character.
 check_win(player_char): Defines all possible winning combinations and checks if the
given player_char occupies any of these combinations.
 check_tie(): Determines if the board is full, indicating a tie if no player has won.
 play_game(): This is the main function that orchestrates the game flow:
o It initializes the current_player to "X".
o It enters a while loop that continues until game_over is True.
o Inside the loop, it prints the board, gets the current player's move, checks for a win or tie,
and then switches the current_player.
 if __name__ == "__main__":: Ensures that play_game() is called only when the script is
executed directly.

You might also like