File size: 1,628 Bytes
1f2d366 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# -*- 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() |