この記事では、Python初心者の方向けに、基本的なプログラミングの概念(関数、ループ、条件分岐)を使用して、CLI(コマンドラインインターフェース)上で動作するマルバツゲームを作成していきます!
Pythonで制作できるゲーム一覧はこちらの記事で確認できます!
はじめに
マルバツゲームは、2人のプレイヤーが交互に、3×3のグリッドにマーク(通常はXとO)を置いていき、先に縦・横・斜めのいずれかで自分のマークを3つ並べたプレイヤーが勝ちとなるゲームです。このゲームを作成することで、Pythonの基礎を固めることができます。
必要な機能
- ボードの表示
- ユーザー入力の処理
- 勝利条件のチェック
- ゲームの状態(勝者がいるか、引き分けか)の判断
- ゲームのリセット
ステップ1: ボードの表示
まずは、ゲームのボードを表示する関数を作成します。ボードはリストを使用して表現します。
def display_board(board):
print(board[0] + '|' + board[1] + '|' + board[2])
print('-+-+-')
print(board[3] + '|' + board[4] + '|' + board[5])
print('-+-+-')
print(board[6] + '|' + board[7] + '|' + board[8])
Pythonでのゲーム制作を学びたい人はこちらの書籍がおすすめです!
ステップ2: ユーザー入力の処理
プレイヤーがボード上のどの位置にマークを置くかを決めるために、ユーザーから入力を受け付ける関数を作成します。ただし、注意点として、すでに埋まっているマスには置けないようにする必要があります。
def player_input(board, player):
position = 0
valid = False
while not valid:
try:
position = int(input(f"Player {player}, enter your move (1-9): ")) - 1
if position not in range(0, 9):
print("Invalid input. Please enter a number between 1 and 9.")
elif board[position] != ' ':
print("This spot is already taken. Please choose another spot.")
else:
valid = True
except ValueError:
print("Invalid input. Please enter a number.")
board[position] = player
この関数では、まずプレイヤーから入力を受け取ります。入力が有効(1から9の数字で、指定された位置が空いている)かどうかをチェックします。入力が無効な場合は、適切なメッセージを出力して、もう一度入力を求めます。このプロセスを有効な入力を受け取るまで繰り返します。
AIを使ってPythonのプログラムを簡単に生成したい方にオススメ!
ステップ3: 勝利条件のチェック
ゲームの勝利条件をチェックする関数を作成します。
def check_win(board, mark):
win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4, 6)]
for condition in win_conditions:
if board[condition[0]] == board[condition[1]] == board[condition[2]] == mark:
return True
return False
ステップ4: ゲームの状態の判断
ゲームが終了したかどうかを判断する関数を作成します。勝者がいるか、ボードが埋まって引き分けになったかをチェックします。
def check_game_over(board):
if ' ' not in board or check_win(board, 'X') or check_win(board, 'O'):
return True
return False
ステップ5: ゲームの実行
これらの関数を組み合わせて、ゲームを実行するメインループを作成します。
def play_game():
board = [' '] * 9
current_player = 'X'
while not check_game_over(board):
display_board(board)
player_input(board, current_player)
if check_win(board, current_player):
display_board(board)
print(f"Player {current_player} wins!")
break
if ' ' not in board:
display_board(board)
print("The game is a tie!")
break
current_player = 'O' if current_player == 'X' else 'X'
print("Game over.")
ステップ6: ゲームの開始
最後に、ゲームを実際に開始するためのコードを追加します。
if __name__ == "__main__":
play_game()
Pythonでのゲーム制作を学びたい人はこちらの書籍がおすすめです!
コード全体
def display_board(board):
print(board[0] + '|' + board[1] + '|' + board[2])
print('-+-+-')
print(board[3] + '|' + board[4] + '|' + board[5])
print('-+-+-')
print(board[6] + '|' + board[7] + '|' + board[8])
def player_input(board, player):
position = 0
valid = False
while not valid:
try:
position = int(input(f"Player {player}, enter your move (1-9): ")) - 1
if position not in range(0, 9):
print("Invalid input. Please enter a number between 1 and 9.")
elif board[position] != ' ':
print("This spot is already taken. Please choose another spot.")
else:
valid = True
except ValueError:
print("Invalid input. Please enter a number.")
board[position] = player
def check_win(board, mark):
win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4, 6)]
for condition in win_conditions:
if board[condition[0]] == board[condition[1]] == board[condition[2]] == mark:
return True
return False
def check_game_over(board):
if ' ' not in board or check_win(board, 'X') or check_win(board, 'O'):
return True
return False
def play_game():
board = [' '] * 9
current_player = 'X'
while not check_game_over(board):
display_board(board)
player_input(board, current_player)
if check_win(board, current_player):
display_board(board)
print(f"Player {current_player} wins!")
break
if ' ' not in board:
display_board(board)
print("The game is a tie!")
break
current_player = 'O' if current_player == 'X' else 'X'
print("Game over.")
if __name__ == "__main__":
play_game()
まとめ
さて、このチュートリアルでは、Pythonで簡単なマルバツゲームを作成しました。
ここでここまで記事を読んでいただいた皆さんにお知らせしなければならないことがあります…
実は、このプログラム、ChatGPTに全て書いてもらっているのです。
ChatGPTを使えば、今までエンジニアが数時間掛けて書いていたコードを、ものの3分で作成してくれます。
これからエンジニアとして活躍したい方、文系からエンジニアを目指したい方は、ぜひChatGPTの活用方法を学んで、高度なIT人材になりましょう!
ChatGPTを使ってPythonでゲームを制作したい方は、こちらのAIスクールがおすすめです!