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

Python で三目並べゲームを作成する:ステップバイステップのコード チュートリアル

Python の Tic Tac Toe Game は、ぜひ試してみたい興味深いプロジェクトです。これは課題を解決するクールで楽しいプロジェクトであり、Python の基本概念をマスターするのに役立ちます。楽しい三目並べゲームを作成すると、スキルを向上させることができます。

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

チックトック ゲームの遊び方

三目並べゲームは、ゲームボードを必要とせずに誰でもプレイできるシンプルな 2 人用ゲームです。 2 人のプレイヤーが、勝利または引き分けでゲームが終了するまで、異なるセルにマークを付ける必要があります。

三目並べゲームの遊び方は次のとおりです。

ステップ 1) 三目並べゲームは、正方形のグリッド内の空のセルから始まります。これは三目並べボードです。

ステップ 2) 両プレイヤーは 2 つのシンボル (通常は X または O) から選択します。ゲーム内では他の固有のシンボルを使用できます。

ステップ 3) 現在のプレイヤーは、勝利の組み合わせを埋めるまで、三目並べボードのセルを埋めて順番にマークを付けます。それは、同じ符号を持つ行、列、または対角線全体です。

ステップ 4) すべてのセルが埋まっていて明らかな勝者がいない場合、ゲームが引き分けになる可能性もあります

要件

三目並べ Python プロジェクトを構築するには、Python プログラミング言語の初心者レベルの理解が必要です。これには、「for」ループと反復、および Python で使用される if ステートメントについての理解が含まれます。

三目並べ Python プロジェクトを完了するには、Python と Python テキスト エディターがコンピューターにインストールされている必要もあります。これは Python による初心者レベルの三目並べゲームなので、Python ライブラリは必要ありません。

コード内のバグの解決策を見つけるには、ある程度のデバッグ スキルが必要な場合があります。また、ゲーム コンポーネントについても十分に理解している必要があります。

三目並べ Python アルゴリズム

Python プログラミング言語で三目並べゲームを作成するには、次の手順に従います。

ステップ 1) 三目並べゲームを始めるためのボードを作成します。

ステップ 2) ゲームボードの寸法を決定するようユーザーに要求します。

ステップ 3) 最初のプレイヤーをランダムに選択します。

ステップ 4) 三目並べゲームが始まります。

ステップ 5) プレイヤーはボード上の空いている場所を選択してプレイします。

ステップ 6) 選択した空の場所をプレーヤーのサインで埋めます。

ステップ 7) ゲーム ロジックを使用して、プレーヤーがゲームで勝つか引き分けになるかを判断します。

ステップ 8) プレイヤーが勝てない場合、または 2 番目のプレイヤーと引き分けになった場合は、毎回のプレイ後にゲーム ボードを表示します。

ステップ 9) それぞれ引き分けまたは勝利のメッセージを表示します。

ステップ 10) 新しいゲームを開始するオプションを使用して三目並べゲームを終了します。

三目並べの完全な Python コード

# Guru99
# Code developed by Guru99.com
# Guru99 tic-tac-toe game
#Get input
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.")
# Print the game board
def printBoard(board):
 print()
 for row in board:
 print(*row)
 print()
# Check if player won using the winning combinations
def checkWin(board):
 # Check rows
 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
 # Check column numbers
 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
 # Check left diagonal
 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
 # Check right diagonal
 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
 # No win
 return False
# Play tic tac toe game
def play():
 # Introduction
 print("------------\nN-DIMENSIONAL TIC TAC TOE game by guru 99.com \n------------")
 # Set up variables
 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
 # Play guru99 tic tac toe game in Python using while infinite loop
 while True:
 # Print guru99 tic tac toe game board
 printBoard(board)
 # Get user pick
 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.")
 # Populate location
 board[pick[0]][pick[1]] = "X" if turn == 0 else "O"
 used += 1
 # Check for win
 #Guru99 tutorial
 if checkWin(board):
 printBoard(board)
 print(f"Game over, Player {turn+1} wins.")
 break
 # Check for tie
 elif used == N*N:
 printBoard(board)
 print("Game over. Players have tied the match.")
 print("Guru99.com tic tac toe game ")
 break
 # If no win yet, update next user
 turn = (turn+1)%2
 # Check for rematch
 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':
 # End the game
 print("\nGuru99 TicTacToe game ended.")
 return
 else:
 # Rematch
 play()
# Main
if __name__ == '__main__':
 play()

上記のソース コードを実行すると、以下は 3 X 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 で三目並べのボードを作成するのに役立つ手順は次のとおりです。

三目並べの 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.")
# Print the board
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 Average:Python でリストの AVERAGE を見つける方法
  2. Python-基本構文
  3. Python で三目並べゲームを作成する:ステップバイステップのコード チュートリアル
  4. 例を使用した Python map() 関数
  5. Python の type() と isinstance() と例
  6. Python 変数、定数、およびリテラル
  7. Python の For &While ループ:列挙、中断、継続ステートメント
  8. Python XML パーサー チュートリアル:xml ファイルの例を読む (Minidom、ElementTree)
  9. Python DSL:特殊なドメインに合わせたソリューション
  10. Python Main 関数とメソッドの例:def Main() を理解する
  11. Python ファイル処理:テキスト ファイルの作成、読み取り、書き込み、開く方法