ctictactoe.py
1 state = [[0 for _ in range(3)] for _ in range(3)] 2 3 4 def num_to_cell(num: int) -> (int, int): 5 return (num - 1) % 3, 2 - (num - 1) // 3 6 7 8 def cell_to_num(x: int, y: int) -> int: 9 return (2 - y) * 3 + x + 1 10 11 12 def display(numbers: bool): 13 print("\033c", end='') 14 for i in range(3): 15 if i > 0: 16 print("---+---+---") 17 print("|".join([" " + ("\033[36m" + str(cell_to_num(j, i)) + "\033[0m" if numbers and x == 0 else " XO"[x]) + " " for j, x in 18 enumerate(state[i])])) 19 20 21 def userinput(): 22 valid = [str(cell_to_num(j, i)) for i in range(3) for j in range(3) if state[i][j] == 0] 23 x = "" 24 while x not in valid: 25 display(True) 26 x = input(">> ") 27 x, y = num_to_cell(int(x)) 28 state[y][x] = 1 29 30 31 def aimove(): 32 for y in range(3): 33 for x in range(3): 34 if state[y][x] == 0: 35 state[y][x] = 2 36 return 37 38 39 def check_state() -> int: 40 for row in state: 41 if row == [1] * 3 or row == [2] * 3: 42 return row[0] 43 for col in zip(*state): 44 if col == (1,) * 3 or col == (2,) * 3: 45 return col[0] 46 if state[0][0] == state[1][1] == state[2][2] != 0: 47 return state[0][0] 48 if state[2][0] == state[1][1] == state[0][2] != 0: 49 return state[2][0] 50 for x in range(3): 51 for y in range(3): 52 if state[y][x] == 0: 53 return -1 54 return 0 55 56 57 while check_state() == -1: 58 userinput() 59 if check_state() == -1: 60 aimove() 61 display(False) 62 print(["Draw!", "You won!", "Computer won!"][check_state()])