def feed_carnivore(cls, hungry_carnivores, player_state, list_of_player): """ Feeds the largest hungry carnivore :param hungry_carnivores: list of hungry carnivores :param player_state: the current player state :param list_of_player: list of all player states :return: """ sorted_carnivores = Species.sort_lex(hungry_carnivores) for carnivore in sorted_carnivores: targets = [] for player in list_of_player: if player == player_state: continue for i in range(0, len(player.species)): defender = player.species[i] left_neighbor = (False if i == 0 else player.species[i - 1]) right_neighbor = (False if i == len(player.species) - 1 else player.species[i + 1]) if defender.is_attackable(carnivore, left_neighbor, right_neighbor): targets.append(defender) if targets: sorted_targets = Species.sort_lex(targets) target = sorted_targets[0] target_player = next(player for player in list_of_player if target in player.species) return [carnivore, target_player, target] return False
def sense(self, animal_base): surrounding_res = Surroundings() for spec in self.animals.keys(): for animal2 in self.animals[spec]: animal2_dist = self.distanceToAgent(animal_base, animal2) if (animal2_dist < animal_base.genes.sense): if Species.predator( animal_base._species) == animal2._species: surrounding_res.closest_predator = animal2 surrounding_res.closest_predator_dist = animal2_dist elif Species.prey( animal_base._species) == animal2._species: surrounding_res.closest_prey = animal2 surrounding_res.closest_prey_dist = animal2_dist for spec in self.plants.keys(): for plant in self.plants[spec]: plant_dist = self.distanceToAgent(animal_base, plant) if (plant_dist < animal_base.genes.sense): if (surrounding_res.closest_plant is None or plant_dist < surrounding_res.closest_plant_dist): surrounding_res.closest_plant = plant surrounding_res.closest_plant_dist = plant_dist return surrounding_res
def feed_carnivore(cls, hungry_carnivores, player_state, list_of_player): """ Feeds the largest hungry carnivore :param hungry_carnivores: list of hungry carnivores :param player_state: the current player state :param list_of_player: list of all player states :return: """ sorted_carnivores = Species.sort_lex(hungry_carnivores) for carnivore in sorted_carnivores: targets = [] for player in list_of_player: if player == player_state: continue for i in range(0, len(player.species)): defender = player.species[i] left_neighbor = (False if i == 0 else player.species[i - 1]) right_neighbor = (False if i == len(player.species) - 1 else player.species[i + 1]) if defender.is_attackable(carnivore, left_neighbor, right_neighbor): targets.append(defender) if targets: sorted_targets = Species.sort_lex(targets) target = sorted_targets[0] target_player = next(player for player in list_of_player if target in player.species) return [carnivore, target_player, target] else: return False
def test_can_eat(self): self.assertFalse(self.species_1.can_eat()) self.assertTrue(self.species_4.can_eat()) fat_tissue = Species(4, 3, 4, [TraitCard("fat-tissue")], 3) self.assertTrue(fat_tissue.can_eat()) fat_tissue.fat_storage = 4 self.assertFalse(fat_tissue.can_eat())
def setUp(self): self.t1 = TraitCard("horns", 3) self.t2 = TraitCard("ambush", 1) self.t3 = TraitCard("carnivore", 2) self.t4 = TraitCard("fat-tissue", 0) self.t5 = TraitCard("foraging", 3) self.t6 = TraitCard("herding", 0) self.defSpec = Species(0, 0, 1, [], 0) self.specWGrownBody = Species(0, 1, 1, [], 0) self.specW3t = Species(0, 0, 1, [self.t3, self.t4, self.t5], 0) self.specWAll = Species(0, 1, 2, [self.t4], 0) self.playerWithManyCards = PlayerState( 1, 0, [], [self.t1, self.t2, self.t3, self.t4, self.t5, self.t6]) self.playerForAll = PlayerState(1, 0, [self.specWAll], []) self.playerFor3t = PlayerState(1, 0, [self.specW3t], [self.t6]) self.playerForDefSpec = PlayerState(1, 0, [self.defSpec], [self.t5, self.t6]) self.playerForBodyNewspec = PlayerState( 1, 0, [self.specWGrownBody], [self.t3, self.t4, self.t5, self.t6]) self.noAct = Action4(0, [], [], [], []) self.actGP = Action4(0, [GainPopulation(0, 1)], [], [], []) self.actGB = Action4(0, [], [GainBodySize(0, 1)], [], []) self.actRT = Action4(0, [], [], [ReplaceTrait(0, 1, 1)], []) self.actBT0t = Action4(0, [], [], [], [BuySpeciesBoard(1, [])]) self.actBT1t = Action4(0, [], [], [], [BuySpeciesBoard(1, [2])]) self.actBT2t = Action4(0, [], [], [], [BuySpeciesBoard(1, [2, 3])]) self.actBT3t = Action4(0, [], [], [], [BuySpeciesBoard(1, [2, 3, 4])]) self.actBT4t = Action4(0, [], [], [], [BuySpeciesBoard(1, [2, 3, 4, 5])]) self.addBodyToNewSpec = Action4(0, [GainPopulation(1, 1)], [], [], [BuySpeciesBoard(2, [3])]) self.actAll = Action4(0, [GainPopulation(0, 1)], [GainBodySize(0, 2)], [ReplaceTrait(0, 0, 3)], [BuySpeciesBoard(4, [5])])
class TestReaction(unittest.TestCase): def setUp(self): self._limiting = Species("Limiting", 100) self._limiting.set_n(0.001) self._reactant2 = Species("Reactant #1", 200) self._reactant3 = Species("Reactant #2", 300) self._product = Species("Product", 400) def test_add_get_limiting_reactant(self): reaction = Reaction() reaction.add_limiting_reactant(self._limiting) self.assertEqual(reaction.get_limiting_reactant().n(), 0.001) def test_add_get_reactant(self): reaction = Reaction() reaction.add_limiting_reactant(self._limiting) reaction.add_reactant(self._reactant2, 2) reaction.add_reactant(self._reactant3, 3) self.assertEqual(reaction.get_non_limiting_reactants()[0].n(), 0.002) self.assertEqual(reaction.get_non_limiting_reactants()[1].n(), 0.003) def test_add_get_product(self): reaction = Reaction() reaction.add_product(self._product, 0.4) self.assertEqual(reaction.get_product().n(), 0.001) def test_get_yield(self): reaction = Reaction() reaction.add_limiting_reactant(self._limiting) reaction.add_product(self._product, 0.3) self.assertEqual(reaction.get_yield(), 75)
def test_sort_lex(self): sorted_list = [ self.species_2, self.species_1, self.species_3, self.species_4, self.species_5 ] self.assertEqual(Species.sort_lex(self.species_list), sorted_list) self.assertNotEqual(Species.sort_lex(self.species_list), self.species_list)
def initializeModels(): model = newModel() board = [0 for x in range(10)] board = [list(board) for x in range(20)] species = Species(model,[board]*2,[[1,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0]],0) assert (len(species.intake) == len(species.output)) species.create() return species
def validate_cards(self, total_deck): """ Validates that the TraitCards in this PlayerState's hand and on its Species boards are all possible and unique :param total_deck: a list of TraitCards representing all valid card possibilities :raise ValueError if duplicate or invalid cards exist on this player """ TraitCard.validate_all_unique(self.hand, total_deck) Species.validate_all_cards(self.species, total_deck)
def initialize_species(X, Y, positive_examples, negative_examples, minority_flag): # Positive Species species_a = Species(X, Y, positive_examples, negative_examples, 1, 100, minority_flag) # Negative Species species_b = Species(X, Y, negative_examples, positive_examples, 0, 100, not minority_flag) return [species_a, species_b]
def optimizer_test(self): target = np.array([5,1,2]) def objective(a,b,c): arr = np.array([a,b,c]) return np.average((arr - target)**2)**0.5 genome = {'a':range(10), 'b':range(10), 'c':range(1)} genome = Genome(genome) spec = Species(genome, objective=objective) spec.evaluate() spec.evolve()
def test_largest_fatty_need(self): self.species_1.traits = [TraitCard("fat-tissue")] self.species_2.traits = [TraitCard("fat-tissue")] self.species_4.traits = [TraitCard("fat-tissue")] self.assertEqual( Species.largest_fatty_need([self.species_1, self.species_4]), self.species_4) self.assertEqual( Species.largest_fatty_need([self.species_1, self.species_2]), self.species_1)
def validate_attributes(self): """ Validates the attributes of this PlayerState :raise AssertionError if any attributes are out of bounds """ assert(isinstance(self.name, int) and self.name >= MIN_PLAYER_ID) assert(isinstance(self.food_bag, int) and self.food_bag >= MIN_FOOD_BAG) assert(isinstance(self.hand, list)) TraitCard.validate_all_attributes(self.hand) assert(isinstance(self.species, list)) Species.validate_all_attributes(self.species)
def situationFromJson(situation): defend = JsonParsing.speciesFromJson(situation[0]) attack = JsonParsing.speciesFromJson(situation[1]) if not attack or not defend: quit() lNeighbor = JsonParsing.speciesFromJson(situation[2]) or Species(0, 0, 0, [], 0) rNeighbor = JsonParsing.speciesFromJson(situation[3]) or Species(0, 0, 0, [], 0) return defend, attack, lNeighbor, rNeighbor
def parse_choice(choice): """ Parse a choice into a [PlayerState, listOf(Species), listOf(Species] :param choice: json list representing [playerstate, listof species, listof species] :return: [PlayerState, listOf(Species), listOf(Species)] """ ps = PlayerState.convertPlayerState(choice[0]) prev_species = [Species.convertSpecies(species) for species in [prev for prev in choice[1]]] later_species = [Species.convertSpecies(species) for species in [late for late in choice[2]]] return [ps, prev_species, later_species]
def organism_test(self): genome = Genome({ 'A':range(10), 'B':'abcdefg', 'C':np.linspace(0, 1, 100)}) species = Species(genome) org1 = species.spawn_organism() org2 = species.spawn_organism() org3 = org1.mate(org2) org3.mutate()
def json_to_species(cls, json_species): assert(cls.validate_species_json(json_species)) species_food = json_species[0][1] species_body = json_species[1][1] species_pop = json_species[2][1] species_traits = [] for trait in json_species[3][1]: species_traits.append(cls.json_to_trait(trait)) species_obj = Species(species_pop, species_food, species_body, species_traits) if len(json_species) == 5: species_obj.fat_storage = json_species[4][1] return species_obj
def setUp(self): self.attacker = Species() self.attacker.traits = [TraitCard("carnivore")] self.defender = Species() self.left_neighbor = Species() self.right_neighbor = Species() self.species_1 = Species(4, 4, 4) self.species_2 = Species(4, 4, 4) self.species_3 = Species(4, 4, 3) self.species_4 = Species(4, 3, 3) self.species_5 = Species(3, 3, 3) self.species_list = [self.species_2, self.species_4, self.species_3, self.species_5, self.species_1]
def readXYZ(xyz, bonds=None, cluster_bond=None, fixed_atoms=None): # extract molecule information from xyz mol = next(pb.readfile('xyz', xyz)) reactant_atom = [a.OBAtom.GetAtomicNum() for a in mol] # Manually give bond information # (Because in metal system the bond information detect by openbabel usually have some problem) if bonds or cluster_bond: m = Molecule(pb.ob.OBMol()) obmol = m.OBMol obmol.BeginModify() for atom in mol: coords = [coord for coord in atom.coords] atomno = atom.atomicnum obatom = ob.OBAtom() obatom.thisown = 0 obatom.SetAtomicNum(atomno) obatom.SetVector(*coords) obmol.AddAtom(obatom) del obatom if cluster_bond: bonds = [(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx(), bond.GetBondOrder()) for bond in pb.ob.OBMolBondIter(mol.OBMol)] #bonds = imaginary_bond(bonds, reactant_atom, fixed_atoms) bonds.extend(cluster_bond) for bond in bonds: obmol.AddBond(bond[0], bond[1], bond[2]) # obmol.ConnectTheDots() obmol.PerceiveBondOrders() # obmol.SetTotalSpinMultiplicity(1) obmol.SetTotalCharge(int(mol.charge)) obmol.Center() obmol.EndModify() mol_obj = gen3D.Molecule(obmol) reactant_graph = Species(xyz_file_to_atoms(xyz)) reactant_bonds = [(i[0] - 1, i[1] - 1) for i in bonds] make_graph(reactant_graph, bond_list=reactant_bonds) else: mol_obj = gen3D.Molecule(mol.OBMol) reactant_graph = Species(xyz_file_to_atoms(xyz)) reactant_bonds = tuple( sorted([(bond.GetBeginAtomIdx() - 1, bond.GetEndAtomIdx() - 1) for bond in pb.ob.OBMolBondIter(mol.OBMol)])) make_graph(reactant_graph, bond_list=reactant_bonds) return mol_obj, reactant_graph
def parse_cj_dj(json_cj_dj): """ Parse a json cj_dj into a [listOf(listOf(Species)), listOf(listOf(Species))] :param json_cj_dj: json list representing [listof species, listof species] - First list of species is each specieslist of all players acting before this player - Second list of species is each specieslist of all players who's turns come after this player :return: (listOf(Species), listOf(Species)) """ prev_species, later_species = [], [] for prev in json_cj_dj[0]: prev_species.append([Species.convertSpecies(species) for species in prev]) for later in json_cj_dj[1]: later_species.append([Species.convertSpecies(species) for species in later]) return prev_species, later_species
def setUp(self): self.species1 = Species(0, 1, 3, []) self.carni2 = Species(0, 2, 3, [Trait.carnivore]) self.herbavore = Species(0, 1, 1, []) self.herbavore2 = Species(0, 1, 1, []) self.herbavore3 = Species(1, 1, 1, []) self.herbavore4 = Species(2, 1, 2, []) self.fat_tissue = Species(0, 1, 1, []) self.fat_tissue.setTraits([Trait.fat_tissue]) self.fat_tissue2 = Species(0, 3, 1, []) self.fat_tissue2.setTraits([Trait.fat_tissue]) self.opherb = Species(0, 1, 1, []) self.opfatherb = Species(0, 7, 1, []) self.fertileCard = TraitCard(Trait.fertile, 2) self.climbingCard = TraitCard(Trait.climbing, 0) self.cooperationCard = TraitCard(Trait.cooperation, 0) self.carnivoreCard = TraitCard(Trait.carnivore, 0) self.longNeckCard = TraitCard(Trait.long_neck, 0) self.ambushCard = TraitCard(Trait.ambush, 0) self.burrowingCard = TraitCard(Trait.burrowing, 0) self.cooperation2Card = TraitCard(Trait.cooperation, -1) self.player1 = Player(1, [], 0) self.player2 = Player(2, [], 0) self.player3 = Player(3, [], 0) self.validAction1 = [2, [[2, 6]], [[2, 3]], [[5, 4]], [[2, 0, 0]]] self.validAction2 = [2, [[2, 0]], [[2, 1]], [[4, 3]], []] self.validAction3 = [2, [[2, 1]], [], [[3, 0]], []] self.validAction4 = [2, [], [], [[0, 1]], []] self.validAction5 = [0, [], [], [], []] self.invalidAction1 = ["hi", 1, [], "so", False] self.invalidAction2 = ["hi", 1, []] self.invalidAction3 = [False, [["2", 6]], [[2, 3]], [[5, 4]], [[2, 0, 0]]] self.validFeeding1 = False self.validFeeding2 = 1 self.validFeeding3 = [1, 9] self.validFeeding4 = [0, 0, 1] self.invalidFeeding1 = True self.invalidFeeding2 = [1, 2, 3, 3, ""] self.invalidFeeding3 = ["p", "i", "e"]
def breed_new_generation(self): self.calculate_genome_adjusted_fitness() self.remove_weak_genomes_from_species() self.remove_stale_species() survived_species: List[Species] = [] children: List[Genome] = [] total_adjusted_fitness: float = self.calculate_total_adjusted_fitness() carry_over: float = 0 for species in self.species: fchild: float = self.population * ( species.get_total_adjusted_fitness() / total_adjusted_fitness) nchild: int = int(fchild) carry_over += fchild - nchild if carry_over >= 1: carry_over -= 1 nchild += 1 if nchild < 1: continue new_species: Species = Species(species.get_top_genome()) new_species.previous_top_fitness = species.previous_top_fitness new_species.staleness = species.staleness survived_species.append(new_species) for _ in range(1, nchild): children.append(species.breed_child()) self.species: List[Species] = survived_species for child in children: self.add_to_species(child)
def speciate(self): for spec in self.population: spec.entities = [] for entity in self.population: suitable_species = False for spec in self.species: if Species.are_compatible(spec.standard, entity.brain): spec.add(entity) suitable_species = True break if not suitable_species: self.species.append(Species(entity, self.spec_innov)) self.spec_innov += 1
def show_changes(self, other_player): """ Creates a string representation of the changed attributes between a PlayerState before and after an imperative function is called on it. :param other_player: The PlayerState after it has been modified :return: String of attribute changes, or "" if unchanged. """ changes = [] if self.name != other_player.name: changes.append(CHANGE_TEMPLATE % ("name", str(self.name), str(other_player.name))) if self.food_bag != other_player.food_bag: changes.append( CHANGE_TEMPLATE % ("food_bag", str(self.food_bag), str(other_player.food_bag))) hand_changes = TraitCard.show_all_changes(self.hand, other_player.hand) if hand_changes: changes.append(hand_changes) species_changes = Species.show_all_changes(self.species, other_player.species) if species_changes: changes.append(species_changes) if self.active != other_player.active: changes.append(CHANGE_TEMPLATE % ("active", self.active, other_player.active)) return ", ".join(changes)
def __init__(self, db_name): """db_name: and Emsembl database name""" if isinstance(db_name, EnsemblDbName): db_name = db_name.Name self.Name = db_name self.Type = get_dbtype_from_name(db_name) self.Prefix = get_db_prefix(db_name) release, build = get_version_from_name(db_name) self.Release = release self.GeneralRelease = self.Release if len(build) == 1: if self.Type != 'compara': self.Build = build[0] else: self.Build = None self.GeneralRelease = build[0] elif build: self.Build = build[1] self.GeneralRelease = build[0] else: self.Build = None self.Species = None self.Species = Species.getSpeciesName(self.Prefix)
def getSpecies(self): self.category = 'species' self.callServiceThread() self.species = Species(self.result_d['name'], self.result_d['classification']) print("Name: {} Classification: {}".format( self.species.name, self.species.classification))
def reproduction(self, fitness_array): def check_species(g): for s in self.species: if s.check_if_member(g): return True return False for i, g in enumerate(self.genoms): g.fitness = fitness_array[i] if not check_species(g): self.species.append(Species(g)) n_extint = 0 new_species = [] for s in self.species: s.sort() extinct = s.kill() if extinct: n_extint += 1 else: new_species.append(s.reproduce()) self.species = new_species n_extra = self.clients - len(self.genoms) for i in range(n_extra): random.choice(self.genoms).reproduce_extra()
def feed_herbivores(cls, hungry_herbivores): """ Feeds a herbivore species :param hungry_herbivores: list of hungry herbivores :return: the Species to feed """ return Species.sort_lex(hungry_herbivores)[0]
def __init__(self): self.species_list = [Species("Blob")] self.biome_list = [] #todo: make a graph self.id_to_player = {} #placeholder, set up empty player self.add_player(Player("placeholder"))
def getSpecies(self): self.category = 'species' result_d = json.loads( SwapiService.getSwapi(self.category, self.getId())) self.species = Species(result_d['name'], result_d['classification']) print("Name: {} Classification: {}".format( self.species.name, self.species.classification))
def speciesFromJson(jsonSpecies): # If the if statement errors out, the input is ill shaped try: if jsonSpecies is False: return False if jsonSpecies[0][0] == "food" and jsonSpecies[1][0] == "body" and jsonSpecies[2][0] == "population" and jsonSpecies[3][0] == "traits": food = jsonSpecies[0][1] body = jsonSpecies[1][1] population = jsonSpecies[2][1] traits = [] hasFatTissue = False for trait in jsonSpecies[3][1] : if JsonParsing.checkTrait(trait): traits.append(trait) if trait == "fat-tissue": hasFatTissue = True if len(jsonSpecies) == 5 and hasFatTissue and jsonSpecies[4][0] == "fat-food": fatFood = jsonSpecies[4][1] else: fatFood = 0 return Species(food, body, population, traits, fatFood) else: pass # TODO: what should actually happen when the labels for an array are wrong? except Exception as e: raise e
def setUp(self): self.player1 = Player(1, [], 0, info = "j") self.player2 = Player(2, [], 0, info = "j") self.player3 = Player(3, [], 0, info = "j") self.player4 = Player(4, [], 0, info = "j") self.player5 = Player(5, [], 0, info = "j") self.player6 = Player(6, [], 0, info = "j") self.player7 = Player(7, [], 0, info = "j") self.player8 = Player(8, [], 0, info = "j") self.players = [self.player1, self.player2, self.player3] self.players8 = [self.player1, self.player2, self.player3, self.player4, self.player5, self.player6, self.player7, self.player8] self.species1 = Species(0, 3, 3, []) self.species2 = Species(0, 2, 1, []) self.speciesscavenger = Species(0, 3, 3, [Trait.scavenger]) self.speciesforaging = Species(0, 3, 3, [Trait.foraging]) self.speciescoop = Species(0, 3, 3, [Trait.cooperation]) self.speciesfull = Species(2, 2, 2, []) self.speciesfull1 = Species(3, 2, 3, []) self.speciesfull2 = Species(4, 2, 4, []) self.speciesfat= Species(0, 3, 3, [Trait.fat_tissue]) self.speciesfat.setFatFood(1) self.specieshorns = Species(0, 3, 3, [Trait.horns]) self.speciescarni = Species(0, 3, 3, [Trait.carnivore]) self.specieshorns1 = Species(0, 3, 1, [Trait.horns]) self.speciescarni1 = Species(0, 3, 1, [Trait.carnivore]) self.speciesLongFertile = Species(0, 3, 1, [Trait.long_neck, Trait.fertile]) self.speciesFertile = Species(0, 3, 1, [Trait.fertile]) self.speciesLongNeck = Species(0, 3, 1, [Trait.long_neck]) self.watering_hole = WateringHole(0) self.dealer = Dealer(self.watering_hole, self.players) self.warning_call_card = TraitCard(Trait.warning_call, 0) self.warning_call_card2 = TraitCard(Trait.warning_call, 1) self.climbing_card = TraitCard(Trait.climbing, 3) self.carnivore_card = TraitCard(Trait.carnivore, -8) self.fertileCard = TraitCard(Trait.fertile, 2) self.climbingCard = TraitCard(Trait.climbing, 0) self.cooperationCard = TraitCard(Trait.cooperation, 0) self.carnivoreCard = TraitCard(Trait.carnivore, 0) self.longNeckCard = TraitCard(Trait.long_neck, 0) self.fertileCard1 = TraitCard(Trait.fertile, 2) self.climbingCard1 = TraitCard(Trait.climbing, 1) self.cooperationCard1 = TraitCard(Trait.cooperation, 1) self.carnivoreCard1 = TraitCard(Trait.carnivore, 1) self.longNeckCard1 = TraitCard(Trait.long_neck, 1) self.ambushCard = TraitCard(Trait.ambush, 1) self.deck = [self.warning_call_card, self.climbing_card, self.carnivore_card] self.deck2 = deck.generateDeck()[:12] self.dealer.setDeck(self.deck) self.dealer.setWateringHole(20)
def add_species(self, add_card_list): """ :effect Adds a new species to the right of this Player State's current species :param add_card_list: List of Nat representing indicies of Trait Cards in this Player State's hand to add to the new species. """ trait_list = [self.hand[i] for i in add_card_list] self.species.append(Species(traits=trait_list))
def species(self): map = self._readmap('classes') results = [] for id in map: results.append(Species(id=int(id), name=map[id])) return sorted(results, key=lambda x: x.id)
def add_to_species(self, genome: Genome): for species in self.species: if Genome.is_same_species(species.genomes[0], genome): species.genomes.append(genome) species.previous_top_fitness = max( species.previous_top_fitness, genome.fitness) return self.species.append(Species(genome))
def setUp(self): self.carnivore = TraitCard(CARNIVORE, 3) self.burrowing = TraitCard(BURROWING, 2) self.fattissue = TraitCard(FATTISSUE, 4) self.foraging = TraitCard(FORAGING, 2) self.horns = TraitCard(HORNS, 6) self.cooperation = TraitCard(COOPERATION, 1) self.scavenger = TraitCard(SCAVENGER, 2) self.species_1 = Species(4, 4, 4, []) self.species_2 = Species(4, 4, 4) self.species_3 = Species(4, 4, 3) self.species_4 = Species(4, 3, 3) self.species_5 = Species(3, 1, 3) self.species_6 = Species(4, 3, 3) self.species_7 = Species(4, 4, 4) self.species_list = [ self.species_2, self.species_4, self.species_3, self.species_5, self.species_1 ] self.player_1 = PlayerState( species=[self.species_4, self.species_5, self.species_6], hand=[self.carnivore]) self.player_2 = PlayerState(species=[self.species_1], hand=[self.carnivore, self.fattissue]) self.player_3 = PlayerState( species=[self.species_2, self.species_3, self.species_7], hand=[self.foraging])
def feed_carnivore(cls, hungry_carnivores, player, opponents): """ Feeds the largest hungry carnivore :param hungry_carnivores: list of hungry carnivores :param player: the current player's state :param opponents: list of all other player's states :return: """ sorted_carnivores = Species.sort_lex(hungry_carnivores) for carnivore in sorted_carnivores: targets = Dealer.carnivore_targets(carnivore, opponents) if targets: sorted_targets = Species.sort_lex(targets) target = sorted_targets[0] target_player = next(player for player in opponents if target in player.species) return [carnivore, target_player, target] return False
def mutation_step(self): """Mutates a random node.""" # pick a random node in the graph, i.e. an integer node = random.randint(0, self.N - 1) # get the species currently living on that node species = self.State[node] # mutate the species and add it to the node in question. new_genome = species.mutated_genome() self.State[node] = Species(new_genome, self.fitness(new_genome))
def start(self, player): """ Handles the start of a turn by dealing cards and a new Species (if necessary) to the given PlayerState :param player: the PlayerState being dealt to :effect: Updates given PlayerState with additional TraitCards and possible Species """ new_cards = self.cards_to_deal(player) opt_species = (False if player.species else Species()) player.start(opt_species, new_cards)
def setUp(self): # Traits (Trait, Food-value) self.carnivore = TraitCard(CARNIVORE, 3) self.burrowing = TraitCard(BURROWING, 2) self.fattissue = TraitCard(FATTISSUE, 4) self.foraging = TraitCard(FORAGING, 2) self.horns = TraitCard(HORNS, 6) self.cooperation = TraitCard(COOPERATION, 1) self.scavenger = TraitCard(SCAVENGER, 2) # Species (Population, Food, Body, Traits, Fat-Storage) self.species1 = Species(1, 0, 2, [self.cooperation]) self.species2 = Species(6, 2, 1, [self.carnivore]) self.species3 = Species(3, 3, 3, [self.fattissue], 0) self.species4 = Species(5, 5, 5, [self.burrowing]) self.species5 = Species(5, 3, 4, [self.foraging]) self.species6 = Species( 2, 1, 7, [self.carnivore, self.fattissue, self.scavenger], 0) self.species7 = Species(7, 1, 6, [self.horns]) self.player1_species = [self.species1, self.species2] self.player2_species = [self.species3, self.species4, self.species5] self.player3_species = [self.species6, self.species7] # Players (Name, Bag, Hand, Species) self.player1 = PlayerState(1, 0, [self.fattissue], self.player1_species) self.player2 = PlayerState(2, 3, [self.fattissue, self.carnivore], self.player2_species) self.player3 = PlayerState(3, 6, [self.burrowing], self.player3_species) self.public_player1 = PlayerState(1, False, False, self.player1_species) self.public_player2 = PlayerState(2, False, False, self.player2_species) self.public_player3 = PlayerState(3, False, False, self.player3_species) self.list_of_players = [self.player1, self.player2, self.player3] # Dealer (List of Players, Watering Hole, Deck) self.dealer1 = Dealer(self.list_of_players, 10, []) # Actions self.food_card_action1 = FoodCardAction(0) self.food_card_action2 = FoodCardAction(1) self.grow_action_pop = GrowAction(POPULATION, 0, 0) self.grow_action_body = GrowAction(BODY, 1, 1) self.add_species_action1 = AddSpeciesAction(0, [1]) self.add_species_action2 = AddSpeciesAction(0, []) self.replace_trait_action1 = ReplaceTraitAction(0, 0, 0) self.replace_trait_action2 = ReplaceTraitAction(2, 0, 1) self.replace_trait_action3 = ReplaceTraitAction(0, 2, 0) # Action4 self.action4_1 = Action4(self.player1, [self.food_card_action1]) self.action4_2 = Action4( self.player2, [self.food_card_action2, self.grow_action_pop])
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 feed_fatty(cls, fat_tissue_species, food_available): """ Feeds a species with the fat-tissue trait :param fat_tissue_species: species with a fat-tissue trait :param food_available: food on the watering_hole_board :return: list of [Species, int] where Species is the fat_tissue_species and int is the requested food """ fatty = Species.largest_fatty_need(fat_tissue_species) food_requested = (fatty.body if fatty.body < food_available else food_available) return [fatty, food_requested]
def setUp(self): # Traits (Trait, Food-value) self.carnivore = TraitCard(CARNIVORE, 3) self.burrowing = TraitCard(BURROWING, 2) self.fattissue = TraitCard(FATTISSUE, 2) self.foraging = TraitCard(FORAGING, 2) self.horns = TraitCard(HORNS, 0) self.cooperation = TraitCard(COOPERATION, 1) self.scavenger = TraitCard(SCAVENGER, 2) # Species (Population, Food, Body, Traits, Fat-Storage) self.species1 = Species(1, 0, 2, [self.cooperation]) self.species2 = Species(6, 2, 1, [self.carnivore]) self.species3 = Species(3, 3, 3, [self.fattissue], 0) self.species4 = Species(5, 5, 5, [self.burrowing]) self.species5 = Species(5, 3, 4, [self.foraging]) self.species6 = Species( 2, 1, 7, [self.carnivore, self.fattissue, self.scavenger], 0) self.species7 = Species(7, 1, 6, [self.horns]) self.player1_species = [self.species1, self.species2] self.player2_species = [self.species3, self.species4, self.species5] self.player3_species = [self.species6, self.species7] # Players (Name, Bag, Hand, Species) self.player1 = PlayerState(1, 0, [self.horns, self.foraging], self.player1_species, ext_player=Player()) self.player2 = PlayerState(2, 3, [self.carnivore, self.fattissue], self.player2_species, ext_player=Player()) self.player3 = PlayerState(3, 6, [self.burrowing], self.player3_species, ext_player=Player()) self.public_player1 = PlayerState(1, False, False, self.player1_species) self.public_player2 = PlayerState(2, False, False, self.player2_species) self.public_player3 = PlayerState(3, False, False, self.player3_species) self.list_of_players = [self.player1, self.player2, self.player3] # Dealer (List of Players, Watering Hole, Deck) self.dealer1 = Dealer(self.list_of_players, 10, []) # Action self.action4_1 = Action4(FoodCardAction(1), [GrowAction(POPULATION, 0, 0)], [], [], []) self.action4_2 = Action4(FoodCardAction(0), [], [], [], [ReplaceTraitAction(1, 0, 1)]) self.action4_3 = Action4(FoodCardAction(0), [], [], [], []) self.action4_list = [self.action4_1, self.action4_2, self.action4_3]
def __init__(self, Graph: nx.Graph, mutation_ratio: int, uncertainty: float, surrender_option_on: bool): self.Graph = Graph self.N = Graph.number_of_nodes() self.State = [ Species([]) ] * self.N # The state will contain a mapping of nodes to the species that currently lives on it. self.mutation_ratio = mutation_ratio self.uncertainty = uncertainty self.surrender_option_on = surrender_option_on self.surrender_fight_ratio = None
def parse_species(species_json): """ converts from a json representation of species to a species representation :param species_json: Species+ :return: Species """ try: if (len(species_json) == 5): [[f, food], [b, body], [p, population], [t, lot], [fb, fat_food]] = species_json if (f == "food" and b == "body" and p == "population" and t == "traits" and fb == "fat-food"): species = Species(food, body, population, parse_lot(lot)) if fat_food == 0: return species species.setFatFood(fat_food) return species else: [[f, food], [b, body], [p, population], [t, lot]] = species_json if (f == "food" and b == "body" and p == "population" and t == "traits"): return Species(food, body, population, parse_lot(lot)) except ValueError: raise ValueError("invalid species")
def from_json_gamestate(json_state): """ Takes in a json game state, converting it into a list that contains the PlayerState, WateringHole, and other species :param json_state: JSON List - [Natural, [Species+, ..., Species+], Cards, Natural+, LOB] :return: [PlayerState, Nat, List of Species] """ ps = PlayerState.from_json_state(json_state[:3]) watering_hole = json_state[3] all_species = [] for species_list in json_state[4]: all_species.append([Species.convertSpecies(species) for species in species_list]) return [ps, watering_hole, all_species]
def speciate(self): comporg = None counter = 0 #//Step through all existing organisms for curorg in self.organisms: #//For each organism, search for a species it is compatible to cur_species_i = 0 found = False while (cur_species_i < len(self.species)) and (not found): comporg = self.species[cur_species_i].first() if comporg is None: #//Keep searching for a matching species cur_species_i += 1 elif curorg.gnome.compatibility(comporg.gnome) < neat.compat_threshold: #//Found compatible species, so add this organism to it self.species[cur_species_i].add_Organism(curorg) curorg.species = self.species[cur_species_i] found = True else: #//Keep searching for a matching species cur_species_i += 1 #//If we didn't find a match, create a new species if not found: newspecies = Species() counter += 1 newspecies.SetFromId(counter) self.species.append(newspecies) newspecies.add_Organism(curorg) curorg.species = newspecies # end species search conditions # end organism loop self.last_species = counter return True
def is_larger_attack_option(self, defend_player, def_spec_index, attacker, largest_def_species): """ Checks if the attacker -> def_species_index is a larger attack option than attacker -> largest_def_species :param defend_player: PlayerState - the defending playerState containing the defending species to compare :param def_spec_index: Nat - the index of the species to compare against largest_def_species :param attacker: Species - the attacking species :param largest_def_species: Species - the current largest defending species to compare against :return: One of: - Tuple(Nat, Species) - the new larger option found - False (if not a larger option) """ lNeighbor, rNeighbor = defend_player.get_neighbors(def_spec_index) def_species = defend_player.species[def_spec_index] if Species.isAttackable(def_species, attacker, lNeighbor, rNeighbor) and def_species.isLarger(largest_def_species): return def_spec_index, defend_player.species[def_spec_index] return False
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")
def test_is_larger(self): # Population different self.defender.population = 2 self.attacker.population = 1 self.assertEqual(Species.is_larger(self.defender, self.attacker), 1) self.assertEqual(Species.is_larger(self.attacker, self.defender), -1) # Same population different food self.attacker.population = 2 self.defender.food = 2 self.attacker.food = 1 self.assertEqual(Species.is_larger(self.defender, self.attacker), 1) self.assertEqual(Species.is_larger(self.attacker, self.defender), -1) # Same population and food different body self.attacker.food = 2 self.defender.body = 4 self.attacker.body = 3 self.assertEqual(Species.is_larger(self.defender, self.attacker), 1) self.assertEqual(Species.is_larger(self.attacker, self.defender), -1) # Equal population, food, and body self.attacker.body = 4 self.assertEqual(Species.is_larger(self.defender, self.attacker), 0)
def setUp(self): self.pDealer = ProxyDealer() self.card1 = TraitCard(Trait.ambush, -2) self.card2 = TraitCard(Trait.carnivore, -8) self.card3 = TraitCard(Trait.ambush, 0) self.species1 = Species(0, 3, 3, []) self.species2 = Species(0, 2, 1, []) self.speciesscavenger = Species(0, 3, 3, [Trait.scavenger]) self.speciesforaging = Species(0, 3, 3, [Trait.foraging]) self.speciescoop = Species(0, 3, 3, [Trait.cooperation]) self.speciesfull = Species(2, 2, 2, []) self.speciesfull1 = Species(3, 2, 3, []) self.speciesfull2 = Species(4, 2, 4, []) self.speciesfat= Species(0, 3, 3, [Trait.fat_tissue]) self.speciesfat.setFatFood(1) self.specieshorns = Species(0, 3, 3, [Trait.horns]) self.speciescarni = Species(0, 3, 3, [Trait.carnivore]) self.specieshorns1 = Species(0, 3, 1, [Trait.horns]) self.speciescarni1 = Species(0, 3, 1, [Trait.carnivore]) self.speciesLongFertile = Species(0, 3, 1, [Trait.long_neck, Trait.fertile]) self.speciesFertile = Species(0, 3, 1, [Trait.fertile]) self.speciesLongNeck = Species(0, 3, 1, [Trait.long_neck])
def setUp(self): self.dealer = Dealer([Player(), Player(), Player(), Player()]) self.dealer.watering_hole = 10 self.dealer.player_sets[0]['state'].name = 0; self.dealer.player_sets[1]['state'].name = 1; self.dealer.player_sets[2]['state'].name = 2; self.dealer.player_sets[3]['state'].name = 3; self.dealer.current_player_index = 2 self.species_1 = Species(4, 4, 4) self.species_2 = Species(4, 4, 4) self.species_3 = Species(4, 3, 3) self.species_4 = Species(4, 3, 3) self.species_5 = Species(3, 3, 3) self.species_list = [self.species_1, self.species_2, self.species_3, self.species_4, self.species_5] self.dealer.player_sets[0]['state'].species = [self.species_1] self.dealer.player_sets[1]['state'].species = [self.species_2] self.dealer.player_sets[2]['state'].species = [self.species_3] self.dealer.player_sets[3]['state'].species = [self.species_4, self.species_5]
def feed_result_carnivore(self, attSpecIndex, defPlayerIndex, defSpecIndex): """ Effect: Attacking species will get food, decrease population if attacking horns. Defending species of defPlayerIndex will reduce in population if attack succeeds Food is taken from the wateringHole for successful attacks Extinction will cause extinct species owners to get cards, which are removed from this dealers hand :param attSpecIndex: Nat - the index of the carnivore species in the player that is attacking :param defPlayerIndex: Nat - the index of the player to attack :param defSpecIndex: Nat - the index of the species in the defending player to attack :return: Void """ attPlayerState = self.playerStates[0] attSpecies = attPlayerState.get_species_at(attSpecIndex) defPlayerState = self.playerStates[defPlayerIndex] defSpecies = defPlayerState.get_species_at(defSpecIndex) leftSpecies = defPlayerState.getLeftNeighbor(defSpecIndex) rightSpecies = defPlayerState.getRightNeighbor(defSpecIndex) if Species.isAttackable(defSpecies, attSpecies, leftSpecies, rightSpecies): self.execute_attack(attSpecies, defSpecies, attPlayerState, defPlayerState, attSpecIndex, defSpecIndex) else: raise Exception("Bad Attack")
def setUp(self): self._limiting = Species("Limiting", 100) self._limiting.set_n(0.001) self._reactant2 = Species("Reactant #1", 200) self._reactant3 = Species("Reactant #2", 300) self._product = Species("Product", 400)
class TestSpecies(unittest.TestCase): def setUp(self): self.attacker = Species() self.attacker.traits = [TraitCard("carnivore")] self.defender = Species() self.left_neighbor = Species() self.right_neighbor = Species() self.species_1 = Species(4, 4, 4) self.species_2 = Species(4, 4, 4) self.species_3 = Species(4, 4, 3) self.species_4 = Species(4, 3, 3) self.species_5 = Species(3, 3, 3) self.species_list = [self.species_2, self.species_4, self.species_3, self.species_5, self.species_1] def test_can_eat(self): self.assertFalse(self.species_1.can_eat()) self.assertTrue(self.species_4.can_eat()) fat_tissue = Species(4, 3, 4, [TraitCard("fat-tissue")], 3) self.assertTrue(fat_tissue.can_eat()) fat_tissue.fat_storage = 4 self.assertFalse(fat_tissue.can_eat()) def test_trait_names(self): self.assertEqual(self.defender.trait_names(), []) self.assertEqual(self.attacker.trait_names(), ["carnivore"]) def test_attackable(self): self.assertTrue(self.defender.is_attackable(self.attacker)) def test_no_carnivore(self): self.attacker.traits = [] self.assertFalse(self.defender.is_attackable(self.attacker)) def test_burrowing(self): self.defender.traits = [TraitCard("burrowing")] self.defender.population, self.defender.food = (4, 4) self.assertFalse(self.defender.is_attackable(self.attacker)) self.defender.food = 3 self.assertTrue(self.defender.is_attackable(self.attacker)) def test_climbing(self): self.defender.traits = [TraitCard("climbing")] self.assertFalse(self.defender.is_attackable(self.attacker)) self.attacker.traits.append(TraitCard("climbing")) self.assertTrue(self.defender.is_attackable(self.attacker)) def test_hard_shell(self): self.defender.traits = [TraitCard("hard-shell")] self.defender.body = 3 self.attacker.body = 6 self.assertFalse(self.defender.is_attackable(self.attacker)) self.attacker.body = 7 self.assertTrue(self.defender.is_attackable(self.attacker)) def test_herding(self): self.defender.traits = [TraitCard("herding")] self.defender.population = 4 self.attacker.population = 3 self.assertFalse(self.defender.is_attackable(self.attacker)) self.attacker.population = 5 self.assertTrue(self.defender.is_attackable(self.attacker)) def test_symbiosis(self): self.defender.traits = [TraitCard("symbiosis")] self.defender.body = 3 self.right_neighbor.body = 5 self.assertFalse(self.defender.is_attackable(self.attacker, right_neighbor=self.right_neighbor)) self.right_neighbor.body = 2 self.assertTrue(self.defender.is_attackable(self.attacker, right_neighbor=self.right_neighbor)) def test_warning_call(self): self.left_neighbor.traits = [TraitCard("warning-call")] self.right_neighbor.traits = [TraitCard("warning-call")] self.assertFalse(self.defender.is_attackable(self.attacker, left_neighbor=self.left_neighbor)) self.assertFalse(self.defender.is_attackable(self.attacker, right_neighbor=self.right_neighbor)) self.attacker.traits.append(TraitCard("ambush")) self.assertTrue(self.defender.is_attackable(self.attacker, left_neighbor=self.left_neighbor)) def test_is_larger(self): # Population different self.defender.population = 2 self.attacker.population = 1 self.assertEqual(Species.is_larger(self.defender, self.attacker), 1) self.assertEqual(Species.is_larger(self.attacker, self.defender), -1) # Same population different food self.attacker.population = 2 self.defender.food = 2 self.attacker.food = 1 self.assertEqual(Species.is_larger(self.defender, self.attacker), 1) self.assertEqual(Species.is_larger(self.attacker, self.defender), -1) # Same population and food different body self.attacker.food = 2 self.defender.body = 4 self.attacker.body = 3 self.assertEqual(Species.is_larger(self.defender, self.attacker), 1) self.assertEqual(Species.is_larger(self.attacker, self.defender), -1) # Equal population, food, and body self.attacker.body = 4 self.assertEqual(Species.is_larger(self.defender, self.attacker), 0) def test_sort_lex(self): sorted_list = [self.species_2, self.species_1, self.species_3, self.species_4, self.species_5] self.assertEqual(Species.sort_lex(self.species_list), sorted_list) self.assertNotEqual(Species.sort_lex(self.species_list), self.species_list) def test_largest_tied_species(self): tied_species = [self.species_2, self.species_1] self.assertEqual(Species.largest_tied_species(self.species_list), tied_species) def test_largest_fatty_need(self): self.species_1.traits = [TraitCard("fat-tissue")] self.species_2.traits = [TraitCard("fat-tissue")] self.species_4.traits = [TraitCard("fat-tissue")] self.assertEqual(Species.largest_fatty_need([self.species_1, self.species_4]), self.species_4) self.assertEqual(Species.largest_fatty_need([self.species_1, self.species_2]), self.species_1)
def test_largest_fatty_need(self): self.species_1.traits = [TraitCard("fat-tissue")] self.species_2.traits = [TraitCard("fat-tissue")] self.species_4.traits = [TraitCard("fat-tissue")] self.assertEqual(Species.largest_fatty_need([self.species_1, self.species_4]), self.species_4) self.assertEqual(Species.largest_fatty_need([self.species_1, self.species_2]), self.species_1)
def test_largest_tied_species(self): tied_species = [self.species_2, self.species_1] self.assertEqual(Species.largest_tied_species(self.species_list), tied_species)
def test_sort_lex(self): sorted_list = [self.species_2, self.species_1, self.species_3, self.species_4, self.species_5] self.assertEqual(Species.sort_lex(self.species_list), sorted_list) self.assertNotEqual(Species.sort_lex(self.species_list), self.species_list)