79833949

Date: 2025-11-30 14:23:49
Score: 0.5
Natty:
Report link

Good day. I got the same task today as part of Angela Yu's Python Bootcamp, and below is my solution.
Am a newbie therefore i wanted to avoid diving into complicated concepts which I havent learnt and wanted to make it as simple as possible.

import numpy as np
from random import choice

print("Let's play Tic Tac Toe!")

board = np.array([[None, None, None], [None, None, None], [None, None, None]])


def render_uiboard(board):
    symbols = {None: "  ", "X": "❌", "O": "⭕"}
    rows = []
    for i in range(3):
        row = f"{symbols[board[i,0]]} | {symbols[board[i,1]]} | {symbols[board[i,2]]}"
        rows.append(row)

    separator = "\n-------------\n"
    return separator.join(rows)


print(render_uiboard(board), "\n")
print("Am playing ❌, I move first!")


def check_win(board, player):
    for row, col in zip(board, np.transpose(board)):
        if np.all(row == player) or np.all(col == player):
            print(f"Player {player} won!")
            return True
    main_diag = np.diagonal(board)
    antidiagonal = np.diagonal(np.fliplr(board))
    if np.all(main_diag == player) or np.all(antidiagonal == player):
        print(f"Player {player} won!")
        return True


def check_draw(board):
    return np.all(board != None)  # if no more empty cells


def get_user_coord(board):
    valid_input = False
    while not valid_input:
        input_coords = input("Your turn! Enter coords (e.g. 1 0): ")
        if input_coords in (
            "0 0",
            "0 1",
            "0 2",
            "1 0",
            "1 1",
            "1 2",
            "2 0",
            "2 1",
            "2 2",
        ):
            r, c = map(int, input_coords.split())
            if board[r, c] == None:
                valid_input = True
                return r, c
            else:
                print("That cell is already occupied. Choose another.")
        else:
            print("Please enter valid coordinates for an empty cell.")


game_over = False
while not game_over:
    empty_coords = [(r, c) for r in range(3) for c in range(3) if board[r, c] is None]
    r, c = choice(empty_coords)
    board[r, c] = "X"
    print(render_uiboard(board))
    print("\n")
    if check_win(board, "X"):
        game_over = True
        break
    if check_draw(board):
        print("It's a draw!")
        break

    r, c = get_user_coord(board)
    board[r, c] = "O"
    print(render_uiboard(board))
    print("\n")
    if check_win(board, "O"):
        game_over = True
        break
    if check_draw(board):
        print("It's a draw!")
        break

    continue
Reasons:
  • Blacklisted phrase (1): Good day
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Irena Dav