def test_player_service_create(): # creating expected values now = datetime(2020, 1, 1, 1, 1, 1) random_id = "abcdefgh" expected_player = Player(id=random_id, name="johnny", created_at=now, last_seen=now) # mocking repository mock_player_repository = MagicMock(spec=PlayerRepository) mock_player_repository.save.return_value = expected_player # mocking datetime mock_datetime = MagicMock(spec=datetime) mock_datetime.now.return_value = now # mocking id generator mock_id_generator = MagicMock(return_value=random_id) # injecting mocks into service player_service = PlayerService(mock_player_repository) player_service.datetime = mock_datetime player_service.id_generator = mock_id_generator # calling service new_player = Player(id=None, name="johnny") player = player_service.create(new_player) assert player.id == random_id assert player.name == "johnny" assert player.created_at == now assert player.last_seen == now mock_player_repository.save.assert_called_with(new_player)
def test_name_setter_and_getter(set_up_player, change_player): name, color = set_up_player player = Player(name, color) assert player.name == name new_name, new_color = change_player player.name = new_name assert player.name == new_name
def moves_generate(self): # From state, determine possible moves if not self.state[self.deckCardCount]: self.terminal_reward = 0 self.is_terminal = True return p = self._player() hand = p[Player.handIndex] plays = Player.play_options(hand, p[Player.boardIndex]) pulls = Player.pull_options(self.state[self.discardIndex]) for c in hand: self.moves_discard_deal.append((c, 'd')) for pull in pulls: self.moves_discard_pull.append((c, pull)) for play in plays: self.moves_play_deal.append((play, 'd')) for pull in pulls: self.moves_play_pull.append((play, pull)) self.untried_move_count = len(self.moves_discard_deal) +\ len(self.moves_discard_pull) +\ len(self.moves_play_deal) +\ len(self.moves_play_pull)
def test_color_setter_and_getter(set_up_player, change_player): name, color = set_up_player player = Player(name, color) assert player.color == color new_name, new_color = change_player player.color = new_color assert player.color == new_color
def set_up_tree_nests_fixed(): """Sets up nests at fixed position. Use this if you do not want two nests to be created at one position.""" tree = KdTreeAndDict() positions = [array([5, 5]), array([-5, -5]), array([1000, 1000])] players = [Player("franz", (0, 0, 0)), Player("calvin", (178, 58, 238)), Player("hobbes", (122, 86, 201))] tree.create_nests(players, positions, size=1, health=100) return tree, positions
def __init__(self, num_deck): """ Represents a simple model for a blackjack game between a single player and a dealer. :param num_deck: the number of decks used for the game """ player_starting_amt = int(input("How much do you want to start with:\n")) Utils.require_non_negative(num_deck) Utils.require_non_negative(player_starting_amt) self.dealer = Dealer() self.player = Player(player_starting_amt) self.deck = Deck(num_deck) self.is_player_turn = True # True if the players turn. False if the dealers turn
def test_data_storage(set_up_player): name, color = set_up_player player = Player(name, color) player.store_data() player2 = Player(name, color) player2.read_data(filename=str(name) + ".p") assert player.__dict__ == player2.__dict__
def load_data(self, file): types = dict() types['NO'] = None types['FI'] = None types['PL'] = Player, None types['BL'] = SlideBox, Direction.Blocked types['HO'] = SlideBox, Direction.Horizontal types['VE'] = SlideBox, Direction.Vertical types['BO'] = SlideBox, Direction.Both with open(file, 'r') as f: y = 0 for line in f: l = line.split(sep=' ') for x, elem in enumerate(l): elem = elem.rstrip('\r\n') typed_elem = None if types[elem] is None: self.box_matrix[y][x] = None if elem == 'FI': self.finish = (x, y) if type(types[elem]) is tuple: type_of_elem = types[elem][0] if type_of_elem is SlideBox: typed_elem = SlideBox(x, y, types[elem][1]) if type_of_elem is Player: typed_elem = Player(x, y) self.player = type_of_elem self.player.x = x self.player.y = y if typed_elem is None: raise ValueError self.add_unit(typed_elem) y += 1
def get_by_id(self, player_id): logging.debug("Fetching player with id %s from the database", player_id) row = self.database.execute("SELECT * FROM player WHERE id = ?", (player_id, )).fetchone() if row is not None: return Player(row[0], row[1], row[2], row[3]) return None
def set_up_foods(): player = Player("Nobody", (178, 58, 238)) position = array([5., 5.]) intensity = 20. pheromone1 = Pheromone(position, player, intensity) position = array([4., 5.]) intensity = 10. pheromone2 = Pheromone(position, player, intensity) pheromones = [pheromone1, pheromone2] return pheromones
def __init__(self, players: int, random=True) -> None: if not isinstance(players, int): raise ValueError('Invalid game: players must be integer') if not 2 <= players <= 15: raise ValueError('Invalid game: must be between 2 and 15 players') self.deck = create_deck(random=random) self.players = [Player(self.__deal_hand(), n) for n in range(players)] self.__player_cycle = ReversibleCycle(self.players) self.__current_player = next(self.__player_cycle) self.__winner = None self.__check_first_card()
def __init__(self): self.player = Player() self.view = View(1300, 800) self.view.change_view_state(View.STARTVIEW) self.game_state = None self.event_list_start_view = { 'start_button': self.start_button_pressed, 'quit_game': self.quit_button_pressed } self.event_list_game_view = { 'build_scout': self.create_ant, 'quit_game': self.quit_button_pressed } self.game_loop()
def validateCase(self, hand, board, options): os = Player.play_options(hand, board) self.assertEqual(len(options), len(os)) for o in os: self.assertIn(o, options)
def test_color_setter(): player = Player(name, color) new_color = "rosa" player.color = new_color assert player.color == new_color
def set_up_environment(): player = Player(name="Nobody", color=(178, 58, 238)) nest = Nest(position=array([0., 0.]), player=player, size=10., health=100.) ant = Worker(player=player, home_nest=nest, speed=1) return player, nest, ant
def setUp(self): self.test_player_one = Player(1000) self.test_player_two = Player(0) self.test_card_one = Card(3, "spades") self.test_card_two = Card("ace", "diamonds") self.test_card_three = Card(4, "hearts")
class TestPlayer(TestCase): def setUp(self): self.test_player_one = Player(1000) self.test_player_two = Player(0) self.test_card_one = Card(3, "spades") self.test_card_two = Card("ace", "diamonds") self.test_card_three = Card(4, "hearts") def test_invalid_player(self): with self.assertRaises(ValueError): Player(-1) def test_make_bet(self): self.assertEqual(self.test_player_one.bet, 0) self.test_player_one.make_bet(200) self.assertEqual(self.test_player_one.bet, 200) self.assertEqual(self.test_player_one.balance, 800) def test_make_bet_error(self): with self.assertRaises(ValueError): self.test_player_one.make_bet(2000) with self.assertRaises(ValueError): self.test_player_two.make_bet(1) def test_add_card_basic(self): self.assertEqual(len(self.test_player_one.hand), 0) self.test_player_one.add_card(self.test_card_one) self.assertEqual(len(self.test_player_one.hand), 1) self.assertEqual(self.test_player_one.hand[0].describe(), "The 3 of spades.") def test_add_card_complex(self): self.assertEqual(len(self.test_player_one.hand), 0) self.test_player_one.add_card(self.test_card_one) self.test_player_one.add_card(self.test_card_two) self.assertEqual(self.test_player_one.hand[0].describe(), "The 3 of spades.") self.assertEqual(self.test_player_one.hand[1].describe(), "The ace of diamonds.") self.test_player_one.add_card(self.test_card_three) self.assertEqual(self.test_player_one.hand[2].describe(), "The 4 of hearts.") def test_clear_hand(self): self.test_add_card_complex() self.assertEqual(len(self.test_player_one.hand), 3) self.test_player_one.clear_hand() self.assertEqual(len(self.test_player_one.hand), 0)
def nest_creation_fixed(): position = array([0.5, 0.5]) player = Player(name="Nobody", color=(178, 58, 238)) size = 5 health = 10 return (position, player, size, health)
def test_name_setter(): player = Player(name, color) new_name = "herbert" player.name = new_name assert player.name == new_name
def test_model_creation(): player = Player(name, color) assert player.name == name and player.color == color
def test_init__(set_up_player): name, color = set_up_player player = Player(name, color) assert player.name == name and player.color == color
def run_mcts(n, modelState=None, userInput=False, verbose=True): model = None if modelState: model = Expedition.make_from_state(modelState, False) else: model = Expedition() model.setup() now = time.clock() move_stats = { 'play_card': 0, 'play_discard': 0, 'pull_card': 0, 'pull_discard': 0, 'evaluation': [] } while model.cardsInDeckCount: node = UCT(ExpeditionNode(model.state()), n) if verbose: print('___________________________________________') print('Turn:', int(model.turnPly / 2), 'State:', model) print(Back.WHITE + Fore.RED, 'Selected Move:', end='') print(Style.RESET_ALL, end='') print(ExpeditionNode.move_display(node.move), Style.RESET_ALL, flush=True) if verbose: node.parent.children_display() model.play_move(node.move) record_move_stats(move_stats, node.move, node.reward / node.visits) if model.cardsInDeckCount: if userInput: print(model) p = model.player() o = Player.play_options(p[Player.handIndex], p[Player.boardIndex]) for a in sorted(p[Player.handIndex], key=lambda c: (c[0], c[1])): print('(' + str(a[0]) + ',' + str('X' if a[1] < 3 else a[1] - 1), end=') ') print() for i, a in enumerate(o): print(str(i) + '/' + str(8 + i) + ':' '(' + str(a[0]) + ',' + str('X' if a[1] < 3 else a[1] - 1), end=') ') print() a = int(input()) action = 'discard' if a < 8 else 'play' play = p[Player.handIndex][a] if a < 8 else o[a - 8] print(model.discard) a = input() a = 0 if a == '' else int(a) pull = 'd' if a == 0 else a print('>>', (action, (play, pull))) model.play_move((action, (play, pull))) else: move = model.play_random_turn() if verbose: print('\r\n' + Back.RED + Fore.WHITE + 'Opponent\'s move:', ExpeditionNode.move_display(move), Style.RESET_ALL, flush=True) print(model.winner, Player.board_score(model.players[0][Player.boardStateIndex]), Player.board_score(model.players[1][Player.boardStateIndex])) print(move_stats) print(time.clock() - now, flush=True) return model.winner
def get_all(self): logging.debug("Fetching all players from the database") rows = self.database.execute("SELECT * FROM player").fetchall() # convert rows to Player objects return [Player(row[0], row[1], row[2], row[3]) for row in rows]
def create(): player_service = PlayerService() data = request.json logging.debug("Creating player: %s", data) player = player_service.create(Player(id=None, name=data['name'])) return jsonify(player.__dict__)
def test_name_getter(): player = Player(name, color) assert player.name == name
def test_color_getter(): player = Player(name, color) assert player.color == color
def validateCase(self, board, score): s = Player.board_score(board) self.assertEqual(s, score)
def test_invalid_player(self): with self.assertRaises(ValueError): Player(-1)