def test_place_workers(self): positions = self.player.place_workers(self.initial_board) self.assertEqual(positions, [Position(0, 0), Position(0, 4)]) initial_board2 = Board(self.INITIAL_BOARD2) positions2 = self.player.place_workers(initial_board2) self.assertEqual(positions2, [Position(4, 4), Position(4, 0)])
def __init__(self): self.color = '' self.strategy = Strategy() self.starting_positions = [Position(0, 0), Position(0, 4), Position(4, 4), Position(4, 0)] self.RuleChecker = RuleChecker() self.game_state = 'start' self.name = 'Kanye' self.last_board = Board([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
def __init__(self, color): self.color = color self.strategy = Strategy() self.starting_positions = [ Position(0, 0), Position(0, 4), Position(4, 4), Position(4, 0) ]
def execute(self, input): command = input[0] if not self.check_input(input): return self.error_message() if command == 'Register' and self.game_state == 0: self.game_state = 1 return self.name if command == 'Place' and self.game_state == 1: self.color = str(input[1]) b = Board(input[2]) self.last_board = b if not self.RuleChecker.validate_initial_board(b, self.color): return self.error_message() self.game_state = 2 posns = self.place_workers(b) self.last_board.worker_locations[self.color + '1'] = Position( posns[0][0], posns[0][1]) self.last_board.worker_locations[self.color + '2'] = Position( posns[1][0], posns[1][1]) return posns if command == 'Play' and self.game_state == 2: b = Board(input[1]) if not self.is_possible_board(b): return self.error_message() self.last_board = b if not self.RuleChecker.validate_board(b): return self.error_message() play_options = self.get_plays(b) if play_options: index = random.randint(0, len(play_options) - 1) playmade = self.format_plays(play_options)[index] else: play_options = self.strategy.get_legal_plays(self.color, b) if play_options: index = random.randint(0, len(play_options) - 1) playmade = self.format_plays(play_options)[index] else: playmade = [] if playmade: if len(playmade) == 3: Playmade = Play(playmade[0], playmade[1], playmade[2]) else: Playmade = Play(playmade[0], playmade[1]) self.last_board = Playmade.resulting_board(self.last_board) return playmade if command == 'Game Over': self.game_state = 0 self.last_board = Board([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) self.color = '' return 'OK' return self.error_message()
def __init__(self): self.color = '' self.strategy = Strategy() self.starting_positions = [ Position(0, 0), Position(0, 4), Position(4, 4), Position(4, 0) ] self.RuleChecker = RuleChecker() self.game_state = 0 self.name = ''.join( random.choice(string.ascii_uppercase) for _ in range(5)) self.last_board = Board([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
def act(self, board): player = board.turn() actions = board.list_moves() scored_actions = [] middle = board.width // 2 for action in actions: row = board.row(action) pos = Position(row, action) score = 0 if board.would_win(pos, player): score += 1000000 if board.would_win(pos, 3 - player): score += 1000 score += middle - abs(middle - action) scored_actions.append((action, score)) scored_actions.sort(key=lambda value: -value[1]) best_score = scored_actions[0][1] best_moves = [ action for action, score in scored_actions if score == best_score ] return random.choice(best_moves)
def drawBoard(self, squareSize=100): widthOffset = (WIDTH - squareSize * 8) / 2 heightOffset = (HEIGHT - squareSize * 8) / 2 black = True for row in range(8): black = not black for col in range(8): pos = Position( left=widthOffset + squareSize * col, top=heightOffset + squareSize * row, ) square = BoardSquare( position=pos, width=squareSize, piece=None, filled=None, location=(row, col), ) grid[row][col] = square rect = pygame.Rect(square.position.left, square.position.top, 100, 100) if black: pygame.draw.rect(WIN, colors.BOARD_GREEN, rect) else: pygame.draw.rect(WIN, colors.BOARD_WHITE, rect) black = not black
def random_to_random(): win_num = 0 for j in range(10000): pos = Position(empty_board,'A',0,-1) step = 0 while True: try: index = pos.pick_move()[0] except Exception: win_num+=0.5 break pos = pos.move(index) if pos.reward()!=0: win_num+=1 break try: index2 = pos.pick_move()[0] except Exception: win_num+=0.5 break pos = pos.move(index2) if pos.reward()!=0: break step+=1 if step>=N*N: win_num+=0.5 pos.show() return win_num/100.0
def load_map(file_name): walls, goals = set(), set() boxes, player = set(), None with open(file_name, 'r') as f: num_lines = int(f.readline()) for y, line in enumerate(f.readlines()): if line: for x, char in enumerate(line): pos = Position(x, y) if char in WALL: walls.add(pos) if char in GOAL: goals.add(pos) if char in BOX: boxes.add(pos) if char in PLAYER: player = pos else: break board = Board(num_lines, walls, goals) return board, boxes, player
def play_and_train(net,i,batches_per_game=2): positions = [] tree = TreeNode(net=net,pos=Position(empty_board,'A',0,-1)) tree.expand() while True: # tree search move one step next_tree = tree_search(tree,N_SIMS) positions.append((tree.pos,tree.distribution())) tree = next_tree #tree.pos.show() #print 'Number of A is %d, number of a is %d' % (tree.pos.board.count('A'),tree.pos.board.count('a')) reward = tree.pos.reward() if reward!=0.0: # attention!!! print 'attention reward is ',reward if tree.pos.turn=='A': score = -1.0 else: score = 1.0 #tree.expand() #next_tree = tree_search(tree,N_SIMS) #positions.append((tree.pos,tree.distribution())) break if tree.pos.step > N*N*2: score = 0.0 break #print 'Begin fit_game==================' X_positions = [encode_position(pos) for pos,dist in positions] X_dists = [dist for pos,dist in positions] net.fit_game(X_positions,X_dists,score) X_positions = [encode_position(pos,board_transform='flip_vert') for pos,dist in positions] X_dists = [dist for pos,dist in positions] net.fit_game(X_positions,X_dists,score) X_positions = [encode_position(pos,board_transform='flip_horiz') for pos,dist in positions] X_dists = [dist for pos,dist in positions] net.fit_game(X_positions,X_dists,score) X_positions = [encode_position(pos,board_transform='flip_both') for pos,dist in positions] X_dists = [dist for pos,dist in positions] net.fit_game(X_positions,X_dists,score) X_positions = [encode_position(pos,board_transform='flip_clock') for pos,dist in positions] X_dists = [dist for pos,dist in positions] net.fit_game(X_positions,X_dists,score) X_positions = [encode_position(pos,board_transform='flip_reverse_clock') for pos,dist in positions] X_dists = [dist for pos,dist in positions] net.fit_game(X_positions,X_dists,score) X_positions = [encode_position(pos,board_transform='flip_clock2') for pos,dist in positions] X_dists = [dist for pos,dist in positions] net.fit_game(X_positions,X_dists,score) X_positions = [encode_position(pos,board_transform='flip_reverse_clock2') for pos,dist in positions] X_dists = [dist for pos,dist in positions] net.fit_game(X_positions,X_dists,score)
def placement(self, coord1, coord2): worker1 = self.turn + '1' worker2 = self.turn + '2' worker1_Pos = Position(coord1[0], coord1[1]) worker2_Pos = Position(coord2[0], coord2[1]) if not self.board._is_in_bounds( worker1_Pos) or not self.board._is_in_bounds(worker2_Pos): return self._opponent_wins(self.turn) if self.board.is_cell_occupied( worker1_Pos) or self.board.is_cell_occupied(worker2_Pos): return self._opponent_wins(self.turn) self.board.worker_locations[worker1] = worker1_Pos self.board.worker_locations[worker2] = worker2_Pos self.turn = self._opponent_color(self.turn) return self.board
def test_battle_process(): start_timestamp = 1510000000 board = Board(piece_shape_set_generate()) battle = Battle(start_timestamp, 5, 2, board) for player_id in range(4): assert battle.try_join_player(start_timestamp, player_id, {"user_id": player_id}) assert battle.try_drop_piece(start_timestamp, 0, 0, Position())
def add_to_board(self, board): moves = {} for row in range(1, board.rows + 1): for column in range(1, board.columns + 1): p = Position(row, column, board, self.verbosity.verbose_int) possible_positions = [] for i in self.moves: possible_position = p.get_new_position(i[0], i[1]) if possible_position.fits_on_board: possible_positions.append(possible_position) moves[p.coordinate] = possible_positions Knight.all_possible_moves = moves
def execute(self, input): command = input[0] if not self.check_input(input): return self.error_message() if command == 'Register' and self.game_state == 0: self.game_state = 1 return 'Kanye' if command == 'Place' and self.game_state == 1: self.color = str(input[1]) b = Board(input[2]) self.last_board = b if not self.RuleChecker.validate_initial_board(b, self.color): return self.error_message() self.game_state = 2 posns = self.place_workers(b) self.last_board.worker_locations[self.color + '1'] = Position( posns[0][0], posns[0][1]) self.last_board.worker_locations[self.color + '2'] = Position( posns[1][0], posns[1][1]) return posns if command == 'Play' and self.game_state == 2: b = Board(input[1]) if not self.is_possible_board(b): return self.error_message() self.last_board = b if not self.RuleChecker.validate_board(b): return self.error_message() play_options = self.get_plays(b) if play_options: return self.format_plays(play_options)[0] else: play_options = self.strategy.get_legal_plays(self.color, b) if play_options: return self.format_plays(play_options)[0] else: return [] if command == 'Game Over' and self.game_state == 2: self.game_state = 3 return 'OK' return self.error_message()
def is_possible_board(self, b): opponent_possible_boards = [] l_board = self.last_board if len(l_board.worker_locations.keys()) < 2: grid = b.height_grid for row in grid: for cell in row: if cell > 0: return False return True if len(l_board.worker_locations.keys()) < 4: grid = b.height_grid sum = 0 for row in grid: for cell in row: sum = sum + cell if sum == 1: return True return False oldgrid = l_board.height_grid newgrid = b.height_grid oldworkers = l_board.worker_locations newworkers = b.worker_locations heightchange = [] movedworkers = [] for i in range(len(oldgrid)): for j in range(len(oldgrid[0])): if oldgrid[i][j] != newgrid[i][j]: if newgrid[i][j] - oldgrid[i][j] != 1: return False heightchange.append(Position(i, j)) if len(heightchange) > 2: return False for worker in oldworkers.keys(): if oldworkers[worker] != newworkers[worker]: if not oldworkers[worker].near(newworkers[worker]): return False movedworkers.append(worker) found = 0 if len(movedworkers) > 2: return False if movedworkers[0][:-1] == movedworkers[1][:-1]: return False for worker in movedworkers: newpos = newworkers[worker] if newpos.near(heightchange[0]): heightchange[0] = heightchange[1] found = found + 1 elif newpos.near(heightchange[1]): heightchange[1] = heightchange[0] found = found + 1 return found == 2
def placement(self, p): rsp = p.execute(['Place', self.turn, self.board.format_board()]) coords = rsp if isinstance(coords, (basestring, str)): return self.otherplayerwins() coord1 = coords[0] coord2 = coords[1] worker1 = self.turn + '1' worker2 = self.turn + '2' worker1_Pos = Position(coord1[0], coord1[1]) worker2_Pos = Position(coord2[0], coord2[1]) if not self.board._is_in_bounds( worker1_Pos) or not self.board._is_in_bounds(worker2_Pos): return self.otherplayerwins() if self.board.is_cell_occupied( worker1_Pos) or self.board.is_cell_occupied(worker2_Pos): return self.otherplayerwins() self.board.worker_locations[worker1] = worker1_Pos self.board.worker_locations[worker2] = worker2_Pos self.turn = self.other_color(self.turn) return self.board
def _generate_start_position(self, start_position): error1 = "The %s value of your start position must be an integer. Please enter the starting location in the following format: 4.5" error2 = "the %s (the %s value of the starting position) does not fit on the board" row_column = start_position.split(".") assert len(row_column) is 2, "start position must contain exactly one '.' period" try: row = int(row_column[0]) except ValueError: print error1 %("first") exit(1) try: column = int(row_column[1]) except ValueError: print error1 %("second") exit(1) assert 0 < row <= self.board.rows, error2 %("row","first") assert 0 < column <= self.board.columns, error2 %("column","second") return Position(row, column, self.board, self.verbosity.verbose_int)
def evaluate_random(net): win_num = 0 for j in range(100): pos = Position(empty_board,'A',0,-1) step = 0 while True: pos_array = encode_position(pos) pos_array_new = np.expand_dims(pos_array,axis=0) dis = net.predict_distribution(pos_array_new) index = np.argmax(dis) while index<N*N and pos.board[index]!='.': dis[index] = 0.0 index = np.argmax(dis) if index == N*N: index = pos.pick_move()[0] if pos.board[index]!='.': win_num+=0.5 break pos = pos.move(index) if pos.reward()!=0: win_num+=1 break try: index2 = pos.pick_move()[0] except Exception: win_num+=0.5 break pos = pos.move(index2) if pos.reward()!=0: break step+=1 if step>=N*N: win_num+=0.5 pos.show() return win_num/100.0
def main(): img = get_image() squares = get_squares(img) walls, goals = set(), set() boxes, player = set(), None num_lines = len(squares) for y, line in enumerate(squares): for x, s in enumerate(line): char = detect(s) pos = Position(x, y) if char in WALL: walls.add(pos) if char in GOAL: goals.add(pos) if char in BOX: boxes.add(pos) if char in PLAYER: player = pos if len(boxes) - len(goals) == 1: goals.add(player) board = Board(num_lines, walls, goals) board.print_board(boxes, player) path = Astar_search(board, boxes, player) idx = 0 for boxes, player in path[::-1]: idx += 1 subprocess.call('clear') board.print_board(boxes, player) input()
def test_is_in_bounds(self): self.assertFalse(self.board._is_in_bounds(Position(0, 5))) self.assertFalse(self.board._is_in_bounds(Position(5, 3))) self.assertFalse(self.board._is_in_bounds(Position(0, -1))) self.assertTrue(self.board._is_in_bounds(Position(3, 2)))
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Oct 7 16:56:36 2018 @author: ubuntu """ from board import make_board, Position, empty_board p0 = Position(empty_board, 'A', 0, -1) p0.show() print '===========' p1 = p0.move(0) p1.show() print '===========' p2 = p1.move(1) p2.show() print '===========' p3 = p2.move(2) p3.show() print '===========' board = make_board(empty_board) p4 = Position(board, 'A', 10, -1) p4.show() p5 = p4.flip_clock() print '===========' p5.show() print '===========' p6 = p4.flip_reverse_clock() p6.show()
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Oct 7 17:12:14 2018 @author: ubuntu """ from mcts import encode_position, TreeNode from board import Position, make_board, empty_board from net import GobangModel p0 = Position(make_board(empty_board), 'a', 0, -1) p0.show() x = encode_position(p0) print x[10:15, 0, 0] print x[10:15, 0, 1] print x[10:15, 0, 2] p1 = p0.move(18) y = encode_position(p1) print y[10:15, 0, 0] print y[10:15, 0, 1] print y[10:15, 0, 2] p2 = p1.move(37) z = encode_position(p2) print z[10:15, 0, 0] print z[10:15, 0, 1] print z[10:15, 0, 2]
def is_satisfying(self): return self._is_satisfying(Position(self.rows, self.cols), self.tree)
def would_win(self, action, player): row = self.board.row(action) pos = Position(row, action) return self.board.would_win(pos, player)