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

use pygame to write a Gobang game

  1. User

    use pygame to write a Gobang game

  2. Assistant

    Sure! Gobang, also known as Five in a Row, is a classic strategy board game where two players alternately place 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.

    Below is a complete implementation of a Gobang game using Pygame. This version allows two players to play against each other on the same computer.

    Prerequisites

    1. Python Installed: Ensure you have Python 3.x installed on your system.

    2. Pygame Installed: Install Pygame using pip if you haven't already:

      pip install pygame
      

    Gobang Game Implementation

    import pygame
    import sys
    
    # Initialize Pygame
    pygame.init()
    
    # Constants
    BOARD_SIZE = 15  # 15x15 grid
    CELL_SIZE = 40
    MARGIN = 20
    WINDOW_SIZE = BOARD_SIZE * CELL_SIZE + 2 * MARGIN
    LINE_COLOR = (0, 0, 0)
    BG_COLOR = (205, 133, 63)  # Wood-like background
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    WIN_COLOR = (255, 0, 0)
    
    # Initialize the screen
    screen = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE))
    pygame.display.set_caption("Gobang (Five in a Row)")
    
    # Fonts
    font = pygame.font.SysFont(None, 36)
    
    # Board State: 0 = empty, 1 = black, 2 = white
    board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
    
    current_player = 1  # 1 = Black, 2 = White
    game_over = False
    winner = None
    winning_stones = []  # To highlight the winning sequence
    
    def draw_board():
        screen.fill(BG_COLOR)
        # Draw grid lines
        for i in range(BOARD_SIZE):
            pygame.draw.line(screen, LINE_COLOR,
                             (MARGIN, MARGIN + i * CELL_SIZE),
                             (MARGIN + (BOARD_SIZE - 1) * CELL_SIZE, MARGIN + i * CELL_SIZE))
            pygame.draw.line(screen, LINE_COLOR,
                             (MARGIN + i * CELL_SIZE, MARGIN),
                             (MARGIN + i * CELL_SIZE, MARGIN + (BOARD_SIZE - 1) * CELL_SIZE))
        # Draw stones
        for y in range(BOARD_SIZE):
            for x in range(BOARD_SIZE):
                stone = board[y][x]
                if stone != 0:
                    center = (MARGIN + x * CELL_SIZE, MARGIN + y * CELL_SIZE)
                    if stone == 1:
                        color = BLACK
                    else:
                        color = WHITE
                    pygame.draw.circle(screen, color, center, CELL_SIZE // 2 - 2)
                    pygame.draw.circle(screen, LINE_COLOR, center, CELL_SIZE // 2 - 2, 1)  # Outline
        # Highlight winning stones
        for pos in winning_stones:
            x, y = pos
            rect = pygame.Rect(MARGIN + x * CELL_SIZE - CELL_SIZE // 2,
                               MARGIN + y * CELL_SIZE - CELL_SIZE // 2,
                               CELL_SIZE, CELL_SIZE)
            pygame.draw.rect(screen, WIN_COLOR, rect, 3)
    
    def get_grid_pos(mouse_x, mouse_y):
        """Convert mouse coordinates to grid position."""
        for x in range(BOARD_SIZE):
            for y in range(BOARD_SIZE):
                grid_x = MARGIN + x * CELL_SIZE
                grid_y = MARGIN + y * CELL_SIZE
                if (grid_x - CELL_SIZE//2 < mouse_x < grid_x + CELL_SIZE//2 and
                    grid_y - CELL_SIZE//2 < mouse_y < grid_y + CELL_SIZE//2):
                    return x, y
        return None
    
    def check_win(x, y):
        """Check if the current move at (x, y) wins the game."""
        def count_stones(dx, dy):
            count = 1
            stones = [(x, y)]
            # Check in the (dx, dy) direction
            i = 1
            while True:
                nx = x + dx * i
                ny = y + dy * i
                if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE and board[ny][nx] == current_player:
                    count += 1
                    stones.append((nx, ny))
                    i += 1
                else:
                    break
            # Check in the opposite (-dx, -dy) direction
            i = 1
            while True:
                nx = x - dx * i
                ny = y - dy * i
                if 0 <= nx < BOARD_SIZE and 0 <= ny < BOARD_SIZE and board[ny][nx] == current_player:
                    count += 1
                    stones.append((nx, ny))
                    i += 1
                else:
                    break
            return count, stones
    
        directions = [(1, 0), (0, 1), (1, 1), (1, -1)]  # horizontal, vertical, two diagonals
        for dx, dy in directions:
            cnt, stones = count_stones(dx, dy)
            if cnt >= 5:
                return True, stones
        return False, []
    
    def draw_status():
        if game_over:
            if winner == 1:
                text = font.render("Black Wins!", True, BLACK)
            elif winner == 2:
                text = font.render("White Wins!", True, WHITE)
            else:
                text = font.render("It's a Draw!", True, (0, 0, 0))
        else:
            player = "Black" if current_player == 1 else "White"
            text = font.render(f"{player}'s Turn", True, BLACK if current_player == 1 else WHITE)
        text_rect = text.get_rect(center=(WINDOW_SIZE//2, MARGIN//2))
        screen.blit(text, text_rect)
    
    def reset_game():
        global board, current_player, game_over, winner, winning_stones
        board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
        current_player = 1
        game_over = False
        winner = None
        winning_stones = []
    
    def main():
        global current_player, game_over, winner, winning_stones
    
        clock = pygame.time.Clock()
    
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
    
                if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
                    mouse_x, mouse_y = event.pos
                    pos = get_grid_pos(mouse_x, mouse_y)
                    if pos:
                        x, y = pos
                        if board[y][x] == 0:
                            board[y][x] = current_player
                            has_won, stones = check_win(x, y)
                            if has_won:
                                game_over = True
                                winner = current_player
                                winning_stones = stones
                            elif all(cell != 0 for row in board for cell in row):
                                game_over = True
                                winner = None  # Draw
                            else:
                                current_player = 2 if current_player == 1 else 1
    
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_r:
                        reset_game()
    
            draw_board()
            draw_status()
            pygame.display.flip()
            clock.tick(60)
    
    if __name__ == "__main__":
        main()
    

    How the Code Works

    1. Initialization:

      • Pygame Initialization: Initializes all Pygame modules.
      • Constants: Define the board size, cell size, colors, and window size.
      • Screen Setup: Sets up the Pygame window with the specified size and title.
      • Board State: Represents the board as a 2D list where 0 indicates an empty cell, 1 for black stones, and 2 for white stones.
      • Game State Variables: Tracks the current player, game over status, winner, and the winning sequence of stones.
    2. Drawing the Board (draw_board):

      • Fills the background with a wood-like color.
      • Draws the grid lines for the board.
      • Iterates through the board state to draw black and white stones.
      • Highlights the winning sequence with a red rectangle if the game is over.
    3. Handling Mouse Clicks (get_grid_pos):

      • Converts the mouse click position to the corresponding grid coordinates.
      • Ensures that the click is within the bounds of a cell.
    4. Win Detection (check_win):

      • After each move, checks in all four directions (horizontal, vertical, and two diagonals) to see if there are five consecutive stones of the current player.
      • Returns whether a win has occurred and the positions of the winning stones.
    5. Status Display (draw_status):

      • Shows whose turn it is or announces the winner when the game is over.
    6. Reset Game (reset_game):

      • Resets the board and all game state variables to start a new game.
    7. Main Game Loop (main):

      • Handles events such as quitting the game, mouse clicks for placing stones, and key presses for resetting the game (press R to reset).
      • Continuously updates and redraws the game state at 60 frames per second.

    How to Play

    1. Starting the Game: Run the script, and a window with a 15x15 grid will appear.
    2. Placing Stones:
      • Black Player: Starts first. Click on an empty cell to place a black stone.
      • White Player: Takes the next turn. Click on another empty cell to place a white stone.
    3. Winning the Game: The first player to align five of their stones horizontally, vertically, or diagonally wins. The winning sequence will be highlighted in red.
    4. Resetting the Game: Press the R key to reset the game at any time.

    Enhancements and Features You Can Add

    1. AI Opponent: Implement an AI to allow single-player mode.
    2. Better Graphics: Improve the visual aesthetics with better graphics and animations.
    3. Undo Move: Allow players to undo their last move.
    4. Score Tracking: Keep track of wins, losses, and draws over multiple games.
    5. Adjustable Board Size: Allow players to choose different board sizes.
    6. Responsive Design: Make the game window resizable and adjust the UI accordingly.

    Running the Game

    1. Save the Script: Save the above Python code to a file, for example, gobang.py.

    2. Run the Script: Navigate to the directory containing gobang.py and run:

      python gobang.py
      
    3. Enjoy Playing: The game window should appear, and you can start playing Gobang!

    Feel free to modify and enhance the game as you see fit. Happy coding and enjoy your game of Gobang!