def test_score_fail2(self):
        # Tests failing score due to invalid type
        player = PlayerEntity('iBot', Color.WHITE)

        with self.assertRaises(TypeError):
            player.score = 'whaa'
Ejemplo n.º 2
0
def initialize_state(json_obj: dict) -> State:
    """
    Initializes a State object from the given json representation of a state.

    :param json_obj: json object (dictionary) containing player list and board
    :return: the state described by the json obj as a State object
    """
    if not isinstance(json_obj, dict):
        raise TypeError('Expected dict for json_obj!')

    if 'players' not in json_obj.keys():
        raise ValueError('Expected players in object!')

    if 'board' not in json_obj.keys():
        raise ValueError('Expected board in object!')

    # Retrieve player list
    player_list = json_obj['players']
    board_json = json_obj['board']

    # Get board from json
    board = initialize_board(board_json)

    # Initialize empty collection to hold players
    players = []

    # Initialize collection to hold player ids and their
    # avatar placements
    player_placements = {}

    # Cycle over each json object in the json list
    for player in player_list:
        # Make up Player object
        new_player = PlayerEntity("", _str_to_color(player['color']))

        # Update player score to whatever the current score is in the state
        new_player.score = player['score']

        # Add player object to players list
        players.append(new_player)

        # Insert placement
        player_placements.update(
            {_str_to_color(player['color']): player['places']})

    # Make up state with board and players
    state = State(board, players)

    # Determine the maximum number of avatars for a single player
    avatars_per_player_no = max(
        map(lambda x: len(x), player_placements.values()))

    # For each i in the number of avatars per player
    for i in range(avatars_per_player_no):
        # For each player, place i-th avatar if possible
        for p_color, p_placements in player_placements.items():
            # Retrieve current player's i-th avatar
            try:
                placement = player_placements[p_color][i]

                # Convert to Position object
                position_to_place = Position(placement[0], placement[1])

                # Place current player's avatar at position
                state.place_avatar(p_color, position_to_place)
            except IndexError:
                continue

    return state