def from_json_state(json_state): """ Takes in a json 'state' of a Player, converting it into a new PlayerState object :param json_state: JSON List - [Natural, [Species+, ..., Species+], Cards] :return: PlayerState - the new PlayerState object created from the json representation """ food_bag = json_state[0] species_list = [Species.convertSpecies(species) for species in json_state[1]] trait_cards = [TraitCard.from_json(trait) for trait in json_state[2]] return PlayerState(bag=food_bag, speciesList=species_list, trait_cards=trait_cards)
def testFromJson(self): json_trait1 = [3, CARNIVORE] trait1 = TraitCard(CARNIVORE, 3) self.assertEquals(TraitCard.from_json(json_trait1), trait1) with self.assertRaises(Exception): TraitCard.from_json([CARNIVORE, 3]) with self.assertRaises(Exception): TraitCard.from_json([3, CARNIVORE, 2]) with self.assertRaises(Exception): TraitCard.from_json([3, "nonsense"])
def get_hand(json_trait_cards): """ Parse a json trait hand into a list of TraitCards :param json_trait_cards: JSON list of [traitValue, traitName] :return: listOf(TraitCard) - The Dealer's hand from configuration """ list_of_species_cards = [] found_traits = {} for trait_card in json_trait_cards: if len(trait_card) == 2: list_of_species_cards.append(TraitCard.from_json(trait_card)) if trait_card[1] in found_traits: found_traits[trait_card[1]] += 1 else: found_traits[trait_card[1]] = 1 Dealer.validate_hand(found_traits) return list_of_species_cards
def convertPlayerState(state): """ Creates a PlayerState from from the given JSON representation :param state: JSON list - represents the playerState :return: PlayerState - with attributes contained in 'state' """ playerTraitCards = [] if state[0][0] == ID_LABEL and state[1][0] == SPECIES_LABEL and state[2][0] == BAG_LABEL: id = state[0][1] speciesList = [Species.convertSpecies(species) for species in state[1][1]] bag = state[2][1] if len(state) == 4 and state[3][0] == CARDS_LABEL: playerTraitCards = [TraitCard.from_json(card) for card in state[3][1]] if id < 1 or bag < 0: raise Exception("Bad JSON PlayerState Data") return PlayerState(id, bag, speciesList, playerTraitCards) else: raise Exception("Bad JSON PlayerState input")