# Tic-tac-toe in the basic core (experimental minimalistic programming)
# Made by Lennart and Grok Bot.
# The game program uses ONLY the 8 core commands: if, then, else, goto, Y, N, maby, .
# Y = yes, N = no, maby = the open third answer (game still open), "." = end.
# You play X, the computer plays O. Run: python tictactoe_basic_core.py

BASIC_CORE_COMMANDS = ("if", "then", "else", "goto", "Y", "N", "maby", ".")
Y, N, MABY = "Y", "N", "maby"

# ---------------------------------------------------------------------------
# The "board": small host helpers the core commands look at (conditions)
# and act on (actions). They hold no game flow - the flow is the program.
# ---------------------------------------------------------------------------
board = [" "] * 9
LINES = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]

def show():
    print()
    for r in range(3):
        print(" " + " | ".join(board[i] if board[i] != " " else str(i + 1) for i in range(r*3, r*3+3)))
        if r < 2:
            print("---+---+---")
    print()

def winner():
    for a, b, c in LINES:
        if board[a] != " " and board[a] == board[b] == board[c]:
            return board[a]
    return None

def state():
    """Y = someone has won, N = draw (board full), maby = still open."""
    if winner():
        return Y
    return N if " " not in board else MABY

def human_move():
    while True:
        try:
            s = input("Your move X (1-9): ").strip()
        except EOFError:
            raise SystemExit("\nNo more input - game stopped.")
        if s.isdigit() and 1 <= int(s) <= 9 and board[int(s) - 1] == " ":
            board[int(s) - 1] = "X"
            return
        print("That square is not free, try again.")

def find_line(mark):
    for line in LINES:
        cells = [board[i] for i in line]
        if cells.count(mark) == 2 and cells.count(" ") == 1:
            return line[cells.index(" ")]
    return None

def can_win():   return Y if find_line("O") is not None else N
def can_block(): return Y if find_line("X") is not None else N
def center_free(): return Y if board[4] == " " else N
def corner_free(): return Y if any(board[i] == " " for i in (0, 2, 6, 8)) else N

def put(i):
    board[i] = "O"
    print(f"Computer plays O on {i + 1}")

def play_win():    put(find_line("O"))
def play_block():  put(find_line("X"))
def play_center(): put(4)
def play_corner(): put(next(i for i in (0, 2, 6, 8) if board[i] == " "))
def play_side():   put(next(i for i in (1, 3, 5, 7) if board[i] == " "))
def say_winner():  print(("You win, well played!" if winner() == "X" else "Computer wins!"))
def say_draw():    print("Draw - the board is full.")

# ---------------------------------------------------------------------------
# Interpreter, compatible with run_basic_core in osmosic_computer.py.
# Extra: a line may carry a label as 3rd item, and goto may jump to a label.
# then/else/maby may also carry ("goto", label) to branch.
# ---------------------------------------------------------------------------
def run_basic_core(program, max_steps=100000):
    labels = {ln[2]: n for n, ln in enumerate(program) if len(ln) > 2}
    answer, line, steps = None, 0, 0
    while line < len(program) and steps < max_steps:
        command, value = (tuple(program[line]) + (None,))[:2]
        steps += 1
        if command not in BASIC_CORE_COMMANDS:
            raise ValueError(f"Unknown basic core command: {command}")
        if command == ".":
            break
        if command == "if":
            answer = value() if callable(value) else value
        elif command == "goto":
            line = labels.get(value, value)
            continue
        elif (command == "then" and answer == Y) or (command == "else" and answer == N) \
                or (command == "maby" and answer == MABY):
            if isinstance(value, tuple) and value[0] == "goto":
                line = labels.get(value[1], value[1])
                continue
            elif callable(value):
                value()
            else:
                print(value)
        line += 1

# ---------------------------------------------------------------------------
# The game, written only with the 8 basic core commands.
# ---------------------------------------------------------------------------
TICTACTOE = [
    ("if", Y, "start"),
    ("then", "Tic-tac-toe in the basic core. You are X, the computer is O."),
    ("then", show),
    # --- human turn ---
    ("if", Y, "human"),
    ("then", human_move),
    ("then", show),
    ("if", state),
    ("then", ("goto", "won")),
    ("else", ("goto", "draw")),
    ("maby", ("goto", "computer")),
    # --- computer turn: win, block, center, corner, side ---
    ("if", can_win, "computer"),
    ("then", play_win),
    ("then", ("goto", "after")),
    ("if", can_block),
    ("then", play_block),
    ("then", ("goto", "after")),
    ("if", center_free),
    ("then", play_center),
    ("then", ("goto", "after")),
    ("if", corner_free),
    ("then", play_corner),
    ("else", play_side),
    ("if", state, "after"),
    ("then", show),
    ("then", ("goto", "won")),
    ("else", show),
    ("else", ("goto", "draw")),
    ("maby", show),
    ("goto", "human"),
    # --- endings ---
    ("if", Y, "won"),
    ("then", say_winner),
    ("goto", "end"),
    ("if", Y, "draw"),
    ("then", say_draw),
    (".", None, "end"),
]

if __name__ == "__main__":
    run_basic_core(TICTACTOE)
