当前位置: 首页>编程语言>正文

五子棋盘python源代码 python五子棋原理

python 五子棋AI实现(2):棋型评估函数实现

  • 五子棋基本棋型介绍
  • 评估方法介绍
  • 简单AI介绍
  • 代码实现
  • 完整代码
  • main.py
  • GameMap.py
  • ChessAI.py

五子棋基本棋型介绍

参考资料:http://game.onegreen.net/wzq/HTML/142336.html 最常见的基本棋型大体有以下几种:连五,活四,冲四,活三,眠三,活二,眠二。

① 连五:顾名思义,五颗同色棋子连在一起,不需要多讲。

图2-1

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_lua,第1张

② 活四:有两个连五点(即有两个点可以形成五),图中白点即为连五点。

稍微思考一下就能发现活四出现的时候,如果对方单纯过来防守的话,是已经无法阻止自己连五了。

图2-2

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_五子棋盘python源代码_02,第2张

③ 冲四:有一个连五点,如下面三图,均为冲四棋型。图中白点为连五点。

相对比活四来说,冲四的威胁性就小了很多,因为这个时候,对方只要跟着防守在那个唯一的连五点上,冲四就没法形成连五。

图2-3

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_lua_03,第3张

图2-4

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_lua_04,第4张

图2-5

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_lua_05,第5张

④ 活三:可以形成活四的三,如下图,代表两种最基本的活三棋型。图中白点为活四点。

活三棋型是我们进攻中最常见的一种,因为活三之后,如果对方不以理会,将可以下一手将活三变成活四,而我们知道活四是已经无法单纯防守住了。所以,当我们面对活三的时候,需要非常谨慎对待。在自己没有更好的进攻手段的情况下,需要对其进行防守,以防止其形成可怕的活四棋型。

图2-6

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_数组_06,第6张

图2-7

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_五子棋盘python源代码_07,第7张

其中图2-7中间跳着一格的活三,也可以叫做跳活三。⑤ 眠三:只能够形成冲四的三,如下各图,分别代表最基础的六种眠三形状。图中白点代表冲四点。眠三的棋型与活三的棋型相比,危险系数下降不少,因为眠三棋型即使不去防守,下一手它也只能形成冲四,而对于单纯的冲四棋型,我们知道,是可以防守住的。

图2-8

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_五子棋盘python源代码_08,第8张

图2-9

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_代码实现_09,第9张

图2-10

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_代码实现_10,第10张

图2-11

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_数组_11,第11张

图2-12

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_lua_12,第12张

图2-13

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_lua_13,第13张

如上所示,眠三的形状是很丰富的。对于初学者,在下棋过程中,很容易忽略不常见的眠三形状,例如图2-13所示的眠三。

有新手学了活三眠三后,会提出疑问,说活三也可以形成冲四啊,那岂不是也可以叫眠三? 会提出这个问题,说明对眠三定义看得不够仔细:眠三的的定义是,只能够形成冲四的三。而活三可以形成眠三,但也能够形成活四。

此外,在五子棋中,活四棋型比冲四棋型具有更大的优势,所以,我们在既能够形成活四又能够形成冲四时,会选择形成活四。

温馨提示:学会判断一个三到底是活三还是眠三是非常重要的。所以,需要好好体会。 后边禁手判断的时候也会有所应用。

⑥ 活二:能够形成活三的二,如下图,是三种基本的活二棋型。图中白点为活三点。

活二棋型看起来似乎很无害,因为他下一手棋才能形成活三,等形成活三,我们再防守也不迟。但其实活二棋型是非常重要的,尤其是在开局阶段,我们形成较多的活二棋型的话,当我们将活二变成活三时,才能够令自己的活三绵绵不绝微风里,让对手防不胜防。

图2-14

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_代码实现_14,第14张

图2-15

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_数组_15,第15张

图2-16

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_数组_16,第16张

⑦眠二:能够形成眠三的二。图中四个为最基本的眠二棋型,细心且喜欢思考的同学会根据眠三介绍中的图2-13找到与下列四个基本眠二棋型都不一样的眠二。图中白点为眠三点。

图2-17

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_数组_17,第17张

图2-18

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_lua_18,第18张

图2-19

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_数组_19,第19张

图2-20

五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_代码实现_20,第20张

评估方法介绍

由上面的介绍可知,有7种有效的棋型(连五,活四,冲四,活三,眠三,活二,眠二),我们可以创建黑棋和白棋两个数组,记录棋盘上黑棋和白棋分别形成的所有棋型的个数,然后按照一定的规则进行评分。

如何记录棋盘上的棋形个数,一个很直观的方法是,棋盘上有15条水平线,15条竖直线,不考虑长度小于5的斜线,有21条从左上到右下的斜线,21条从左下到右上的斜线。然后对每一条线分别对黑棋和白棋查找是否有符合的棋型。这种方法比较直观,但是实现起来不方便。有兴趣的可以尝试下。

这里用的方法是,对整个棋盘进行遍历,对于每一个白棋或黑棋,以它为中心,记录符合的棋型个数。 具体实现方式如下:

  1. 遍历棋盘上的每个点,如果是黑棋或白旗,则对这个点所在四个方向形成的四条线分别进行评估。四个方向即水平,竖直,两个斜线( \ , / ),四个方向依次按照从左到右, 从上到下,从左上到右下,从左下到右上 来检测。
  2. 对于具体的一条线,如下图,已选取点为中心,取该方向上前面四个点,后面四个点,组成一个长度为9的数组。
  3. 五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_五子棋盘python源代码_21,第21张

  4. 然后找下和中心点相连的同色棋子有几个,比如下图,相连的白色棋子有3个,根据相连棋子的个数再分别进行判断,最后得出这行属于上面说的哪一种棋型。具体判断可以看代码中的 analysisLine 函数. 这里有个注意点,在评估白旗1的时候,白棋3和5已经被判断过,所以要标记下,下次遍历到这个方向的白棋3和5,需要跳过,避免重复统计棋型。
  5. 五子棋盘python源代码 python五子棋原理,五子棋盘python源代码 python五子棋原理_数组_22,第22张

  6. 根据棋盘上黑棋和白棋的棋型统计信息,按照一定规则进行评分。 假设形成该棋局的最后一步是黑棋下的,则最后的评分是(黑棋得分 - 白棋得分),在相同棋型相同个数的情况下,白棋会占优,因为下一步是白棋下。比如黑棋有个冲四,白棋有个冲四,显然白棋占优,因为下一步白棋就能成连五。 按照下面的规则依次匹配,下面设的评分值是可以优化调整的: 前面9条为必杀情况,会直接返回评分,
  • 黑棋连5,评分为10000
  • 白棋连5,评分为 -10000
  • 黑棋两个冲四可以当成一个活四
  • 白棋有活四,评分为 -9050
  • 白棋有冲四,评分为 -9040
  • 黑棋有活四,评分为 9030
  • 黑棋有冲四和活三,评分为 9020
  • 黑棋没有冲四,且白棋有活三,评分为 9010
  • 黑棋有2个活三,且白棋没有活三或眠三,评分为 9000
  • 下面针对黑棋或白棋的活三,眠三,活二,眠二的个数依次增加分数,评分为(黑棋得分 - 白棋得分)

简单AI介绍

有了评估函数,轮到AI下棋时,就要针对当前的棋局,找到一个最有利的位置来下。AI会尝试在每个空点下棋,形成一个新的棋局,然后用评估函数来获取这个棋局时的评分。从中选取评分最高的位置来就行了。 AI 获取最有利位置的逻辑:

  • 遍历棋盘上的每一个空点: 在这个空点下棋,获取新的棋局的评分 如果是更高的评分,则保存该位置 将这个位置恢复为空点
  • 获得最高评分的位置

上面这段逻辑我们在后续的文章中会不断优化,使得AI越来越厉害。

代码实现

AI的实现都在ChessAI类中,record数组记录所有位置的四个方向是否被检测过。count二维数组记录黑棋和白棋的棋型个数统计。pos_score 给棋盘上每个位置设一个初始分数,越靠近棋盘中心,分数越高,用来在最开始没有任何棋型时的,AI优先选取靠中心的位置。reset函数每次调用评估函数前都需要清一下之前的统计数据。

class ChessAI():
	def __init__(self, chess_len):
		self.len = chess_len
		# [horizon, vertical, left diagonal, right diagonal]
		self.record = [[[0,0,0,0] for x in range(chess_len)] for y in range(chess_len)]
		self.count = [[0 for x in range(CHESS_TYPE_NUM)] for i in range(2)]
		self.pos_score = [[(7 - max(abs(x - 7), abs(y - 7))) for x in range(chess_len)] for y in range(chess_len)]
		
	def reset(self):
		for y in range(self.len):
			for x in range(self.len):
				for i in range(4):
					self.record[y][x][i] = 0

		for i in range(len(self.count)):
			for j in range(len(self.count[0])):
				self.count[i][j] = 0
		
		self.save_count = 0

findBestChess 函数就是AI的入口函数。search 函数是上面AI逻辑的代码实现,先通过 genmove 函数获取棋盘上所有的空点,然后依次尝试,获得评分最高的位置并返回。

# get all positions that is empty
	def genmove(self, board, turn):
		moves = []
		for y in range(self.len):
			for x in range(self.len):
				if board[y][x] == 0:
					score = self.pos_score[y][x]
					moves.append((score, x, y))

		moves.sort(reverse=True)
		return moves

	def search(self, board, turn):
		moves = self.genmove(board, turn)
		bestmove = None
		max_score = -0x7fffffff
		for score, x, y in moves:
			board[y][x] = turn.value
			score = self.evaluate(board, turn)
			board[y][x] = 0
			
			if score > max_score:
				max_score = score
				bestmove = (max_score, x, y)
		return bestmove
		
	def findBestChess(self, board, turn):
		time1 = time.time()
		score, x, y = self.search(board, turn)
		time2 = time.time()
		print('time[%f] (%d, %d), score[%d] save[%d]' % ((time2-time1), x, y, score, self.save_count))
		return (x, y)

evaluate函数, 就是上面评估方法的代码实现,参数turn表示最近一手棋是谁下的,根据turn决定的mine(表示自己棋的值)和oppoent(表示对手棋的值,下一步棋由对手下),在对棋型评分时会用到。checkWin 是游戏用来判断是否有一方获胜了。 其中调用的getScore函数就是对黑棋和白棋进行评分。evaluatePoint函数就是对于一个位置的四个方向分别进行检查。

def evaluate(self, board, turn, checkWin=False):
		self.reset()
		
		if turn == MAP_ENTRY_TYPE.MAP_PLAYER_ONE:
			mine = 1
			opponent = 2
		else:
			mine = 2
			opponent = 1
		
		for y in range(self.len):
			for x in range(self.len):
				if board[y][x] == mine:
					self.evaluatePoint(board, x, y, mine, opponent)
				elif board[y][x] == opponent:
					self.evaluatePoint(board, x, y, opponent, mine)
		
		mine_count = self.count[mine-1]
		opponent_count = self.count[opponent-1]
		if checkWin:
			return mine_count[FIVE] > 0
		else:	
			mscore, oscore = self.getScore(mine_count, opponent_count)
			return (mscore - oscore)

	def evaluatePoint(self, board, x, y, mine, opponent):
		dir_offset = [(1, 0), (0, 1), (1, 1), (1, -1)] # direction from left to right
		for i in range(4):
			if self.record[y][x][i] == 0:
				self.analysisLine(board, x, y, i, dir_offset[i], mine, opponent, self.count[mine-1])
			else:
				self.save_count += 1

analysisLine函数是判断一条线上自己棋能形成棋型的代码, mine表示自己棋的值,opponent表示对手棋的值。 要根据中心点相邻己方棋子能连成的个数来分别判断,己方棋值设为M,对方棋值设为P,空点值设为X。具体可以看代码中的注释。

  • 连成5个点,可以直接返回
  • 连成4个点,要考虑是否被对手棋档着,比如 PMMMMX
  • 连成3个点,要考虑隔一个空点的情况,比如 MXMMMX。
  • 连成2个点,要考虑隔一个空点的如情况,比如 MXMMX,MMXMM。
  • 只有1个点,要考虑隔一个或二个空点的情况,比如 XMXMX,XMXXMX。

getLine函数,根据棋子的位置和方向,获取上面说的长度为9的线。有个取巧的地方,如果线上的位置超出了棋盘范围,就将这个位置的值设为对手的值,因为超出范围和被对手棋挡着,对棋型判断的结果是一样的。setRecord函数 标记已经检测过,需要跳过的棋子。

# line is fixed len 9: XXXXMXXXX
	def getLine(self, board, x, y, dir_offset, mine, opponent):
		line = [0 for i in range(9)]
		
		tmp_x = x + (-5 * dir_offset[0])
		tmp_y = y + (-5 * dir_offset[1])
		for i in range(9):
			tmp_x += dir_offset[0]
			tmp_y += dir_offset[1]
			if (tmp_x < 0 or tmp_x >= self.len or 
				tmp_y < 0 or tmp_y >= self.len):
				line[i] = opponent # set out of range as opponent chess
			else:
				line[i] = board[tmp_y][tmp_x]
						
		return line
		
	def analysisLine(self, board, x, y, dir_index, dir_offset, mine, opponent, count):
		# record line range[left, right] as analysized
		def setRecord(self, x, y, left, right, dir_index, dir_offset):
			tmp_x = x + (-5 + left) * dir_offset[0]
			tmp_y = y + (-5 + left) * dir_offset[1]
			for i in range(left, right+1):
				tmp_x += dir_offset[0]
				tmp_y += dir_offset[1]
				self.record[tmp_y][tmp_x][dir_index] = 1
	
		empty = MAP_ENTRY_TYPE.MAP_EMPTY.value
		left_idx, right_idx = 4, 4
		
		line = self.getLine(board, x, y, dir_offset, mine, opponent)

		while right_idx < 8:
			if line[right_idx+1] != mine:
				break
			right_idx += 1
		while left_idx > 0:
			if line[left_idx-1] != mine:
				break
			left_idx -= 1
		
		left_range, right_range = left_idx, right_idx
		while right_range < 8:
			if line[right_range+1] == opponent:
				break
			right_range += 1
		while left_range > 0:
			if line[left_range-1] == opponent:
				break
			left_range -= 1
		
		chess_range = right_range - left_range + 1
		if chess_range < 5:
			setRecord(self, x, y, left_range, right_range, dir_index, dir)
			return CHESS_TYPE.NONE
		
		setRecord(self, x, y, left_idx, right_idx, dir_index, dir)
		
		m_range = right_idx - left_idx + 1
		
		# M:mine chess, P:opponent chess or out of range, X: empty
		if m_range == 5:
			count[FIVE] += 1
		
		# Live Four : XMMMMX 
		# Chong Four : XMMMMP, PMMMMX
		if m_range == 4:
			left_empty = right_empty = False
			if line[left_idx-1] == empty:
				left_empty = True			
			if line[right_idx+1] == empty:
				right_empty = True
			if left_empty and right_empty:
				count[FOUR] += 1
			elif left_empty or right_empty:
				count[SFOUR] += 1
		
		# Chong Four : MXMMM, MMMXM, the two types can both exist
		# Live Three : XMMMXX, XXMMMX
		# Sleep Three : PMMMX, XMMMP, PXMMMXP
		if m_range == 3:
			left_empty = right_empty = False
			left_four = right_four = False
			if line[left_idx-1] == empty:
				if line[left_idx-2] == mine: # MXMMM
					setRecord(self, x, y, left_idx-2, left_idx-1, dir_index, dir)
					count[SFOUR] += 1
					left_four = True
				left_empty = True
				
			if line[right_idx+1] == empty:
				if line[right_idx+2] == mine: # MMMXM
					setRecord(self, x, y, right_idx+1, right_idx+2, dir_index, dir)
					count[SFOUR] += 1
					right_four = True 
				right_empty = True
			
			if left_four or right_four:
				pass
			elif left_empty and right_empty:
				if chess_range > 5: # XMMMXX, XXMMMX
					count[THREE] += 1
				else: # PXMMMXP
					count[STHREE] += 1
			elif left_empty or right_empty: # PMMMX, XMMMP
				count[STHREE] += 1
		
		# Chong Four: MMXMM, only check right direction
		# Live Three: XMXMMX, XMMXMX the two types can both exist
		# Sleep Three: PMXMMX, XMXMMP, PMMXMX, XMMXMP
		# Live Two: XMMX
		# Sleep Two: PMMX, XMMP
		if m_range == 2:
			left_empty = right_empty = False
			left_three = right_three = False
			if line[left_idx-1] == empty:
				if line[left_idx-2] == mine:
					setRecord(self, x, y, left_idx-2, left_idx-1, dir_index, dir)
					if line[left_idx-3] == empty:
						if line[right_idx+1] == empty: # XMXMMX
							count[THREE] += 1
						else: # XMXMMP
							count[STHREE] += 1
						left_three = True
					elif line[left_idx-3] == opponent: # PMXMMX
						if line[right_idx+1] == empty:
							count[STHREE] += 1
							left_three = True
						
				left_empty = True
				
			if line[right_idx+1] == empty:
				if line[right_idx+2] == mine:
					if line[right_idx+3] == mine:  # MMXMM
						setRecord(self, x, y, right_idx+1, right_idx+2, dir_index, dir)
						count[SFOUR] += 1
						right_three = True
					elif line[right_idx+3] == empty:
						#setRecord(self, x, y, right_idx+1, right_idx+2, dir_index, dir)
						if left_empty:  # XMMXMX
							count[THREE] += 1
						else:  # PMMXMX
							count[STHREE] += 1
						right_three = True
					elif left_empty: # XMMXMP
						count[STHREE] += 1
						right_three = True
						
				right_empty = True
			
			if left_three or right_three:
				pass
			elif left_empty and right_empty: # XMMX
				count[TWO] += 1
			elif left_empty or right_empty: # PMMX, XMMP
				count[STWO] += 1
		
		# Live Two: XMXMX, XMXXMX only check right direction
		# Sleep Two: PMXMX, XMXMP
		if m_range == 1:
			left_empty = right_empty = False
			if line[left_idx-1] == empty:
				if line[left_idx-2] == mine:
					if line[left_idx-3] == empty:
						if line[right_idx+1] == opponent: # XMXMP
							count[STWO] += 1
				left_empty = True

			if line[right_idx+1] == empty:
				if line[right_idx+2] == mine:
					if line[right_idx+3] == empty:
						if left_empty: # XMXMX
							#setRecord(self, x, y, left_idx, right_idx+2, dir_index, dir)
							count[TWO] += 1
						else: # PMXMX
							count[STWO] += 1
				elif line[right_idx+2] == empty:
					if line[right_idx+3] == mine and line[right_idx+4] == empty: # XMXXMX
						count[TWO] += 1
						
		return CHESS_TYPE.NONE

完整代码

一共有三个文件,新增加了一个ChessAI.py。

main.py

增加了对于ChessAI类的 findBestChess 函数的调用,获取AI选择的下棋位置。

import pygame
from pygame.locals import *
from GameMap import *
from ChessAI import *


class Button():
	def __init__(self, screen, text, x, y, color, enable):
		self.screen = screen
		self.width = BUTTON_WIDTH
		self.height = BUTTON_HEIGHT
		self.button_color = color
		self.text_color = (255, 255, 255)
		self.enable = enable
		self.font = pygame.font.SysFont(None, BUTTON_HEIGHT*2//3)
		
		self.rect = pygame.Rect(0, 0, self.width, self.height)
		self.rect.topleft = (x, y)
		self.text = text
		self.init_msg()
		
	def init_msg(self):
		if self.enable:
			self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])
		else:
			self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])
		self.msg_image_rect = self.msg_image.get_rect()
		self.msg_image_rect.center = self.rect.center
		
	def draw(self):
		if self.enable:
			self.screen.fill(self.button_color[0], self.rect)
		else:
			self.screen.fill(self.button_color[1], self.rect)
		self.screen.blit(self.msg_image, self.msg_image_rect)
		

class StartButton(Button):
	def __init__(self, screen, text, x, y):
		super().__init__(screen, text, x, y, [(26, 173, 25),(158, 217, 157)], True)
	
	def click(self, game):
		if self.enable: 
			game.start()
			game.winner = None
			self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])
			self.enable = False
			return True
		return False
	
	def unclick(self):
		if not self.enable:
			self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])
			self.enable = True
		
class GiveupButton(Button):
	def __init__(self, screen, text, x, y):
		super().__init__(screen, text, x, y, [(230, 67, 64),(236, 139, 137)], False)
		
	def click(self, game):
		if self.enable:
			game.is_play = False
			if game.winner is None:
				game.winner = game.map.reverseTurn(game.player)
			self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])
			self.enable = False
			return True
		return False

	def unclick(self):
		if not self.enable:
			self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])
			self.enable = True

class Game():
	def __init__(self, caption):
		pygame.init()
		self.screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
		pygame.display.set_caption(caption)
		self.clock = pygame.time.Clock()
		self.buttons = []
		self.buttons.append(StartButton(self.screen, 'Start', MAP_WIDTH + 30, 15))
		self.buttons.append(GiveupButton(self.screen, 'Giveup', MAP_WIDTH + 30, BUTTON_HEIGHT + 45))
		self.is_play = False

		self.map = Map(CHESS_LEN, CHESS_LEN)
		self.player = MAP_ENTRY_TYPE.MAP_PLAYER_ONE
		self.action = None
		self.AI = ChessAI(CHESS_LEN)
		self.useAI = False
		self.winner = None
	
	def start(self):
		self.is_play = True
		self.player = MAP_ENTRY_TYPE.MAP_PLAYER_ONE
		self.map.reset()

	def play(self):
		self.clock.tick(60)
		
		light_yellow = (247, 238, 214)
		pygame.draw.rect(self.screen, light_yellow, pygame.Rect(0, 0, MAP_WIDTH, SCREEN_HEIGHT))
		pygame.draw.rect(self.screen, (255, 255, 255), pygame.Rect(MAP_WIDTH, 0, INFO_WIDTH, SCREEN_HEIGHT))
		
		for button in self.buttons:
			button.draw()
		
		if self.is_play and not self.isOver():
			if self.useAI:
				x, y = self.AI.findBestChess(self.map.map, self.player)
				self.checkClick(x, y, True)
				self.useAI = False

			if self.action is not None:
				self.checkClick(self.action[0], self.action[1])
				self.action = None
			
			if not self.isOver():
				self.changeMouseShow()
			
		if self.isOver():
			self.showWinner()

		self.map.drawBackground(self.screen)
		self.map.drawChess(self.screen)

	
	def changeMouseShow(self):
		map_x, map_y = pygame.mouse.get_pos()
		x, y = self.map.MapPosToIndex(map_x, map_y)
		if self.map.isInMap(map_x, map_y) and self.map.isEmpty(x, y):
			pygame.mouse.set_visible(False)
			light_red = (213, 90, 107)
			pos, radius = (map_x, map_y), CHESS_RADIUS
			pygame.draw.circle(self.screen, light_red, pos, radius)
		else:
			pygame.mouse.set_visible(True)
	
	def checkClick(self,x, y, isAI=False):
		self.map.click(x, y, self.player)
		if self.AI.isWin(self.map.map, self.player):
			self.winner = self.player
			self.click_button(self.buttons[1])
		else:	
			self.player = self.map.reverseTurn(self.player)
			if not isAI:	
				self.useAI = True
	
	def mouseClick(self, map_x, map_y):
		if self.is_play and self.map.isInMap(map_x, map_y) and not self.isOver():
			x, y = self.map.MapPosToIndex(map_x, map_y)
			if self.map.isEmpty(x, y):
				self.action = (x, y)
	
	def isOver(self):
		return self.winner is not None

	def showWinner(self):
		def showFont(screen, text, location_x, locaiton_y, height):
			font = pygame.font.SysFont(None, height)
			font_image = font.render(text, True, (0, 0, 255), (255, 255, 255))
			font_image_rect = font_image.get_rect()
			font_image_rect.x = location_x
			font_image_rect.y = locaiton_y
			screen.blit(font_image, font_image_rect)
		if self.winner == MAP_ENTRY_TYPE.MAP_PLAYER_ONE:
			str = 'Winner is White'
		else:
			str = 'Winner is Black'
		showFont(self.screen, str, MAP_WIDTH + 25, SCREEN_HEIGHT - 60, 30)
		pygame.mouse.set_visible(True)
	
	def click_button(self, button):
		if button.click(self):
			for tmp in self.buttons:
				if tmp != button:
					tmp.unclick()
					
	def check_buttons(self, mouse_x, mouse_y):
		for button in self.buttons:
			if button.rect.collidepoint(mouse_x, mouse_y):
				self.click_button(button)
				break
			
game = Game("FIVE CHESS " + GAME_VERSION)
while True:
	game.play()
	pygame.display.update()
	
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			pygame.quit()
			exit()
		elif event.type == pygame.MOUSEBUTTONDOWN:
			mouse_x, mouse_y = pygame.mouse.get_pos()
			game.mouseClick(mouse_x, mouse_y)
			game.check_buttons(mouse_x, mouse_y)

GameMap.py

这个文件没有修改,可以直接使用上一篇中的代码。

ChessAI.py

AI实现的代码,这个AI目前很简单,只会思考一步,后续会增加思考的步数,比如2步或4步。

from GameMap import *
from enum import IntEnum
import copy
import time

class CHESS_TYPE(IntEnum):
	NONE = 0,
	SLEEP_TWO = 1,
	LIVE_TWO = 2,
	SLEEP_THREE = 3
	LIVE_THREE = 4,
	CHONG_FOUR = 5,
	LIVE_FOUR = 6,
	LIVE_FIVE = 7,
	
CHESS_TYPE_NUM = 8

FIVE = CHESS_TYPE.LIVE_FIVE.value
FOUR, THREE, TWO = CHESS_TYPE.LIVE_FOUR.value, CHESS_TYPE.LIVE_THREE.value, CHESS_TYPE.LIVE_TWO.value
SFOUR, STHREE, STWO = CHESS_TYPE.CHONG_FOUR.value, CHESS_TYPE.SLEEP_THREE.value, CHESS_TYPE.SLEEP_TWO.value
			
class ChessAI():
	def __init__(self, chess_len):
		self.len = chess_len
		# [horizon, vertical, left diagonal, right diagonal]
		self.record = [[[0,0,0,0] for x in range(chess_len)] for y in range(chess_len)]
		self.count = [[0 for x in range(CHESS_TYPE_NUM)] for i in range(2)]
		self.pos_score = [[(7 - max(abs(x - 7), abs(y - 7))) for x in range(chess_len)] for y in range(chess_len)]
		
	def reset(self):
		for y in range(self.len):
			for x in range(self.len):
				for i in range(4):
					self.record[y][x][i] = 0

		for i in range(len(self.count)):
			for j in range(len(self.count[0])):
				self.count[i][j] = 0
		
		self.save_count = 0
	
	def isWin(self, board, turn):
		return self.evaluate(board, turn, True)
	
	# get all positions that is empty
	def genmove(self, board, turn):
		moves = []
		for y in range(self.len):
			for x in range(self.len):
				if board[y][x] == 0:
					score = self.pos_score[y][x]
					moves.append((score, x, y))

		moves.sort(reverse=True)
		return moves

	def search(self, board, turn):
		moves = self.genmove(board, turn)
		bestmove = None
		max_score = -0x7fffffff
		for score, x, y in moves:
			board[y][x] = turn.value
			score = self.evaluate(board, turn)
			board[y][x] = 0
			
			if score > max_score:
				max_score = score
				bestmove = (max_score, x, y)
		return bestmove
		
	def findBestChess(self, board, turn):
		time1 = time.time()
		score, x, y = self.search(board, turn)
		time2 = time.time()
		print('time[%f] (%d, %d), score[%d] save[%d]' % ((time2-time1), x, y, score, self.save_count))
		return (x, y)
	
	# calculate score, FIXME: May Be Improved
	def getScore(self, mine_count, opponent_count):
		mscore, oscore = 0, 0
		if mine_count[FIVE] > 0:
			return (10000, 0)
		if opponent_count[FIVE] > 0:
			return (0, 10000)
				
		if mine_count[SFOUR] >= 2:
			mine_count[FOUR] += 1
			
		if opponent_count[FOUR] > 0:
			return (0, 9050)
		if opponent_count[SFOUR] > 0:
			return (0, 9040)
		
		if mine_count[FOUR] > 0:
			return (9030, 0)
		if mine_count[SFOUR] > 0 and mine_count[THREE] > 0:
			return (9020, 0)
			
		if opponent_count[THREE] > 0 and mine_count[SFOUR] == 0:
			return (0, 9010)
			
		if (mine_count[THREE] > 1 and opponent_count[THREE] == 0 and opponent_count[STHREE] == 0):
			return (9000, 0)
		
		if mine_count[SFOUR] > 0:
			mscore += 2000

		if mine_count[THREE] > 1:
			mscore += 500
		elif mine_count[THREE] > 0:
			mscore += 100
			
		if opponent_count[THREE] > 1:
			oscore += 2000
		elif opponent_count[THREE] > 0:
			oscore += 400

		if mine_count[STHREE] > 0:
			mscore += mine_count[STHREE] * 10
		if opponent_count[STHREE] > 0:
			oscore += opponent_count[STHREE] * 10
			
		if mine_count[TWO] > 0:
			mscore += mine_count[TWO] * 4
		if opponent_count[TWO] > 0:
			oscore += opponent_count[TWO] * 4
				
		if mine_count[STWO] > 0:
			mscore += mine_count[STWO] * 4
		if opponent_count[STWO] > 0:
			oscore += opponent_count[STWO] * 4
		
		return (mscore, oscore)

	def evaluate(self, board, turn, checkWin=False):
		self.reset()
		
		if turn == MAP_ENTRY_TYPE.MAP_PLAYER_ONE:
			mine = 1
			opponent = 2
		else:
			mine = 2
			opponent = 1
		
		for y in range(self.len):
			for x in range(self.len):
				if board[y][x] == mine:
					self.evaluatePoint(board, x, y, mine, opponent)
				elif board[y][x] == opponent:
					self.evaluatePoint(board, x, y, opponent, mine)
		
		mine_count = self.count[mine-1]
		opponent_count = self.count[opponent-1]
		if checkWin:
			return mine_count[FIVE] > 0
		else:	
			mscore, oscore = self.getScore(mine_count, opponent_count)
			return (mscore - oscore)
	
	def evaluatePoint(self, board, x, y, mine, opponent):
		dir_offset = [(1, 0), (0, 1), (1, 1), (1, -1)] # direction from left to right
		for i in range(4):
			if self.record[y][x][i] == 0:
				self.analysisLine(board, x, y, i, dir_offset[i], mine, opponent, self.count[mine-1])
			else:
				self.save_count += 1
	
	# line is fixed len 9: XXXXMXXXX
	def getLine(self, board, x, y, dir_offset, mine, opponent):
		line = [0 for i in range(9)]
		
		tmp_x = x + (-5 * dir_offset[0])
		tmp_y = y + (-5 * dir_offset[1])
		for i in range(9):
			tmp_x += dir_offset[0]
			tmp_y += dir_offset[1]
			if (tmp_x < 0 or tmp_x >= self.len or 
				tmp_y < 0 or tmp_y >= self.len):
				line[i] = opponent # set out of range as opponent chess
			else:
				line[i] = board[tmp_y][tmp_x]
						
		return line
		
	def analysisLine(self, board, x, y, dir_index, dir, mine, opponent, count):
		def setRecord(self, x, y, left, right, dir_index, dir_offset):
			tmp_x = x + (-5 + left) * dir_offset[0]
			tmp_y = y + (-5 + left) * dir_offset[1]
			for i in range(left, right):
				tmp_x += dir_offset[0]
				tmp_y += dir_offset[1]
				self.record[tmp_y][tmp_x][dir_index] = 1
	
		empty = MAP_ENTRY_TYPE.MAP_EMPTY.value
		left_idx, right_idx = 4, 4
		
		line = self.getLine(board, x, y, dir, mine, opponent)

		while right_idx < 8:
			if line[right_idx+1] != mine:
				break
			right_idx += 1
		while left_idx > 0:
			if line[left_idx-1] != mine:
				break
			left_idx -= 1
		
		left_range, right_range = left_idx, right_idx
		while right_range < 8:
			if line[right_range+1] == opponent:
				break
			right_range += 1
		while left_range > 0:
			if line[left_range-1] == opponent:
				break
			left_range -= 1
		
		chess_range = right_range - left_range + 1
		if chess_range < 5:
			setRecord(self, x, y, left_range, right_range, dir_index, dir)
			return CHESS_TYPE.NONE
		
		setRecord(self, x, y, left_idx, right_idx, dir_index, dir)
		
		m_range = right_idx - left_idx + 1
		
		# M:mine chess, P:opponent chess or out of range, X: empty
		if m_range == 5:
			count[FIVE] += 1
		
		# Live Four : XMMMMX 
		# Chong Four : XMMMMP, PMMMMX
		if m_range == 4:
			left_empty = right_empty = False
			if line[left_idx-1] == empty:
				left_empty = True			
			if line[right_idx+1] == empty:
				right_empty = True
			if left_empty and right_empty:
				count[FOUR] += 1
			elif left_empty or right_empty:
				count[SFOUR] += 1
		
		# Chong Four : MXMMM, MMMXM, the two types can both exist
		# Live Three : XMMMXX, XXMMMX
		# Sleep Three : PMMMX, XMMMP, PXMMMXP
		if m_range == 3:
			left_empty = right_empty = False
			left_four = right_four = False
			if line[left_idx-1] == empty:
				if line[left_idx-2] == mine: # MXMMM
					setRecord(self, x, y, left_idx-2, left_idx-1, dir_index, dir)
					count[SFOUR] += 1
					left_four = True
				left_empty = True
				
			if line[right_idx+1] == empty:
				if line[right_idx+2] == mine: # MMMXM
					setRecord(self, x, y, right_idx+1, right_idx+2, dir_index, dir)
					count[SFOUR] += 1
					right_four = True 
				right_empty = True
			
			if left_four or right_four:
				pass
			elif left_empty and right_empty:
				if chess_range > 5: # XMMMXX, XXMMMX
					count[THREE] += 1
				else: # PXMMMXP
					count[STHREE] += 1
			elif left_empty or right_empty: # PMMMX, XMMMP
				count[STHREE] += 1
		
		# Chong Four: MMXMM, only check right direction
		# Live Three: XMXMMX, XMMXMX the two types can both exist
		# Sleep Three: PMXMMX, XMXMMP, PMMXMX, XMMXMP
		# Live Two: XMMX
		# Sleep Two: PMMX, XMMP
		if m_range == 2:
			left_empty = right_empty = False
			left_three = right_three = False
			if line[left_idx-1] == empty:
				if line[left_idx-2] == mine:
					setRecord(self, x, y, left_idx-2, left_idx-1, dir_index, dir)
					if line[left_idx-3] == empty:
						if line[right_idx+1] == empty: # XMXMMX
							count[THREE] += 1
						else: # XMXMMP
							count[STHREE] += 1
						left_three = True
					elif line[left_idx-3] == opponent: # PMXMMX
						if line[right_idx+1] == empty:
							count[STHREE] += 1
							left_three = True
						
				left_empty = True
				
			if line[right_idx+1] == empty:
				if line[right_idx+2] == mine:
					if line[right_idx+3] == mine:  # MMXMM
						setRecord(self, x, y, right_idx+1, right_idx+2, dir_index, dir)
						count[SFOUR] += 1
						right_three = True
					elif line[right_idx+3] == empty:
						#setRecord(self, x, y, right_idx+1, right_idx+2, dir_index, dir)
						if left_empty:  # XMMXMX
							count[THREE] += 1
						else:  # PMMXMX
							count[STHREE] += 1
						right_three = True
					elif left_empty: # XMMXMP
						count[STHREE] += 1
						right_three = True
						
				right_empty = True
			
			if left_three or right_three:
				pass
			elif left_empty and right_empty: # XMMX
				count[TWO] += 1
			elif left_empty or right_empty: # PMMX, XMMP
				count[STWO] += 1
		
		# Live Two: XMXMX, XMXXMX only check right direction
		# Sleep Two: PMXMX, XMXMP
		if m_range == 1:
			left_empty = right_empty = False
			if line[left_idx-1] == empty:
				if line[left_idx-2] == mine:
					if line[left_idx-3] == empty:
						if line[right_idx+1] == opponent: # XMXMP
							count[STWO] += 1
				left_empty = True

			if line[right_idx+1] == empty:
				if line[right_idx+2] == mine:
					if line[right_idx+3] == empty:
						if left_empty: # XMXMX
							#setRecord(self, x, y, left_idx, right_idx+2, dir_index, dir)
							count[TWO] += 1
						else: # PMXMX
							count[STWO] += 1
				elif line[right_idx+2] == empty:
					if line[right_idx+3] == mine and line[right_idx+4] == empty: # XMXXMX
						count[TWO] += 1
						
		return CHESS_TYPE.NONE


https://www.xamrdz.com/lan/55v1960974.html

相关文章: