Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

use pygame to write a Gobang game, including against AI mode

  1. User

    use pygame to write a Gobang game, including against AI mode

  2. Assistant

    Certainly! Below is a complete implementation of a Gobang (Five in a Row) game using Pygame, which includes a simple AI opponent mode. This implementation provides a basic yet functional game that allows you to play against the computer.


    Table of Contents

    1. Prerequisites
    2. Game Overview
    3. Implementation Details
    4. Complete Source Code
    5. Running the Game
    6. Enhancements

    Prerequisites

    To run the Gobang game, ensure you have the following installed on your system:

    • Python 3.x: You can download it from python.org.

    • Pygame Library: Install it using pip:

      pip install pygame
      

    Game Overview

    Gobang, also known as Five in a Row, is a strategic board game traditionally played with black and white stones on a grid. The objective is to be the first to form an unbroken chain of five stones horizontally, vertically, or diagonally.

    In this implementation:

    • You play as Black.
    • The AI plays as White.
    • The game checks for a win after every move.
    • If the board is full without any player winning, the game ends in a draw.

    Implementation Details

    Key Components

    1. Board Representation: The game board is represented as a 2D list (15x15 grid). Each cell can be:

      • 0: Empty
      • 1: Black stone (Player)
      • -1: White stone (AI)
    2. Drawing the Board: Utilizes Pygame's drawing functions to render the grid and stones.

    3. Player Interaction: Captures mouse clicks to place stones.

    4. AI Logic: Implements a basic AI that selects the next best move based on simple heuristics. For a more challenging AI, consider implementing algorithms like Minimax with Alpha-Beta pruning.

    5. Win Detection: After each move, the game checks all possible directions (horizontal, vertical, both diagonals) for five consecutive stones.

    6. Game Loop: Manages the flow of the game, alternating turns between the player and the AI, and handling game-over scenarios.


    Complete Source Code

    Here's the complete Python script for the Gobang game using Pygame:

    import pygame
    import sys
    import math
    import copy
    
    # Initialize Pygame
    pygame.init()
    
    # Set up constants
    BOARD_SIZE = 15  # 15x15 board
    CELL_SIZE = 40    # Size of each cell in pixels
    MARGIN = 50       # Margin around the board
    WINDOW_SIZE = MARGIN * 2 + CELL_SIZE * (BOARD_SIZE - 1)
    FPS = 30
    
    # Colors (R, G, B)
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    BG_COLOR = (222, 184, 135)  # Burlywood color
    LINE_COLOR = (0, 0, 0)
    HIGHLIGHT_COLOR = (255, 0, 0)
    
    # Set up the display
    screen = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE))
    pygame.display.set_caption("Gobang (Five in a Row)")
    clock = pygame.time.Clock()
    
    # Initialize game state
    board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
    current_player = 1  # 1 for human (black), -1 for AI (white)
    game_over = False
    winner = None
    
    def draw_board():
        """Draw the game board and stones."""
        screen.fill(BG_COLOR)
        # Draw grid lines
        for i in range(BOARD_SIZE):
            # Horizontal lines
            pygame.draw.line(screen, LINE_COLOR,
                             (MARGIN, MARGIN + i * CELL_SIZE),
                             (WINDOW_SIZE - MARGIN, MARGIN + i * CELL_SIZE), 1)
            # Vertical lines
            pygame.draw.line(screen, LINE_COLOR,
                             (MARGIN + i * CELL_SIZE, MARGIN),
                             (MARGIN + i * CELL_SIZE, WINDOW_SIZE - MARGIN), 1)
        # Draw stones
        for y in range(BOARD_SIZE):
            for x in range(BOARD_SIZE):
                if board[y][x] != 0:
                    if board[y][x] == 1:
                        color = BLACK
                    else:
                        color = WHITE
                    pygame.draw.circle(screen, color,
                                       (MARGIN + x * CELL_SIZE, MARGIN + y * CELL_SIZE),
                                       CELL_SIZE // 2 - 2)
        pygame.display.flip()
    
    def get_grid_pos(pos):
        """Convert pixel position to grid coordinates."""
        x_pixel, y_pixel = pos
        x = round((x_pixel - MARGIN) / CELL_SIZE)
        y = round((y_pixel - MARGIN) / CELL_SIZE)
        if 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE:
            return x, y
        else:
            return None
    
    def is_valid_move(x, y):
        """Check if a move is valid (cell is empty)."""
        return board[y][x] == 0
    
    def check_win(x, y):
        """Check if the current move at (x, y) wins the game."""
        def count(direction):
            """Count consecutive stones in a given direction."""
            dx, dy = direction
            cnt = 1  # Count the current stone
            # Check in the positive direction
            i = 1
            while True:
                nx, ny = x + dx * i, y + dy * i
                if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE and board[ny][nx] == board[y][x]:
                    cnt += 1
                    i += 1
                else:
                    break
            # Check in the negative direction
            i = 1
            while True:
                nx, ny = x - dx * i, y - dy * i
                if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE and board[ny][nx] == board[y][x]:
                    cnt += 1
                    i += 1
                else:
                    break
            return cnt
    
        # Directions: (dx, dy)
        directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
        for direction in directions:
            if count(direction) >= 5:
                return board[y][x]
        return 0
    
    def evaluate_move(x, y, player):
        """Simple evaluation function for AI (can be enhanced)."""
        # For simplicity, count the number of stones adjacent to the move
        score = 0
        directions = [(-1, -1), (-1, 0), (-1, 1),
                      (0, -1),          (0, 1),
                      (1, -1),  (1, 0), (1, 1)]
        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE:
                if board[ny][nx] == player:
                    score += 1
        return score
    
    def game_ai():
        """Basic AI to select the next move."""
        best_score = -math.inf
        best_move = None
        for y in range(BOARD_SIZE):
            for x in range(BOARD_SIZE):
                if board[y][x] == 0:
                    # Evaluate move for AI
                    board[y][x] = -1  # AI makes a temporary move
                    score = evaluate_move(x, y, -1)
                    board[y][x] = 0  # Undo move
                    if score > best_score:
                        best_score = score
                        best_move = (x, y)
        if best_move:
            return best_move
        # If no good move found, choose the center or random
        center = BOARD_SIZE // 2
        if board[center][center] == 0:
            return (center, center)
        for y in range(BOARD_SIZE):
            for x in range(BOARD_SIZE):
                if board[y][x] == 0:
                    return (x, y)
        return None
    
    def main():
        global current_player, game_over, winner
    
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
    
                # Player's move
                if not game_over and current_player == 1 and event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    grid_pos = get_grid_pos(pos)
                    if grid_pos:
                        x, y = grid_pos
                        if is_valid_move(x, y):
                            board[y][x] = 1  # Place black stone
                            if check_win(x, y):
                                game_over = True
                                winner = "Black (You)"
                            current_player = -1  # Switch to AI
    
            # AI's turn
            if not game_over and current_player == -1:
                pygame.time.delay(300)  # Brief pause for AI move
                move = game_ai()
                if move:
                    x, y = move
                    board[y][x] = -1  # Place white stone
                    if check_win(x, y):
                        game_over = True
                        winner = "White (AI)"
                    current_player = 1  # Switch back to player
    
            # Drawing the board
            draw_board()
    
            # Display winner
            if game_over:
                font = pygame.font.SysFont(None, 48)
                text = font.render(f"{winner} Wins!", True, HIGHLIGHT_COLOR)
                text_rect = text.get_rect(center=(WINDOW_SIZE//2, WINDOW_SIZE//2))
                screen.blit(text, text_rect)
                pygame.display.flip()
                pygame.time.wait(3000)  # Wait for 3 seconds
                # Reset the game
                board[:] = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
                game_over = False
                winner = None
                current_player = 1
    
            clock.tick(FPS)
    
    if __name__ == "__main__":
        main()
    

    Running the Game

    1. Save the Code: Copy the above script into a file named, for example, gobang.py.

    2. Install Pygame: If you haven't already installed Pygame, do so using pip:

      pip install pygame
      
    3. Run the Game:

      python gobang.py
      
    4. Playing the Game:

      • Human Player: Click on the desired cell to place a black stone.
      • AI Player: The AI will automatically place a white stone after your move.
      • Winning the Game: The game declares a winner when five consecutive stones are aligned horizontally, vertically, or diagonally.
      • Restarting: After a win, the game resets automatically after a short pause.

    Enhancements

    The provided AI is quite basic. For a more challenging opponent, consider implementing the following enhancements:

    1. Minimax Algorithm with Alpha-Beta Pruning:

      • Minimax: A decision rule for minimizing the possible loss while maximizing the potential gain.
      • Alpha-Beta Pruning: An optimization to the Minimax algorithm that reduces the number of nodes evaluated.
    2. Heuristic Evaluation Function:

      • Assign scores to board positions based on various factors like open sequences, potential threats, etc.
    3. Depth Limitation:

      • Limit the depth of the search tree to ensure the AI makes decisions within a reasonable time frame.
    4. Pattern Recognition:

      • Identify common patterns (e.g., open threes, fours) to make more informed decisions.
    5. Multi-threading:

      • Use separate threads to handle AI computations to keep the UI responsive.

    Implementing these features requires a more in-depth understanding of game algorithms and can significantly enhance the AI's performance and challenge level.


    Conclusion

    This implementation provides a foundational structure for a Gobang game using Pygame, complete with a simple AI opponent. While the AI here uses basic heuristics, there's ample room for improvement and customization. Whether you're a beginner looking to understand game development with Pygame or an enthusiast aiming to build a more sophisticated AI, this project serves as an excellent starting point.

    Happy coding and enjoy your game of Gobang!