Python Tic-Tac-Toe 游戏脚本

在 Python 中运行终端 Tic-Tac-Toe 游戏。学习棋盘状态管理、回合切换和获胜条件检查。

在编辑器中尝试

概述

构建 Tic-Tac-Toe 游戏是一项经典练习,可强化矩阵棋盘状态表示、循环结构和条件比较逻辑。

棋盘表示为 3x3 矩阵(或 9 个元素的平面列表)。两名玩家轮流将他们的符号(“X”或“O”)放在网格上。每次移动后,脚本都会检查玩家在行、列或对角线上是否有三个匹配的符号。

此实现包括一个游戏循环,用于切换活动玩家状态、接受坐标放置,并在遇到获胜或平局条件时自动停止。

代码和执行输出

运行模拟会话的全功能命令行 Tic-Tac-Toe 游戏引擎。

tic_tac_toe.py
在编辑器中尝试
def print_board(board):
    for i in range(3):
        row = " | ".join(board[i*3:(i+1)*3])
        print(f" {row} ")
        if i < 2:
            print("---+---+---")

def check_win(board, player):
    win_states = [
        [0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
        [0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
        [0, 4, 8], [2, 4, 6]             # Diagonals
    ]
    return any(all(board[pos] == player for pos in state) for state in win_states)

def play_tic_tac_toe():
    board = [str(i+1) for i in range(9)]
    # Simulated sequence of moves (X and O alternating)
    moves = [4, 0, 8, 2, 7, 6, 3] 
    
    print("Welcome to Tic-Tac-Toe!\n")
    print_board(board)
    print("\nSimulating Gameplay...")
    
    current_player = 'X'
    for move in moves:
        if board[move] not in ['X', 'O']:
            board[move] = current_player
            print(f"\nPlayer {current_player} places on {move+1}:")
            print_board(board)
            
            if check_win(board, current_player):
                print(f"\nPlayer {current_player} wins the game!")
                return
                
            current_player = 'O' if current_player == 'X' else 'X'
            
    print("\nGame ends in a draw!")

play_tic_tac_toe()
端子输出
Welcome to Tic-Tac-Toe!

 1 | 2 | 3 
---+---+---
 4 | 5 | 6 
---+---+---
 7 | 8 | 9 

Simulating Gameplay...

Player X places on 5:
 1 | 2 | 3 
---+---+---
 4 | X | 6 
---+---+---
 7 | 8 | 9 

Player O places on 1:
 O | 2 | 3 
---+---+---
 4 | X | 6 
---+---+---
 7 | 8 | 9 

... (moves continue)

Player X wins the game!

逐步实施

  • 交互式命令行界面循环
  • 简单的人工智能极小极大路由原型
  • 学习二维列表数组坐标映射

常见问题解答

如何与电脑对战?

要实现 AI 对手,您可以使用 Python 的“random”模块来选择棋盘上的空闲插槽,或者使用 Minimax 算法创建一个无与伦比的对手。

如何在回合之间清除终端屏幕?

您可以导入 `os` 并调用 `os.system('cls' if os.name == 'nt' else 'clear')` 来清除标准终端视口。

相关主题