TicTacToeGame / 371_159_252.py
antitheft159's picture
Upload 371_159_252.py
1f2d366 verified
raw
history blame
1.63 kB
# -*- coding: utf-8 -*-
"""371.159.252
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1oXKGaEE20mV4mo0M2oDOSiIZ1ihX0tYc
"""
def print_board(board):
print("\n".join((" | ".join(row) for row in board)))
print("\n")
def check_winner(board, player):
for row in board:
if all(cell == player for cell in row):
return True
for col in range(3):
if all(row[col] == player for row in board):
return True
if all(board[i][2 - i] == player for i in range(3)):
return True
return False
def is_full(board):
return all(cell !=" " for row in board for cell in row)
def get_move():
while True:
try:
move = int(input("Enter your move (1-9): "))
if move < 1 or move > 9:
print("Invalid move. Please enter a number between 1 and 9.")
else:
return move - 1
except ValueError:
print("Invalid input. Pleas enter a number.")
def play_game():
board = [[" " for _ in range(3)] for _ in range(3)]
player = ["X", "O"]
current_player = 0
print("welcome to Tic Tac Toe!")
print_board(board)
while True:
move = get_move()
row, col = divmod(move, 3)
if board[row][col] != " ":
print("Cell already taken. Try again.")
continue
board[row][col] = player[current_player]
print_board(board)
if check_winner(board, player[current_player]):
print(f"Player {player[current_player]} wins!")
break
if is_full(board):
print("It's a draw!")
break
current_player = 1 - current_player
if __name__ == "__main__":
play_game()