以下是一个基于Python Pygame的简易五子棋游戏开发方案,支持人机对战功能:

游戏设计思路

  1. 棋盘系统:15×15标准棋盘
  2. 落子逻辑:玩家点击交叉点落子
  3. 胜负判定:五子连珠即获胜
  4. AI算法:实现基础防守策略

核心代码实现

1. 游戏初始化
import pygame
import sys
import numpy as np

# 初始化参数
BOARD_SIZE = 15
GRID_WIDTH = 40
WINDOW_SIZE = BOARD_SIZE * GRID_WIDTH
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (200, 200, 200)
RED = (255, 0, 0)

# 创建游戏窗口
screen = pygame.display.set_mode((WINDOW_SIZE, WINDOW_SIZE))
pygame.display.set_caption("五子棋")

2. 棋盘绘制
def draw_board():
    screen.fill((210, 180, 140))  # 棋盘底色
    # 绘制网格线
    for i in range(BOARD_SIZE):
        # 横线
        pygame.draw.line(screen, BLACK, 
                        (GRID_WIDTH//2, i*GRID_WIDTH + GRID_WIDTH//2), 
                        (WINDOW_SIZE - GRID_WIDTH//2, i*GRID_WIDTH + GRID_WIDTH//2))
        # 竖线
        pygame.draw.line(screen, BLACK,
                        (i*GRID_WIDTH + GRID_WIDTH//2, GRID_WIDTH//2),
                        (i*GRID_WIDTH + GRID_WIDTH//2, WINDOW_SIZE - GRID_WIDTH//2))

3. 落子逻辑
# 棋盘状态矩阵 (0=空, 1=黑, 2=白)
board_state = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)

def place_stone(row, col, player):
    if board_state[row][col] == 0:
        board_state[row][col] = player
        draw_stone(row, col, player)
        return True
    return False

def draw_stone(row, col, player):
    center = (col * GRID_WIDTH + GRID_WIDTH//2, 
              row * GRID_WIDTH + GRID_WIDTH//2)
    color = BLACK if player == 1 else WHITE
    pygame.draw.circle(screen, color, center, GRID_WIDTH//2 - 2)

4. 胜负判定
def check_win(row, col, player):
    # 检查四个方向: 水平、垂直、对角线、反对角线
    directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
    
    for dr, dc in directions:
        count = 1  # 当前位置已有一颗棋子
        
        # 正向检查
        r, c = row + dr, col + dc
        while 0 <= r < BOARD_SIZE and 0 <= c < BOARD_SIZE:
            if board_state[r][c] == player:
                count += 1
                r += dr
                c += dc
            else:
                break
        
        # 反向检查
        r, c = row - dr, col - dc
        while 0 <= r < BOARD_SIZE and 0 <= c < BOARD_SIZE:
            if board_state[r][c] == player:
                count += 1
                r -= dr
                c -= dc
            else:
                break
        
        if count >= 5:
            return True
    return False

5. AI对战逻辑
def ai_move():
    # 基础AI策略:防守优先
    for row in range(BOARD_SIZE):
        for col in range(BOARD_SIZE):
            if board_state[row][col] == 0:
                # 模拟玩家落子
                board_state[row][col] = 1
                if check_win(row, col, 1):  # 阻止玩家获胜
                    board_state[row][col] = 0
                    return row, col
                board_state[row][col] = 0
    
    # 无紧急防守则随机落子
    empty_positions = [(r, c) for r in range(BOARD_SIZE) 
                      for c in range(BOARD_SIZE) if board_state[r][c] == 0]
    return random.choice(empty_positions) if empty_positions else None

游戏主循环

def main():
    current_player = 1  # 1=玩家(黑棋), 2=AI(白棋)
    game_over = False
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            
            if not game_over and event.type == pygame.MOUSEBUTTONDOWN and current_player == 1:
                # 玩家落子
                x, y = pygame.mouse.get_pos()
                col, row = x // GRID_WIDTH, y // GRID_WIDTH
                if place_stone(row, col, current_player):
                    if check_win(row, col, current_player):
                        print("玩家获胜!")
                        game_over = True
                    current_player = 2  # 切换AI
        
        # AI回合
        if not game_over and current_player == 2:
            ai_row, ai_col = ai_move()
            if ai_row is not None:
                place_stone(ai_row, ai_col, current_player)
                if check_win(ai_row, ai_col, current_player):
                    print("AI获胜!")
                    game_over = True
                current_player = 1  # 切换玩家
        
        draw_board()
        # 绘制所有棋子
        for row in range(BOARD_SIZE):
            for col in range(BOARD_SIZE):
                if board_state[row][col] != 0:
                    draw_stone(row, col, board_state[row][col])
        
        pygame.display.flip()

功能扩展建议

  1. AI增强:实现评分系统评估棋盘位置价值
  2. 界面优化:添加开始界面、胜负提示
  3. 音效系统:落子音效和胜利音效
  4. 规则完善:实现禁手规则
  5. 多人模式:支持双人对战

此实现包含五子棋核心功能,代码约150行,可通过python main.py直接运行(需安装pygame和numpy)。AI采用基础防守策略,可进一步优化为Minimax算法或神经网络实现更强智能。

Logo

助力合肥开发者学习交流的技术社区,不定期举办线上线下活动,欢迎大家的加入

更多推荐