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')` 來清除標準終端視窗。