def test_cycles_work(self): # Set up a player in an almost win state and see if the cycles can # find the win state. The nnet used should just return a random value # between -1 and 1 class RandomNNet(): def __init__(self): pass def predict(self, canonicalBoard): v = random.uniform(-0.999999999999, 0.999999999999) p = [random.random() for i in range(3151)] p = np.array(p) / sum(p) return p, v player_list = [ MCTSNNPlayer(1, 50, RandomNNet()), RandomPlayer(2), RandomPlayer(3) ] player_list[0].dev_cards[Card.VICTORY_POINT] = 8 player_list[0].resources = {'w': 2, 'b': 4, 'l': 4, 'g': 2, 'o': 0} player_list[0].trades_tried = 2 player_list[0].has_rolled = True deck = Deck() board = Board(player_list, False) board.round_num = 3 player_list[0].make_move(Move(Move.BUY_SETTLEMENT, coord=(0, 1)), board, deck, player_list) player_list[0].make_move( Move(Move.BUY_ROAD, road=frozenset([(0, 1), (1, 1)])), board, deck, player_list) player_list[0].make_move( Move(Move.BUY_ROAD, road=frozenset([(0, 0), (1, 1)])), board, deck, player_list) print(player_list[0].decide_move(board, deck, player_list))
def test_draw_dev_play_dev_same_turn(self): player_list = [RandomPlayer(1)] deck = Deck() board = Board(player_list, False) board.active_player = player_list[0] board.round_num = 2 player_list[0].resources = {'w': 1, 'b': 0, 'l': 0, 'g': 1, 'o': 1} player_list[0].has_rolled = True # After buying a dev card, we cannot play it. move_made = player_list[0].make_move( Move(Move.BUY_DEV, card_type=0, player=1), board, deck, player_list) self.assertEqual(move_made, 1) self.assertEqual(player_list[0].dev_drawn, 0) legal_moves = player_list[0].get_legal_moves(board, deck) is_legal = player_list[0].check_legal_move( Move(Move.PLAY_DEV, card_type=0, coord=(0, 0)), board, deck) self.assertEqual(is_legal, False) self.assertEqual(len(legal_moves), 1) self.assertNotEqual(legal_moves[0].move_type, Move.PLAY_DEV) self.assertEqual(player_list[0].dev_cards[0], 1) # Check that if we have another dev card that is the same as the one drawn, # we can play it player_list[0].dev_cards[0] += 1 legal_moves = player_list[0].get_legal_moves(board, deck) self.assertGreater(len(legal_moves), 1) self.assertEqual((legal_moves[1].move_type, legal_moves[1].card_type), (Move.PLAY_DEV, 0)) is_legal = player_list[0].check_legal_move( Move(Move.PLAY_DEV, card_type=0, coord=(0, 0)), board, deck) self.assertEqual(is_legal, True) move_made = player_list[0].make_move( Move(Move.PLAY_DEV, card_type=0, coord=(0, 0)), board, deck, player_list) self.assertEqual(move_made, 1) self.assertEqual(player_list[0].dev_cards[0], 1) self.assertEqual(player_list[0].dev_played, 1) # Now, end the turn and check that on the next turn, we can play the knight that is left over player_list[0].make_move(Move(Move.END_TURN), board, deck, player_list) legal_moves = player_list[0].get_legal_moves(board, deck) self.assertIn(Move(Move.PLAY_DEV, card_type=0, coord=(1, 0)), legal_moves) self.assertNotIn(Move(Move.PLAY_DEV, card_type=0, coord=(0, 0)), legal_moves) self.assertEqual(player_list[0].dev_drawn, -1) self.assertEqual(player_list[0].dev_played, 0) is_legal = player_list[0].check_legal_move( Move(Move.PLAY_DEV, card_type=0, coord=(1, 0)), board, deck) self.assertEqual(is_legal, True) is_legal = player_list[0].check_legal_move( Move(Move.PLAY_DEV, card_type=0, coord=(0, 0)), board, deck) self.assertEqual(is_legal, False) move_made = player_list[0].make_move( Move(Move.PLAY_DEV, card_type=0, coord=(1, 0)), board, deck, player_list) self.assertEqual(move_made, 1) self.assertEqual(player_list[0].dev_played, 1)
def exchange(self): if len(distribution)<7: return [] exchs = self.gac(self.rack, len(self.rack)) for i in exchs: exch = Move(i, self.board, 0, 0, 0, self.board, self.rack, _type = 'e') exch.score = 0 exch.getEvaluation(self.rack) yield exch
def choose_trader(self, traders): while True: print("Below players are available to trade.") for trader in traders: print("Player {}".format(trader.player_num)) choice = int(input("Which player do you want to trade with? Input -1 to cancel the trade.")) if choice == -1: return Move(Move.CHOOSE_TRADER, player=None) for trader in traders: if trader.player_num == choice: return Move(Move.CHOOSE_TRADER, player=choice) print("invalid choice!")
def select_move(self, game_state): """Choose a random valid move that preserves our own eyes.""" candidates = [] for r in range(1, game_state.board.num_rows + 1): for c in range(1, game_state.board.num_cols + 1): candidate = Point(row=r, col=c) if game_state.is_valid_move(Move.play(candidate)) and \ not is_point_an_eye(game_state.board, candidate, game_state.next_player): candidates.append(candidate) if not candidates: return Move.pass_turn() return Move.play(random.choice(candidates))
def legal_moves(self): # 所有合法的操作 moves = [] for row in range(1, self.board.num_rows + 1): for col in range(1, self.board.num_cols + 1): move = Move.play(Point(row, col)) if self.is_valid_move(move): moves.append(move) moves.append(Move.pass_turn()) moves.append(Move.resign()) moves.append(Move.restart()) moves.append(Move.turn_back()) return moves
def setUp(self): self.m = [] with open('test_map.txt', 'r') as f: for i in f.readlines(): i = i.rstrip() self.m.append(list(i)) self.hero = Hero(name='ivan', title='Dragon Slayer', health=100, mana=100, mana_regeneration_rate=2, spell=None, weapon=None) self.mover = Move(self.hero)
def select_move(self, game_state): """Choose a random valid move that preserves our own eyes.""" dim = (game_state.board.num_rows, game_state.board.num_cols) if dim != self.dim: self._update_cache(dim) idx = np.arange(len(self.point_cache)) np.random.shuffle(idx) for i in idx: p = self.point_cache[i] if game_state.is_valid_move(Move.play(p)) and \ not is_point_an_eye(game_state.board, p, game_state.next_player): return Move.play(p) return Move.pass_turn()
def test_other_player_has_more_than_seven(self): player_list = [RandomPlayer(1), RandomPlayer(2), RandomPlayer(3)] for player in player_list: player.resources = {'w': 0, 'b': 0, 'l': 3, 'g': 2, 'o': 0} deck = Deck() board = Board(player_list, False) board.round_num = 3 board.active_player = player_list[0] player_list[1].resources = {'w': 5, 'b': 5, 'l': 3, 'g': 2, 'o': 1} move_made = player_list[0].make_move(Move(Move.ROLL_DICE, roll=7), board, deck, player_list) self.assertEqual(move_made, 1) self.assertEqual(board.seven_roller, player_list[0]) self.assertEqual(board.active_player, player_list[1]) legal_moves = board.active_player.get_legal_moves(board, deck) for move in legal_moves: self.assertEqual(move.move_type, Move.DISCARD_HALF) decided = board.active_player.decide_move(board, deck, player_list) self.assertEqual(decided.move_type, Move.DISCARD_HALF) move_made = board.active_player.make_move(decided, board, deck, player_list) self.assertEqual(move_made, 1) self.assertEqual(board.seven_roller, None) self.assertEqual(board.active_player, player_list[0]) self.assertNotEqual(player_list[1].resources, { 'w': 5, 'b': 5, 'l': 3, 'g': 2, 'o': 1 }) self.assertEqual(sum(player_list[1].resources.values()), 8)
def possible_moves(self): x, y = self.square # typical one hop moves moves = list( map( lambda square: Move.typical( self.board, piece=self, new_square=square), filter( # Either no piece or enemy piece to capture lambda square: square and (not self.board[ square] or self.board[square].player != self.player), (Square(x + 1, y), Square(x, y + 1), Square(x + 1, y + 1), Square(x - 1, y + 1), Square(x - 1, y), Square(x, y - 1), Square(x + 1, y - 1), Square(x - 1, y - 1))))) # castling moves king_side_castle = self.king_side_castle() if king_side_castle: moves.append(king_side_castle) queen_side_castle = self.queen_side_castle() if queen_side_castle: moves.append(queen_side_castle) return moves
def detect_checkmate(self): """This function returns true if the current side is in Checkmate""" # checkmate detection is done as follows: # first we establish a list of the king possible moves (ignoring Check limitations) # then we play each of these moves and determine if we're still in check. if all moves # fail, we're in checkmate. # note: this approach is deliberately simplistic and does not take into account # resolving checkmate by other pieces. # no Check-mate if there's no Check king_attackers = self.get_king_attackers() if len(king_attackers) == 0: return False king = self._pieces[self._current_side_color][ 'K'] # should always be there. the king is never removed. king_next_positions = king.list_next_potential_positions(self._rubrics) if len(king_next_positions) == 0: # not likely but possible. the king must be physically surrounded by its own side's pieces and cant escape. return True # lets just try each and every possible move by the king: for next_position in king_next_positions: board_copy = self.get_board_copy() board_copy.move_piece(Move(king.position, next_position), ignore_check=True) if len(board_copy.get_king_attackers()) == 0: # moved out of check. yay return False return True
def test_lastal_task_nucl_x_prot(self): with TemporaryDirectory() as td: with Move(td): with TestData('test-protein.fa', td) as prot, \ TestData('test-transcript.fa', td) as tr, \ TemporaryFile(td) as out: print(os.listdir(td), file=sys.stderr) db_task = tasks.get_lastdb_task(prot, prot, self.lastdb_cfg) aln_task = tasks.get_lastal_task(tr, prot, out, self.lastal_cfg, translate=True, cutoff=None) run_tasks([db_task, aln_task], ['run']) aln = ''.join(open(out).readlines()) print(aln, file=sys.stderr) self.assertIn('SPAC212_RecQ_type_DNA_helicase_PROTEIN', aln) self.assertIn('SPAC212_RecQ_type_DNA_helicase_TRANSCRIPT', aln) self.assertIn('lambda', aln, msg='lambda missing, wrong LAST version?')
def possible_moves(self, disk: Disk) -> List[Move]: """Returns a list of all possible moves for the given disk color.""" moves = [] for square in self._empty_squares: value = 0 directions = [] # try stepping in all directions from this starting point for step in self.STEP_DIRECTIONS: pos = square + step # not valid if next disk in line is own if self._get_square(pos) == disk: continue steps = 0 # keep stepping over opponents disks while self._get_square(pos) == disk.other_disk(): steps += 1 pos += step # successful move if this direction ends in own disk if self._get_square(pos) == disk: value += steps directions.append(step) if value: moves.append(Move(square, disk, value, directions)) return sorted(moves)
def test_hmmscan_task_multithreaded(self): with TemporaryDirectory() as td: with Move(td): with TestData('20aa-alitest.fa', td) as prot, \ TestData('20aa.hmm', td) as hmm, \ TemporaryFile(td) as out_single,\ TemporaryFile(td) as out_multi: for n_threads in (2, 3, 4, 5): db_task = tasks.get_hmmpress_task( hmm, self.hmmpress_cfg) aln_task_single = tasks.get_hmmscan_task( prot, out_single, hmm, 1.0, 1, self.hmmscan_cfg) aln_task_multi = tasks.get_hmmscan_task( prot, out_multi, hmm, 1.0, n_threads, self.hmmscan_cfg) run_tasks([db_task, aln_task_single], ['run']) run_task(aln_task_multi) print(os.listdir(td), file=sys.stderr) print(open(out_single).read()) alns_single = pd.concat(hmmscan_to_df_iter(out_single)) alns_multi = pd.concat(hmmscan_to_df_iter(out_multi)) self.assertTrue(all(alns_single['domain_i_evalue'].sort_values() == \ alns_multi['domain_i_evalue'].sort_values()))
def test_cmscan_task_multithreaded(self): with TemporaryDirectory() as td: with Move(td): with TestData('rnaseP-bsu.fa', td) as transcript, \ TestData('rnaseP-eubact.c.cm', td) as cm, \ TemporaryFile(td) as out_single,\ TemporaryFile(td) as out_multi: for n_threads in (2, 3, 4, 5): db_task = tasks.get_cmpress_task(cm, self.cmpress_cfg) aln_task_single = tasks.get_cmscan_task( transcript, out_single, cm, 1.0, 1, self.cmscan_cfg) aln_task_multi = tasks.get_cmscan_task( transcript, out_multi, cm, 1.0, n_threads, self.cmscan_cfg) run_tasks([db_task, aln_task_single], ['run']) run_task(aln_task_multi) alns_single = pd.concat(cmscan_to_df_iter(out_single)) alns_multi = pd.concat(cmscan_to_df_iter(out_multi)) self.assertTrue(all(alns_single['e_value'].sort_values() == \ alns_multi['e_value'].sort_values()))
def test_places_for_road(self): player_list = [RandomPlayer(1)] deck = Deck() board = Board(player_list, False) player_list[0].settlements.append((0, 0)) board.add_settlement(player_list[0], (0, 0)) player_list[0].add_road(board, frozenset([(0, 0), (1, 0)])) board.build_road((0, 0), (1, 0), player_list[0]) board.round_num = 2 board.active_player = player_list[0] player_list[0].has_rolled = True player_list[0].resources = {'w': 0, 'b': 1, 'l': 1, 'g': 0, 'o': 0} legal_moves = player_list[0].get_legal_moves(board, deck) self.assertIn(Move(Move.BUY_ROAD, road=frozenset([(2, 0), (1, 0)])), legal_moves) self.assertIn(Move(Move.BUY_ROAD, road=frozenset([(0, 0), (1, 1)])), legal_moves)
def action_to_index(move, current_player_num, total_players, move_to_index): try: if ((move.card_type == Card.KNIGHT and move.move_type == move.PLAY_DEV) \ or move.move_type == move.MOVE_ROBBER or \ move.move_type == move.CHOOSE_TRADER) and move.player != None: victim = move.player - current_player_num + 1 if move.player - current_player_num > 0 \ else total_players - current_player_num + move.player + 1 return move_to_index[Move(move.move_type, card_type=move.card_type, \ coord=move.coord, player=victim)] if move in move_to_index: return move_to_index[move] if move.move_type == move.BUY_DEV: return move_to_index[Move(Move.BUY_DEV)] if move.card_type == Card.ROAD_BUILDING: return move_to_index[Move(move.move_type, card_type=move.card_type, \ road=move.road2, road2=move.road)] if move.move_type == Move.PROPOSE_TRADE: return move_to_index[Move(move.move_type, give_resource=move.give_resource, \ resource=move.resource)] if move.move_type == Move.ROLL_DICE: return move_to_index[Move(move.move_type)] if move.move_type == Move.DISCARD_HALF: return move_to_index[Move(move.move_type)] elif move.card_type == Card.YEAR_OF_PLENTY: return move_to_index[Move(move.move_type, card_type=move.card_type, \ resource=move.resource2, resource2=move.resource)] else: print("Cannot find index for this move: ") print(move) raise (Exception("move not in all possible move array!")) except: print("Cannot find index for this move; key exception") print(move) raise (Exception("move not in all possible move array!"))
def set_value_in_action_vector(action_vector, current_player_num, \ total_players, move_to_index, move, value): if ((move.card_type == Card.KNIGHT and move.move_type == move.PLAY_DEV) \ or move.move_type == move.MOVE_ROBBER or \ move.move_type == move.CHOOSE_TRADER) and move.player != None: victim = move.player - current_player_num + 1 if move.player - current_player_num > 0 \ else total_players - current_player_num + move.player + 1 action_vector[move_to_index[Move(move.move_type, card_type=move.card_type, \ coord=move.coord, player=victim)]] = value elif move in move_to_index: action_vector[move_to_index[move]] = value elif move.move_type == move.BUY_DEV: action_vector[move_to_index[Move(Move.BUY_DEV)]] = value elif move.card_type == Card.ROAD_BUILDING: action_vector[move_to_index[Move(move.move_type, card_type=move.card_type, \ road=move.road2, road2=move.road)]] = value elif move.move_type == Move.PROPOSE_TRADE: action_vector[move_to_index[Move(move.move_type, give_resource=move.give_resource, \ resource=move.resource)]] = value elif move.move_type == Move.ROLL_DICE: action_vector[move_to_index[Move(move.move_type)]] = value elif move.move_type == Move.DISCARD_HALF: action_vector[move_to_index[Move(move.move_type)]] = value elif move.card_type == Card.YEAR_OF_PLENTY: action_vector[move_to_index[Move(move.move_type, card_type=move.card_type, \ resource=move.resource2, resource2=move.resource)]] = value else: print("Cannot find index for this move: ") print(move) raise (Exception("move not in all possible move array!"))
def choose_spot_road(self, board): legal_road = False while not legal_road: loc = self.choose_road(board) move = Move(Move.BUY_ROAD, road=loc) legal_road = self.can_build_road(move, board) if not legal_road: print("Not a legal road! Try again.") return move
def choose_spot_settlement(self, board): legal_settlement = False while not legal_settlement: # Pick a legal spot loc = self.build_settlement(board) legal_settlement = self.can_build_settlement(loc, board) if not legal_settlement: print("Not a legal settlement! Try again.") move = Move(Move.BUY_SETTLEMENT, coord=loc) return move
def test_non_acgt(self): with TemporaryDirectory() as td: with Move(td): with TestData('non-actg-transcripts.fa', td) as transcript: output_fn = os.path.join(td, 'test') tsk = tasks.get_transcriptome_stats_task( transcript, output_fn) stat = run_task(tsk) self.assertEquals(stat, 2)
def make_move(self, move: Move): assert move.player == self._turn # Either pawn is not promoted or if promoted new_piece MUST be specified assert not move.pawn_promoted or move.new_piece with move.update_notation( self ): # update the notation (with context before and after move) # Make the move. self._board.make_move(move) self._moves_.push(move) self._turn = self._turn.enemy
def test_move_equal_operator(move): assert move == Move(Square(1, 1), value=1) assert not move == Move(Square(1, 1), value=0) assert not move == Move(Square(1, 1), value=2) assert not move == Move(Square(0, 1), value=1) assert not move == Move(Square(0, 0), value=1) assert not move == Move(Square(0, 0), value=0)
def move_hero(self, direction): m = Move(self.hero) tmp = m.move(self.dungeon_map, self.x, self.y, direction) if m.cleared: self.cleared = True return if tmp: self.x = tmp[0] self.y = tmp[1] self.print_map() else: if not self.hero.is_alive(): des = input("Do you want to respawn? (y/n) ") if des == "y": self.hero.health = self.hero.max_health self.hero.mana = self.hero.max_mana self.spawn(self.hero) self.print_map() elif des == "n": return dir = input("You can\'t move that way! Pick another direction! ") self.move_hero(dir)
def test_hmmpress_task(self): with TemporaryDirectory() as td: with Move(td): with TestData('test-profile.hmm', td) as tf: task = tasks.get_hmmpress_task(tf, self.hmmpress_cfg) run_tasks([task], ['run']) status = check_status(task) print(os.listdir(td), file=sys.stderr) for ext in self.extensions: self.assertTrue(os.path.isfile(tf + ext)) self.assertEquals(status.status, 'up-to-date')
def choose_resources_to_discard(self, board, deck): discard = total_resources // 2 while True: print("Choose " + str(discard) + " cards to discard.") cards = () for i in range(discard): card = input("Card " + str(i + 1) + " (Input form: l, o, w, b, g)? ") cards = cards + tuple(card) move = Move(Move.DISCARD_HALF, resource=cards) if self.check_legal_move(move, board, deck): return move else: print("Invalid move! Try again.")
def generate(self): prevBoard = self.board.clone() words = self.board.removeDuplicates(self.gacc(self.rack, len(self.rack))) places = self.board.getPlaces(self.board.board) neighbors = [] if places == []: for i in range(1, 15): places.append((i, 8)) places.append((8, i)) for place in places: r, c = place neighbors.append((r+1,c)) neighbors.append((r-1,c)) neighbors.append((r,c+1)) neighbors.append((r,c-1)) neighbors = self.board.removeDuplicates(neighbors) for word in words: for neighbor in neighbors: rIndex, cIndex = neighbor for direc in ['A', 'D']: newBoard = self.board.clone() if self.playWord(word, rIndex, cIndex, direc, newBoard): play = Move(word, newBoard, rIndex, cIndex, direc, prevBoard, self.rack) yield play continue newBoard = self.board.clone() if self.playWordOpp(word, rIndex, cIndex, direc, newBoard): play = Move(word, newBoard, rIndex, cIndex, direc, prevBoard, self.rack, revWordWhenScoring=False) yield play words = self.board.removeDuplicates(self.gac(self.rack, 7)) for (d, row) in enumerate(self.board.board[1:]): yield from self.complete(self.slotify(row[1:]), 'A', d+1, words) for (d, col) in enumerate([[row[i] for row in self.board.board[1:]] for i in range(len(self.board.board))]): yield from self.complete(self.slotify(col), 'D', d, words)
def test_cmpress_task_existing(self): with TemporaryDirectory() as td: with Move(td): with TestData('test-covariance-model.cm', td) as tf: for ext in self.extensions: touch(tf + ext) task = tasks.get_cmpress_task(tf, self.cmpress_cfg) run_tasks([task], ['run']) print(os.listdir(td), file=sys.stderr) print(task, file=sys.stderr) status = check_status(task) self.assertEquals(status.status, 'up-to-date')
def en_passant(self): x, y = self.square if self.board.last_move: last_move = self.board.last_move enemy_piece, from_square, to_square = last_move.piece, last_move.old_square, last_move.new_square if isinstance(enemy_piece, Pawn) and \ ((enemy_piece.player == Player.WHITE and from_square.y == 6 and to_square.y == 4) or (enemy_piece.player == Player.BLACK and from_square.y == 1 and to_square.y == 3)) \ and y == to_square.y and abs(to_square.x - x) == 1: # checking the condition for en-passant en_passant_square = Square( to_square.x, y - 1 if self.player == Player.WHITE else y + 1) return Move.en_passant(self.board, self, en_passant_square, enemy_piece)
def find_possible_road_spots(self, board): possible_roads = [] # Find the settlement with no roads coming from it correct_source = None for element in self.settlements: if element not in self.roads: correct_source = element assert (correct_source != None) possible_sinks = board.coords[correct_source].available_roads for sink in possible_sinks: possible_roads.append( Move(Move.BUY_ROAD, road=frozenset([correct_source, sink]))) return possible_roads