Python 三目並べゲーム スクリプト

Python でターミナル三目並べゲームを実行します。ボードの状態管理、ターンの切り替え、勝利条件のチェックを学びます。

エディターで試してみる

概要

三目並べゲームの構築は、マトリックス ボードの状態表現、ループ構造、条件付き比較ロジックを強化する古典的な演習です。

ボードは 3x3 マトリックス (または 9 つの要素のフラット リスト) として表されます。 2 人のプレーヤーが順番にシンボル (「X」または「O」) をグリッド上に配置します。各移動の後、スクリプトはプレーヤーの行、列、または対角に 3 つの一致するシンボルがあるかどうかをチェックします。

この実装には、アクティブなプレーヤーの状態を切り替え、座標の配置を受け入れ、勝利または引き分けの条件が発生すると自動的に停止するゲーム ループが含まれています。

コードと実行の出力

シミュレートされたセッションを実行する、完全に機能するコマンド ライン三目並べゲーム エンジン。

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!

段階的な実装

  • 対話型コマンドラインインターフェースループ
  • シンプルな人工知能ミニマックス ルーティング プロトタイプ
  • 2D リスト配列の座標マッピングの学習

よくある質問

どうすればコンピュータと対戦できますか?

AI 対戦相手を実装するには、Python の「random」モジュールを使用してボード上の空きスロットを選択するか、ミニマックス アルゴリズムを使用して無敵の対戦相手を作成できます。

ターンの間にターミナル画面をクリアするにはどうすればよいですか?

`os` をインポートし、`os.system('cls' if os.name == 'nt' else 'clear')` を呼び出して、標準のターミナル ビューポートをクリアできます。

関連トピック