还是一大排重复的代码呀,我还是觉得它丑啊,我真的不是处女座,但是这个函数是真丑啊,能不能让它再帅一点,当然可以,4个重复块再收成一个函数,循环调4次,是不是可以,好,就这么干,于是have_five就又漂亮了一点点:
def have_five(self, i, j, color): #四个方向计数 横 竖 左斜 右斜 directions = [[(-1, 0), (1, 0)], \ [(0, -1), (0, 1)], \ [(-1, 1), (1, -1)], \ [(-1, -1), (1, 1)]] for axis in directions: axis_count = 1 for (xdirection, ydirection) in axis: axis_count += self.count_on_direction(i, j, xdirection, ydirection, color) if axis_count >= 5: return True return False
嗯,感觉好多了,这下判断是否有5颗相同颜色棋子的逻辑也有了,再加一个函数来给界面层返回结果,逻辑部分的代码就差不多了:
def get_chess_result(self): if self.have_five(self.__currentI, self.__currentJ, self.__currentState): return self.__currentState else: return ChessboardState.EMPTY
于是,五子棋逻辑代码就写完了,完整代码 gobang.py 如下:
enum import Enum from consts import * class GoBang(object): def __init__(self): self.__chessMap = [[ChessboardState.EMPTY for j in range(N)] for i in range(N)] self.__currentI = -1 self.__currentJ = -1 self.__currentState = ChessboardState.EMPTY def get_chessMap(self): return self.__chessMap def get_chessboard_state(self, i, j): return self.__chessMap[i][j] def set_chessboard_state(self, i, j, state): self.__chessMap[i][j] = state self.__currentI = i self.__currentJ = j self.__currentState = state def get_chess_result(self): if self.have_five(self.__currentI, self.__currentJ, self.__currentState): return self.__currentState else: return ChessboardState.EMPTY def count_on_direction(self, i, j, xdirection, ydirection, color): count = 0 xdirection != 0 and (j + xdirection * step < 0 or j + xdirection * step >= N): break if ydirection != 0 and (i + ydirection * step < 0 or i + ydirection * step >= N): break if self.__chessMap[i + ydirection * step][j + xdirection * step] == color: count += 1 else: break return count def have_five(self, i, j, color): #四个方向计数 横 竖 左斜 右斜 directions = [[(-1, 0), (1, 0)], \ [(0, -1), (0, 1)], \ [(-1, 1), (1, -1)], \ [(-1, -1), (1, 1)]] for axis in directions: axis_count = 1 for (xdirection, ydirection) in axis: axis_count += self.count_on_direction(i, j, xdirection, ydirection, color) if axis_count >= 5: return True return False
小伙伴:大哥,憋了半天,就憋出这么不到60行代码?
我:代码不在多,实现则灵……
明天来给它加个render,前端界面就有了,就是一个简单的完整游戏了,至于AI,别急嘛。
好吧,就这样…
UI部分在这里:
[深度学习]实现一个博弈型的AI,从五子棋开始(2)