# ----------------------------------------------------------------------# 定义棋子类型,输赢情况# ----------------------------------------------------------------------
EMPTY = 0
BLACK = 1
WHITE = 2# ----------------------------------------------------------------------# 定义棋盘类,绘制棋盘的形状,切换先后手,判断输赢等# ----------------------------------------------------------------------classChessBoard(object):def__init__(self):
self.__board = [[EMPTY for n in range(15)] for m in range(15)]
self.__dir = [[(-1, 0), (1, 0)], [(0, -1), (0, 1)], [(-1, 1), (1, -1)], [(-1, -1), (1, 1)]]
# (左 右) (上 下) (左下 右上) (左上 右下)defboard(self):# 返回数组对象return self.__board
defdraw_xy(self, x, y, state):# 获取落子点坐标的状态
self.__board[x][y] = state
defget_xy_on_logic_state(self, x, y):# 获取指定点坐标的状态return self.__board[x][y]
defget_next_xy(self, point, direction):# 获取指定点的指定方向的坐标
x = point[0] + direction[0]
y = point[1] + direction[1]
if x < 0or x >= 15or y < 0or y >= 15:
returnFalseelse:
return x, y
defget_xy_on_direction_state(self, point, direction):# 获取指定点的指定方向的状态if point isnotFalse:
xy = self.get_next_xy(point, direction)
if xy isnotFalse:
x, y = xy
return self.__board[x][y]
returnFalsedefanyone_win(self, x, y):
state = self.get_xy_on_logic_state(x, y) # 当前落下的棋是黑棋还是白棋,它的状态存储在state中for directions in self.__dir: # 对米字的4个方向分别检测是否有5子相连的棋
count = 1# 初始记录为1,因为刚落下的棋也算for direction in directions: # 对落下的棋子的同一条线的两侧都要检测,结果累积
point = (x, y) # 每次循环前都要刷新whileTrue:
if self.get_xy_on_direction_state(point, direction) == state:
count += 1
point = self.get_next_xy(point, direction)
else:
breakif count >= 5:
return state
return EMPTY
defreset(self):# 重置
self.__board = [[EMPTY for n in range(15)] for m in range(15)]
这里加了一个线程执行AI的计算,前面有个 from ai import searcher ,ai还没有写,先从网上找了一个博弈的算法。searcher()就是AI类。该线程传入参数是 board 就是棋盘状态。调用self.ai.search(2, 2),第一个2是博弈树的深度,值越大AI越聪明,但是计算时间也越长。第二个2是说电脑执白棋,如果为1则是黑棋。线程结束后传入参数 x, y 就是AI计算后线程传出的参数。