工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Python

Pythonで三目並べ(Tic Tac Toe)ゲームを作ろう:ステップバイステップコードチュートリアル

Pythonで三目並べゲームを作るのは、基本概念をマスターするのに最適な楽しいプロジェクトです。課題解決を通じてスキルアップできます。

PyCharmなどの優れたPythonエディタやコマンドラインインターフェースを使用できます。

三目並べゲームの遊び方

三目並べは、ゲームボードがなくても楽しめるシンプルな2人用ゲームです。2人のプレイヤーが異なるセルに印をつけ、勝利または引き分けになるまで続けます。

遊び方の手順:

ステップ1: 空のセルで構成される正方形のグリッドからゲーム開始。これがボードになります。

ステップ2: 両プレイヤーは通常「X」と「O」の2つの記号から選択。他のユニークな記号でも可。

ステップ3: 現在のプレイヤーが順番にボードのセルを埋め、あるプレイヤーが縦・横・斜めのいずれか一列を自分の記号で揃えると勝利。

ステップ4: 全セルが埋まっても勝者がいない場合は引き分け。

必要条件

このプロジェクトにはPythonプログラミングの初級理解が必要です。forループ、イテレーション、if文の理解が含まれます。

また、PythonとPythonテキストエディタがインストール済みである必要があります。初級レベルのゲームなので、外部ライブラリは不要です。

デバッグスキルやゲーム構成要素の理解もあると良いでしょう。

三目並べPythonアルゴリズム

以下の手順でPythonで三目並べゲームを作成します。

ステップ1: ボードを作成してゲーム開始準備

ステップ2: ユーザーにボードの次元数を決定させる

ステップ3: 先手プレイヤーをランダムに選択

ステップ4: ゲーム開始

ステップ5: プレイヤーがボードの空きマスを選択

ステップ6: 選択されたマスにプレイヤーの記号を配置

ステップ7: ゲームロジックで勝敗または引き分けを判定

ステップ8: 勝敗が決まらない場合、ボードを表示して次のプレイヤーへ

ステップ9: 引き分けまたは勝利メッセージを表示

ステップ10: 新規ゲーム開始オプション付きでゲーム終了

三目並べの完全Pythonコード

# Guru99
# Code developed by Guru99.com
# Guru99 tic-tac-toe game

# 入力取得関数
def getInput(prompt, cast=None, condition=None, errorMessage=None):
    while True:
        try:
            val = cast(input(prompt))
            assert condition is None or condition(val)
            return val
        except:
            print(errorMessage or "Invalid input.")

# ゲームボード表示
def printBoard(board):
    print()
    for row in board:
        print(*row)
    print()

# 勝利判定(勝利パターンをチェック)
def checkWin(board):
    # 行チェック
    for row in range(len(board)):
        for col in range(len(board)-1):
            if board[row][col] == "_" or board[row][col+1] == "_" or board[row][col] != board[row][col+1]:
                break
        else:
            return True
    # 列チェック
    for col in range(len(board)):
        for row in range(len(board)-1):
            if board[row][col] == "_" or board[row+1][col] == "_" or board[row][col] != board[row+1][col]:
                break
        else:
            return True
    # 左斜めチェック
    for cell in range(len(board)-1):
        if board[cell][cell] == "_" or board[cell+1][cell+1] == "_" or board[cell][cell] != board[cell+1][cell+1]:
            break
        else:
            return True
    # 右斜めチェック
    for cell in range(len(board)-1):
        emptyCell = board[cell][len(board)-cell-1] == "_" or board[cell+1][len(board)-cell-2] == "_"
        different = board[cell][len(board)-cell-1] != board[cell+1][len(board)-cell-2]
        if emptyCell or different:
            break
        else:
            return True
    # 勝利なし
    return False

# ゲームメインループ
def play():
    # イントロ
    print("------------\nN-DIMENSIONAL TIC TAC TOE game by guru 99.com \n------------")
    # 変数設定
    N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ", cast=int, condition=lambda x: x >= 3, errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com")
    board = [['_'] * N for _ in range(N)]
    used = 0
    turn = 0
    # 無限ループでゲーム進行
    while True:
        # ボード表示
        printBoard(board)
        # ユーザー入力取得
        pick = getInput(prompt=f"Player {turn+1} - Pick location (row, col): ", cast=lambda line: tuple(map(int, line.split(" "))), condition=lambda pair: min(pair) >= 0 and max(pair) < N and board[pair[0]][pair[1]] == "_", errorMessage="Invalid input. Please enter a valid, unoccupied location as an integer pair.")
        # 選択場所に記号配置
        board[pick[0]][pick[1]] = "X" if turn == 0 else "O"
        used += 1
        # 勝利判定
        if checkWin(board):
            printBoard(board)
            print(f"Game over, Player {turn+1} wins.")
            break
        # 引き分け判定
        elif used == N*N:
            printBoard(board)
            print("Game over. Players have tied the match.")
            print("Guru99.com tic tac toe game ")
            break
        # 次のプレイヤーへ
        turn = (turn+1)%2
        # リマッチ確認
        playAgain = getInput(prompt="Play Guru99 tic tac toe_Game again? (y/n): ", cast=str, condition=lambda ans: ans.strip("\n").lower() in {"y", "n"}, errorMessage="Invalid input. Please enter 'y' or 'n'.")
        if playAgain == 'n':
            print("\nGuru99 TicTacToe game ended.")
            return
        else:
            play()

# メイン実行
if __name__ == '__main__':
    play()

上記ソースコードを実行すると、3×3ボードで以下のような出力が得られます。

------------
N-DIMENSIONAL TIC TAC TOE game by guru 99.com
------------
Guru99 says>>> Enter N, the dimensions of the board: 3
_ _ _
_ _ _
_ _ _
Player 1 - Pick location (row, col): 1 1
_ _ _
_ X _
_ _ _
Player 2 - Pick location (row, col): 0 1
_ O _
_ X _
_ _ _
Player 1 - Pick location (row, col): 1 2
_ O _
_ X X
_ _ _
Player 2 - Pick location (row, col): 0 2
_ O O
_ X X
_ _ _
Player 1 - Pick location (row, col): 1 0
_ O O
X X X
_ _ _
Game over, Player 1 wins.
Play Guru99 tic tac toe_Game again? (y/n):

コードの詳細解説

Pythonでの三目並べ作成はシンプルです。各関数を分解して、各行が何をしているか理解しましょう。

ボードの表示

三目並べボードはメインのゲーム表示です。Pythonではディスプレイウィンドウでボードを表示します。

ボード作成の手順:

三目並べ用Pythonコード

def getInput(prompt, cast=None, condition=None, errorMessage=None):
    while True:
        try:
            val = cast(input(prompt))
            assert condition is None or condition(val)
            return val
        except:
            print(errorMessage or "Invalid input.")

# ボード表示
def printBoard(board):
    print()
    for row in board:
        print(*row)
    print()

N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ", cast=int, condition=lambda x: x >= 3, errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com")
board = [['_'] * N for _ in range(N)]
used = 0
turn = 0
printBoard(board)

コード出力:

------------
N-DIMENSIONAL TIC TAC TOE game by guru 99.com
------------
Guru99 says>>> Enter N, the dimensions of the board: 3
_ _ _
_ _ _
_ _ _

三目並べゲーム – 勝利条件の判定

プレイヤーの勝利を判定するには、行・列・斜めの勝利パターンをチェックします。勝者がいれば勝利メッセージを表示します。

行の判定

列の判定

列についても行と同様の関数でチェック。各プレイヤーの手番後に勝利判定を行います。

斜めの勝利判定

左斜めはシンプル。常に斜めのセル同士を比較します。勝者がいなければ次の処理へ進みます。

ゲームロジックの実行

これがメインのゲーム関数です。情報を格納する変数を用意します。

まとめ

Python

  1. Pythonタプル完全ガイド:作成、アクセス、高度な操作
  2. Python 型変換とキャスト: 包括的ガイド
  3. IPythonをマスターしてPythonの生産性を大幅アップ
  4. Pythonで数値の二乗を求める6つの効果的な方法
  5. Pythonで平均を計算する:実践ガイド
  6. Python type()とisinstance()の理解:実例付き解説
  7. Python attrs入門:高機能データクラスを実践例でマスター
  8. Python vs PHP:主要な違い、強み、適切な言語選択
  9. Python正規表現(reモジュール)実践ガイド
  10. Python 変数・定数・リテラル: 包括的ガイド
  11. Pythonクロージャ解説:ネスト関数が変数を捕捉する仕組み