# ===== CodeLab: Python 小游戏④:井字棋 =====
# 来源: https://aoerliang.dpdns.org/articles/game-python-tictactoe
# 以下代码片段按文章出现顺序拼接, 共 5 段

# ----- 片段 1 (python) -----
board = [" "] * 9

def show():
    for row in range(3):
        line = board[row * 3 : row * 3 + 3]
        print(" | ".join(line))
        if row < 2:
            print("---------")

show()

# ----- 片段 2 (python) -----
while True:
    text = input("轮到 X,请选择格子(0-8): ")
    if not text.isdigit():
        print("请输入数字!")
        continue
    pos = int(text)
    if pos < 0 or pos > 8:
        print("编号要在 0 到 8 之间!")
        continue
    if board[pos] != " ":
        print("这个格子已经有棋子了!")
        continue
    board[pos] = "X"
    break

# ----- 片段 3 (python) -----
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 winner():
    for a, b, c in LINES:
        if board[a] == board[b] == board[c] != " ":
            return board[a]   # 返回 'X' 或 'O'
    return None

# ----- 片段 4 (python) -----
import random

empty = [i for i in range(9) if board[i] == " "]
move = random.choice(empty)
board[move] = "O"
print(f"电脑落在了 {move} 号格子")

# ----- 片段 5 (python) -----
import random

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():
    for row in range(3):
        print(" | ".join(board[row*3:row*3+3]))
        if row < 2:
            print("---------")

def winner():
    for a, b, c in LINES:
        if board[a] == board[b] == board[c] != " ":
            return board[a]
    return None

def player_move():
    while True:
        text = input("轮到 X,请选择格子(0-8): ")
        if not text.isdigit():
            print("请输入数字!")
            continue
        pos = int(text)
        if pos < 0 or pos > 8 or board[pos] != " ":
            print("无效位置,重新选!")
            continue
        board[pos] = "X"
        return

while True:
    show()
    player_move()
    if winner():
        print(f"\n{winner()} 获胜!")
        break
    if " " not in board:
        print("\n平局!")
        break
    empty = [i for i in range(9) if board[i] == " "]
    board[random.choice(empty)] = "O"

show()
