残りのヘルパー関数を実装する
次に、残りのヘルパー関数:draw_symbols()
、is_board_full()
、is_winner()
、make_move()
、player_move()
、ai_move()
、check_game_over()
、draw_winner()
、draw_reset_button()
、およびreset_game()
を実装します。
## ヘルパー関数
def draw_symbols():
for x in range(3):
for y in range(3):
symbol = board[x][y]
if symbol == PLAYER_SYMBOL:
color = PLAYER_COLOR
elif symbol == AI_SYMBOL:
color = AI_COLOR
else:
color = EMPTY_COLOR
if symbol!= "":
pygame.draw.circle(
win,
color,
(x * CELL_SIZE + CELL_SIZE // 2, y * CELL_SIZE + CELL_SIZE // 2),
CELL_SIZE // 2 - 10,
2,
)
def is_board_full():
for row in board:
if "" in row:
return False
return True
def is_winner(symbol):
for row in board:
if all(cell == symbol for cell in row):
return True
for col in range(3):
if all(board[row][col] == symbol for row in range(3)):
return True
if all(board[i][i] == symbol for i in range(3)):
return True
if all(board[i][2 - i] == symbol for i in range(3)):
return True
return False
def make_move(x, y, symbol):
if board[x][y] == "":
board[x][y] = symbol
return True
return False
def player_move():
global turn
mouse_pos = pygame.mouse.get_pos()
cell_x = mouse_pos[0] // CELL_SIZE
cell_y = mouse_pos[1] // CELL_SIZE
if make_move(cell_x, cell_y, PLAYER_SYMBOL):
turn = "ai"
def ai_move():
global turn
empty_cells = []
for x in range(3):
for y in range(3):
if board[x][y] == "":
empty_cells.append((x, y))
if empty_cells:
x, y = random.choice(empty_cells)
make_move(x, y, AI_SYMBOL)
turn = "player"
def check_game_over():
global game_over, winner
if is_winner(PLAYER_SYMBOL):
game_over = True
return "player"
elif is_winner(AI_SYMBOL):
game_over = True
return "ai"
elif is_board_full():
game_over = True
return "tie"
return None
def draw_winner():
font = pygame.font.Font(None, 50)
if winner == "player":
text = font.render("Player Wins!", True, PLAYER_COLOR)
elif winner == "ai":
text = font.render("AI Wins!", True, AI_COLOR)
else:
text = font.render("It's a Tie!", True, (255, 255, 255))
text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 3))
win.blit(text, text_rect)
def draw_reset_button():
pygame.draw.rect(win, BUTTON_COLOR, reset_button_rect)
button_text = BUTTON_FONT.render("Reset", True, BUTTON_TEXT_COLOR)
button_text_rect = button_text.get_rect(center=reset_button_rect.center)
win.blit(button_text, button_text_rect)
def reset_game():
global board, turn, game_over, winner
board = [["" for _ in range(3)] for _ in range(3)]
turn = "player"
game_over = False
winner = None
上記のコードでは、draw_symbols()
関数が盤面に記号を描画します。is_board_full()
関数が盤面が埋まっているかどうかを確認します。is_winner()
関数が与えられた記号がゲームに勝利したかどうかを確認します。make_move()
関数が盤面に手を打ちます。player_move()
関数がプレイヤーの手番を処理します。ai_move()
関数がAIの手番を処理します。check_game_over()
関数がゲームが終了したかどうかを確認します。draw_winner()
関数が勝者のメッセージを描画します。draw_reset_button()
関数がリセットボタンを描画します。reset_game()
関数がゲームをリセットします。