class Game: def __init__(self, size: tuple, p1, p2, win_length): self.checkerboard = CheckerBoard(size) self.p1 = p1 self.p2 = p2 self.win_length = min(size[0], win_length) def __str__(self): return str(self.checkerboard) def play(self): player = self.p1 while len(self.checkerboard.empty_locations) > 0: try: loc = player.next_loc(self.checkerboard, self.win_length) self.checkerboard.move(player.color, loc) print(self.checkerboard) except Exception as ex: print(ex) return 0 if self.checkerboard.judge(player.color, self.win_length): return player.color player = self._next(player) return 0 def _next(self, player): if player == self.p1: return self.p2 else: return self.p1 def refresh(self): self.checkerboard = CheckerBoard(self.checkerboard.size)
def simulate(self, checkerboard: CheckerBoard, loc: Location, color: int, depth: int, win_length: int): res = {1: 0, -1: 0, 0: 0} checkerboard.move(color, loc) if checkerboard.judge(color, win_length): # win the game res[color] += 1 return res elif depth == 0: # random play player = player1 = Player(-color) player2 = Player(color) while True: try: loc = player.next_loc(checkerboard, win_length) checkerboard.move(player.color, loc) except: res[0] += 1 return res if checkerboard.judge(player.color, win_length): res[player.color] += 1 return res player = player == player1 and player2 or player1 else: state = checkerboard.state locations = set(checkerboard.empty_locations) if len(locations) > 0: for loc in locations: result = self.simulate(checkerboard, loc, -color, depth - 1, win_length) res[0] += result[0] res[1] += result[1] res[-1] += result[-1] checkerboard.state = state else: return res return res