def create_creature(self,
                        x_position,
                        y_position,
                        screen,
                        velocity,
                        gender=None):

        if gender:
            new_creature = Creature(self.window, x_position, y_position,
                                    screen.width, screen.height, velocity,
                                    self.creatures_size,
                                    self.creature_current_id, gender)
        else:

            creature_gender = None
            gender_number = random.randint(1, 3)

            if gender_number == 1:
                creature_gender = "M"

            else:
                gender_number = "F"

            new_creature = Creature(self.window, x_position, y_position,
                                    screen.width, screen.height, velocity,
                                    self.creatures_size,
                                    self.creature_current_id, creature_gender)

        self.creatures.append(new_creature)
        self.population += 1
        pygame.draw.rect(self.window, (0, 0, 255),
                         (x_position, y_position, 10, 10))
        self.creature_current_id += 1
예제 #2
0
 def populate_creatures(self, creatures):
     if type(creatures) == list:
         for creature_name in creatures:
             self.creatures.append(Creature(creature_name, self, dict()))
     else:
         for creature_name, data in creatures.items():
             self.creatures.append(Creature(creature_name, self, data))
예제 #3
0
    def test_damage(self):
        '''
        Test damage function
        Summary: tests Creature.deal_damage function with a fixed amount
        '''
        # create the test subject and observe health
        test_subject = Creature()
        initial_health = test_subject.get_health()

        # deal some damage
        test_subject.deal_damage(50)
        end_health = test_subject.get_health()

        # make the comparison
        self.assertEqual(initial_health, end_health + 50)

        # conduct random tests
        count = 100  # controls how many times we do the test
        while count > 0:  # continue until we count down to 0
            test_subject = Creature()  # we build our test subject every time
            initial_health = test_subject.get_health()

            damage = random.randint(
                1, 100)  # choose a random number from 1 to 100
            test_subject.deal_damage(damage)
            end_health = test_subject.get_health()

            # make the comparison
            self.assertEqual(initial_health, end_health + damage)

            count -= 1
예제 #4
0
def make_babies(mating_pool, pop_size, gen, sizes, screen_size):
    '''Mix the brains of the creatures in the mating pool via crossover. return
    a list of creatures the same length as the original population.
    @params:
        mating_pool: mating pool of creatures to select from.
        pop_size: desired size of population.
    '''
    babies = []
    for i in range(pop_size - 2):
        # Randomly select two creatures from the mating pool.
        mom = mating_pool[random.randint(0, len(mating_pool) - 1)]
        dad = mating_pool[random.randint(0, len(mating_pool) - 1)]

        # Randomly mix their biases by taking a section from one parent and the
        # rest from the other.
        child_biases = []
        child_weights = []
        child_speed = 0

        # If the parents have the same sized first weight matrix, they have the
        # same eyesight. We can mix these, as well as set sizes and eyesight.
        child_speed = mom.max_speed
        wc = np.zeros_like(mom.weights[0])
        for mrow, drow, crow in zip(mom.weights[0], dad.weights[0], wc):
            division = random.randint(0, len(mrow))
            crow[:division] = mrow[:division]
            crow[division:] = drow[division:]
        child_weights.append(wc)
        # For the rest of the weights, randomly crossover genes from parents.
        for wm, wd in zip(mom.weights[1:], dad.weights[1:]):
            wc = np.zeros_like(wm)
            for mrow, drow, crow in zip(wm, wd, wc):
                division = random.randint(0, len(mrow))
                crow[:division] = mrow[:division]
                crow[division:] = drow[division:]
            child_weights.append(wc)

        child_weights = []
        for bm, bd, wm, wd in zip(mom.biases, dad.biases, mom.weights,
                                  dad.weights):
            cb = np.zeros_like(bm)
            cw = np.zeros_like(wm)
            division = random.randint(0, len(bm))
            cb[:division] = bm[:division]
            cb[division:] = bd[division:]

            cw[:division] = wm[:division]
            cw[division:] = wd[division:]
            child_weights.append(cw)
            child_biases.append(cb)

        # Now create the child.
        child = Creature(20, screen_size, sizes, gen, i)
        child.rebuild_brain(child_speed, child_biases, child_weights)
        babies.append(child)
    babies.append(Creature(4, screen_size, sizes, gen, pop_size - 1))
    babies.append(Creature(4, screen_size, sizes, gen, pop_size))
    return babies
예제 #5
0
    def __init__(self):
        self.creatures = [
            Creature("Toad", 1),
            Creature("Frog", 3),
            Dragon("Dragon", 50),
            Creature("Lion", 10)
        ]

        self.wizard = Wizard('Gandolf', 30)
예제 #6
0
def roll_dices():
    selected = listbox_encounters.curselection()
    encounter_index = selected[0]

    enemies = encounters_saved[encounter_index].get_creatures()
    enemies_change = []

    print("tamanho de enemies =", len(enemies))

    characters = []

    for i in range(len(encounters_saved[0].get_creatures())):
        characters.append(
            Creature(encounters_saved[0].get_creatures()[i].get_text()))

    for i in range(len(enemies)):
        enemies_change.append(Creature(enemies[i].get_text()))
        enemies_change[i].set_name("Inimigo " + str(i + 1) + " - " +
                                   enemies[i].get_name())

    characters_encounter = Encounter(encounters_saved[0].get_title(),
                                     characters)
    enemies_encounter = Encounter(
        encounters_saved[encounter_index].get_title(), enemies_change)

    creatures_in_battle = []

    for i in range(len(enemies_encounter.get_creatures())):
        creatures_in_battle.append(enemies_encounter.get_creatures()[i])

    for i in range(len(characters_encounter.get_creatures())):
        creatures_in_battle.append(characters_encounter.get_creatures()[i])

    #creatures_in_battle = enemies_encounter.get_creatures() + characters.get_creatures()

    for i in range(len(creatures_in_battle)):
        dice_roll = randint(1, 20)
        initiative = creatures_in_battle[i].get_initiative()

        print(dice_roll)
        print(initiative)

        creatures_in_battle[i].set_initiative(dice_roll + initiative)

    creatures_in_battle = sorted(creatures_in_battle, key=initiative_sort_key)

    listbox_roll.delete(0, tk.END)

    for creature in creatures_in_battle:
        listbox_roll.insert(
            tk.END,
            creature.get_name() + " = " + str(creature.get_initiative()))
예제 #7
0
파일: pop.py 프로젝트: CClem11/GeneticMaze
 def next_generation(self):
     start_point = self.map.get_start()
     nb_random_creatures = 3
     scores = self.get_scores()
     new_creatures = [
         Creature(pos=start_point) for _ in range(nb_random_creatures)
     ]
     for _ in range(self.nb - nb_random_creatures):
         dna = self.child_dna(self.pick_parent(scores),
                              self.pick_parent(scores))
         child = Creature(pos=start_point, dna=dna)
         child.mutation(0.02)
         new_creatures.append(child)
     self.creatures = new_creatures
예제 #8
0
 def __add_creature_to_battlefield(self, card):
     creature = Creature(card)
     battle_row = self.__battlefield[self.__active_player]
     battle_row.append(creature)
     if DEBUG:
         print(self.__commanders[self.__active_player].name + " placed " +
               creature.name + " onto the battlefield")
예제 #9
0
 def progress(self):
     # Prepare Log
     self.pop_stat.prepare_log()
     # Creatures progression
     for creature in self.pop:
         creature.progress()
         if random.random() <= creature.specie.R:
             self.reproduction(creature)
         if random.random(
         ) <= creature.specie.D + creature.specie.C * len(self.pop):
             self.kill(creature)
     # Application
     for app in self._to_append:
         self.pop.append(app)
     for kil in self._to_kill:
         self.pop.remove(kil)
     self._to_append = []
     self._to_kill = []
     # Spontaneous Birth
     rand = random.random()
     if (rand <= self.specie.B):
         self.pop.append(Creature((len(self.pop) + 1), self.specie))
         self.pop_stat.log_action("B")
     # Log size
     self.pop_stat.log_size(len(self.pop))
예제 #10
0
def create_analytics_data(
    generations,
    serializable_creatures,
):
    ''' Creates the necessary data for plots '''
    medians = []
    convergence = []
    histogram = []
    species = {}
    generations_count = len(generations)
    last_fitness = None
    for i, generation in enumerate(generations):
        if last_fitness is not None:
            fitness = generation[0]
            convergence.append(get_convergence(fitness, last_fitness))
        last_fitness = generation[0]

        median_index = (len(generation) - 1) // 2
        creature_id = generation[median_index]
        creature = serializable_creatures[creature_id]
        medians.append(creature['fitness'])
        for creature_id in generation:
            creature = serializable_creatures[creature_id]
            creature = Creature(**creature)
            cspecies = creature.get_species()
            if cspecies not in species:
                species[cspecies] = [0] * generations_count
            species[cspecies][i] += 1

    for creature_id in generations[-1]:
        creature = serializable_creatures[creature_id]
        histogram.append(int(creature['fitness']))
    return histogram, medians, species, convergence
예제 #11
0
    def create_creatures(self,
                         num_creatures,
                         mutation="NORMAL",
                         reproduction_mutation_chance=0,
                         diet_type="VEGETARIAN"):
        """Places num_creatures creatures randomly around the map.

    Arguments:
      num_creatures: int; Number of creatures to add to map.
      mutation: string; Type of mutation for the creatures (see Creature.py).
      reproduction_mutation_chance
      mutation: string; Mutation of the creature.
      reproduction_mutation_chance: Chance to mutate upor reproduction.
      diet_type: "VEGETARIAN" or "CARNIVORE"

    Returns:
      [Creature]; A list of creatures.
    """
        all_my_creatures = []
        for randy in np.random.choice(self.field.field_size**2,
                                      num_creatures,
                                      replace=False):
            self.creatures.append(
                Creature(
                    [
                        int(np.floor(randy / self.field.field_size)),
                        randy % self.field.field_size
                    ],
                    mutation=mutation,
                    reproduction_mutation_chance=reproduction_mutation_chance,
                    diet_type=diet_type))
예제 #12
0
 def threaded_load(self):
     ''' Loads the saved data from file '''
     file_path = easygui.fileopenbox('Load a generations file',
                                     default='./data/generations/')
     if file_path is None:
         return
     data = load_generations(file_path)
     self.serializable_creatures = data['creatures']
     self.generations = data['generations']
     self.builder.get_object(
         'details')['text'] = f'Generation #{len(self.generations)+1}'
     self.creatures = []
     for i, creature_id in enumerate(self.generations[-1]):
         creature_data = self.serializable_creatures[creature_id]
         creature = Creature(**creature_data,
                             view_port=self.scroll_frame.view_port)
         self.create_creature(creature, i)
     set_entry(self.builder, 'save_as',
               os.path.basename(os.path.splitext(file_path)[0]))
     self.builder.get_object('create')['state'] = 'disabled'
     self.builder.get_object('train')['state'] = 'active'
     self.builder.get_object('find_fitness')['state'] = 'disabled'
     self.builder.get_object('find_fitness_no_gui')['state'] = 'disabled'
     self.builder.get_object('sort')['state'] = 'disabled'
     self.builder.get_object('do_selection')['state'] = 'active'
     self.builder.get_object('reproduce')['state'] = 'disabled'
예제 #13
0
    def threaded_reproduce(self):
        ''' Reproduces the creatures '''
        self.builder.get_object('progress')['value'] = 0
        self.builder.get_object('reproduce')['state'] = 'disabled'

        creatures = copy(self.creatures)
        total_creatures = len(creatures)
        self.creatures = []
        k = 0
        for i, creature in enumerate(creatures):
            for _ in range(OFFSPRINGS_PER_SELECTION_SIZE):
                self.creatures.append(creature)
                creature.frame.grid(row=k // COL_COUNT, column=k % COL_COUNT)
                k += 1
                offspring = reproduce(creature, self.serializable_creatures)
                self.create_creature(offspring, k)
                k += 1
            progress = i * 100 // total_creatures
            self.builder.get_object('progress')['value'] = progress

        for i in range(k, k + RANDOM_NEW_POPULATION_SIZE):
            creature = Creature(n=random.randint(MIN_VERTICES_COUNT,
                                                 MAX_VERTICES_COUNT),
                                view_port=self.scroll_frame.view_port,
                                size=MAX_SIZE)
            self.create_creature(creature, i)

        self.builder.get_object(
            'details')['text'] = f'Generation #{self.get_generation()}'
        self.builder.get_object('progress')['value'] = 0
        self.builder.get_object('train')['state'] = 'active'
        self.builder.get_object('find_fitness')['state'] = 'active'
        self.builder.get_object('find_fitness_no_gui')['state'] = 'active'
예제 #14
0
def reproduce(creature: Creature, serializable_creatures: dict):
    ''' Creates a offsprings of a creature by adding or removing some edges '''
    offspring = Creature(n=creature.n,
                         view_port=creature.view_port,
                         size=creature.size)
    offspring.vertices = copy(creature.vertices)
    offspring.edges = copy(creature.edges)
    offspring.parent = creature.identity

    offspring = change_structure(offspring)
    parent_id = offspring.parent
    parent = serializable_creatures[parent_id]

    while True:
        if parent is None:
            break
        if parent['vertices'] == offspring.vertices and parent[
                'edges'] == offspring.edges:
            offspring = change_structure(offspring)
        else:
            if 'parent' not in parent:
                break
            if parent['parent'] is None:
                break
            parent_id = parent['parent']
            parent = serializable_creatures[parent_id]

    return offspring
예제 #15
0
def test_creatures_2():
    """
    This student is taught to use terminal with atom to write code.
    But after he uses terminal with atom, he find the interface is not very good.
    Cannot compare with pycharm. 
    So that he decide not to listen to teachers, but keep using pycharm. 
    Therefore, the student should still have a terror rating of 105 after he decides not to use terminal.
    """
    USYD = Location("USYD")
    me = Creature("Me", 5, USYD, "INFO1110 student")
    USYD.add_creature(me)
    pycharm = Item("pycharm", "powerful pycharm",
                   "A powerful tool such as pycharm can help you debug", 100)
    USYD.add_item(pycharm)
    me.get_location().remove_item(pycharm)
    me.take(pycharm)
    terminal = Item("terminal", "Mac terminal",
                    "A console to execute commands directly", 1)
    USYD.add_item(terminal)
    me.take(terminal)
    me.get_location().remove_item(terminal)
    me.drop(terminal)
    me.get_location().add_item(pycharm)
    assert me.get_terror_rating() == 105, "Test 2 failed."
    print("Test 2 passed!")
예제 #16
0
    def create_creatures(self,
                         num_creatures,
                         creature_mutation="NORMAL",
                         creature_reproduction_mutation_prob=0,
                         creatures_randomly_teleport=False,
                         creature_diet_type="HERBIVORE",
                         creature_meat_value=2):
        """Places num_creatures creatures randomly around the world.

    Arguments:
      num_creatures: int; Number of creatures to add to world.
      creature_mutation: string; Type of mutation for the creatures (see
        Creature.py).
      creature_reproduction_mutation_prob: float; probability the creature
        will mutate upon reproduction.
      mutation: string; Mutation of the creature.
      creatures_randomly_teleport: bool; Do the creatures teleport to a random
        location on the field every day?
      creature_diet_type: "HERBIVORE" or "CARNIVORE" or "SUPER_CARNIVORE"
    """
        all_my_creatures = []
        for randy in np.random.choice(self.field.field_size**2,
                                      num_creatures,
                                      replace=False):
            x_loc = int(np.floor(randy / self.field.field_size))
            y_loc = randy % self.field.field_size
            self.add_creature(
                Creature(location=[x_loc, y_loc],
                         mutation=creature_mutation,
                         reproduction_mutation_chance=
                         creature_reproduction_mutation_prob,
                         diet_type=creature_diet_type,
                         randomly_teleports=creatures_randomly_teleport,
                         meat_value=creature_meat_value))
예제 #17
0
파일: editor.py 프로젝트: jnewblanc/sog
    def getItemObj(self, itemStr, id1, id2=""):
        """ given return an existing object, or None if it doesn't exist """
        if isRoomFactoryType(itemStr.lower()):
            itemObj = RoomFactory(itemStr, id1)
        elif itemStr.lower() == "character":
            itemObj = Character(None, id2)
            itemObj.setName(id1)
        elif itemStr.lower() == "creature":
            itemObj = Creature(id1)
        elif isObjectFactoryType(itemStr.lower()):
            itemObj = ObjectFactory(itemStr, id1)
        elif itemStr.lower() == "account":
            itemObj = Account()
            itemObj.email = id1
        else:
            print("Can not determine object type.")
            return None

        if not itemObj:
            msg = "Object doesn't exist.  Aborting..."
            print(msg + "\n")
            logger.warning(msg)
            return None
        if not itemObj.load():
            if itemObj.getId() == 0:
                msg = "Couldn't load object and ID is 0.  Aborting..."
                print(msg + "\n")
                logger.warning(msg)
                return None
            else:
                itemObj._isNew = True
        return itemObj
예제 #18
0
파일: room.py 프로젝트: jnewblanc/sog
    def getPermanent(self, permId):
        """ Returns an object, given the objectID """
        itemObj = None
        (objType, objId) = permId.split("/")

        if objType.lower() == "creature":
            itemObj = Creature(objId)
        elif isObjectFactoryType(objType.lower()):
            itemObj = ObjectFactory(objType, objId)
        else:
            logger.error("Can not determine object type.")
            return None

        if itemObj:
            if itemObj.load():
                return itemObj
            else:
                logger.error(
                    "Could not load object "
                    + permId
                    + " with type "
                    + itemObj.getType()
                )
        else:
            logger.error(
                "Could not instanciate object "
                + permId
                + " with type="
                + objType
                + "and id="
                + str(objId)
            )

        return None
예제 #19
0
 def add_monster(self):
     if self.level.creature_spawn_list:
         self.level.spawn_creature(
             Creature(random.choice(self.level.creature_spawn_list)))
         self.update_without_acting()
     else:
         self.io.msg("No random spawning on this level. Can't add monster.")
예제 #20
0
 def threaded_create(self):
     ''' Creates an initial population of creatures '''
     print('Creating initial population')
     for _ in range(POPULATION_SIZE):
         creature = Creature(
             n=random.randint(MIN_VERTICES_COUNT, MAX_VERTICES_COUNT),
             size=MAX_SIZE)
         self.creatures.append(creature)
예제 #21
0
    def create_creatures(self):
        creatures = []
        for creature_id in range(self.population_size):
            pos = self._create_creature_pos()
            creature = Creature(pos, self.creature_spec)
            creatures.append(creature)

        return creatures
예제 #22
0
 def update(self):
     names = [
         "Vlad", "Kostya", "Bella", "Katya", "Sonya", "Tolya", "Sasha",
         "Igor", "Pasha", "Nadya", "Mikhail"
     ]
     if len(self.creatures) < 4:
         if random.random() < .5:
             Creature(random.choice(names), self, self.creature_type)
예제 #23
0
def test_creatures_2():
    crea_2 = Creature('Lost', 2)
    loc_2 = Location('Small tree')
    item_2 = Item('knife', 'a rust knife', 'There is a abandoned knife here.'\
                  , '6' )
    loc_2.item_ls = [item_2]
    crea_2.location = loc_2
    crea_2.take(item_2)
    return len(loc_2.item_ls)  # return 0, because there is no item
예제 #24
0
def test_creatures_5():
    crea_5 = Creature('Lost', 2)
    loc_5 = Location('Garden')
    item_5 = Item('knife', 'a rust knife', 'There is a abandoned knife here.'\
                  , '6' )
    loc_5.item_ls = [item_5]
    crea_5.location = loc_5
    crea_5.take(item_5)
    return len(loc_5.item_ls)
예제 #25
0
 def test_json_init(self):
     c = Creature({
         "name": "Magicarp",
         "health": 10,
         "attack": 1,
         "defense": 10,
         "affinity": "water"
     })
     self.assertEqual("Magicarp", c.name)
예제 #26
0
 def test_failed_init(self):
     with self.assertRaises(RuntimeError) as e:
         Creature({
             "name": "Magicarp",
             "health": 10,
             "attack": 1,
             "defense": 10
         })
     self.assertEqual(e.exception.args[0],
                      "A wild invalid initializer JSON appeared!")
예제 #27
0
 def load(self):
     self.creatures = []
     f = open(self.filename, 'r')
     gen = f.readline()[:-1]
     self.generation = int(gen)
     for line in f:
         c = Creature(saveState=line[:-1])
         self.creatures.append(c)
     f.close()
     self.textLog.push("Loading from file at generation " + gen + ".")
예제 #28
0
파일: pop.py 프로젝트: CClem11/GeneticMaze
    def __init__(self, map, number=50):
        self.nb = number
        self.map = map
        start_point = map.get_start()
        self.creatures = [Creature(pos=start_point) for _ in range(self.nb)]

        #gene = 0, 1, 2 or 3 -> up, down , right, left
        #move x axis and y axis
        self.move_x = [0, 0, 1, -1]
        self.move_y = [-1, 1, 0, 0]
예제 #29
0
    def threaded_load(self):
        ''' Loads the saved data from file '''
        data = load_generations(self.load_path)
        self.serializable_creatures = data['creatures']
        self.generations = data['generations']

        self.creatures = []
        for creature_id in self.generations[-1]:
            creature_data = self.serializable_creatures[creature_id]
            creature = Creature(**creature_data)
            self.creatures.append(creature)
예제 #30
0
 def randomiseCreatures(self, mother=None, father=None):
     self.creatures = []
     for i in range(10):
         if (mother == None) or (father == None):
             c = Creature(DNA=brainUtils.randBinary((5 + 6 * 5 + 3 * 5) *
                                                    8))
         else:
             c = mother.breed(father)
         c.x = (random.random() * (self.ARENA_WIDTH - 50) + 50)
         c.y = (random.random() * (self.ARENA_HEIGHT - 50) + 50)
         self.creatures.append(c)