예제 #1
0
 def test_neighbour_function(self):
     # full neighborhood
     neigh_list = square_grid_neighbours(10, SquareGridCoordinate(1, 1))
     assert len(neigh_list) == 8
     # corner
     neigh_list = square_grid_neighbours(10, SquareGridCoordinate(9, 9))
     assert len(neigh_list) == 3
     # line
     neigh_list = square_grid_neighbours(10, SquareGridCoordinate(0, 5))
     assert len(neigh_list) == 5
예제 #2
0
 def test_neighbour_function(self):
     # full neighborhood
     neigh_list = square_grid_neighbours(10, SquareGridCoordinate(1, 1))
     assert len(neigh_list) == 8
     # corner
     neigh_list = square_grid_neighbours(10, SquareGridCoordinate(9, 9))
     assert len(
         neigh_list
     ) == 8  # Used to work fine. Changed from 3, since now we have 'infinite' grid
     # line
     neigh_list = square_grid_neighbours(10, SquareGridCoordinate(0, 5))
     assert len(
         neigh_list
     ) == 8  # Used to work fine. Changed from 5, since now we have 'infinite' grid
예제 #3
0
파일: base.py 프로젝트: Nessouille/FishBowl
 def _eat(self) -> Dict[int, SquareGridCoordinate]:
     """
     Sharks that are adjacent to a Fish square eat and move into fish square (and do not move after)
     :return: list[(oid, prev_coordinate)]
     """
     _debug = 'Turn: {:<3} - Eat - '.format(self._sim_turn)
     simulation_params = self.get_simulation_parameters(self._sid)
     # get a randomized df of all sharks
     sharks = self._persistence.get_animals_by_type(
         sim_id=self._sid, animal_type=Animal.Shark).sample(frac=1)
     sharks_eating = dict()
     shark_update = dict()
     for idx, shark in sharks.iterrows():
         # get shark neighbour square
         shark_position = SquareGridCoordinate(shark.coord_x, shark.coord_y)
         shark_neighbour = square_grid_neighbours(
             simulation_params.grid_size, shark_position)
         # try to find fish
         has_fish = self._persistence.has_fish_in_square(
             sim_id=self._sid, coordinates=shark_neighbour)
         if len(has_fish) > 0:
             # Shark is eating
             random.shuffle(has_fish)
             eating_coord = has_fish[0]
             if self._persistence.eat_animal_in_square(
                     sim_id=self._sid, coordinate=eating_coord):
                 _logger.debug('{}Shark {} {} eat Fish {} and move'.format(
                     _debug, shark.oid, shark_position, eating_coord))
                 # keep shark ref and position
                 sharks_eating[shark.oid] = shark_position
                 # move shark to eating position
                 self._persistence.move_animal(sim_id=self._sid,
                                               animal_id=shark.oid,
                                               new_position=eating_coord)
                 # add to update dictionary
                 shark_update[shark.oid] = {'last_fed': self._sim_turn}
             else:
                 raise ImpossibleAction(
                     'Something went wrong in Shark: {} feeding in {}'.
                     format(shark, has_fish[0]))
         else:
             _logger.debug('{}turn: {}, No fish to eat for shark {}'.format(
                 _debug, self._sim_turn, shark.oid))
     self._persistence.update_animals(sim_id=self._sid,
                                      update_dict=shark_update)
     _logger.debug('{}{} sharks have eaten'.format(_debug,
                                                   len(sharks_eating)))
     return sharks_eating
예제 #4
0
    def test_animal_function(self):
        client = SimulationClient('sqlite:///:memory:')
        # init DB
        sid = client.init_simulation(**sim_config)
        # add a bunch of animals
        a_list = [(Animal.Fish, SquareGridCoordinate(x=1, y=1)),
                  (Animal.Fish, SquareGridCoordinate(x=2, y=1)),
                  (Animal.Fish, SquareGridCoordinate(x=3, y=1)),
                  (Animal.Fish, SquareGridCoordinate(x=1, y=3)),
                  (Animal.Fish, SquareGridCoordinate(x=3, y=2))]
        for t, c in a_list:
            client.init_animal(sim_id=sid,
                               current_turn=0,
                               animal_type=t,
                               coordinate=c)
        coord_list = client.has_fish_in_square(
            sim_id=sid, coordinates=[SquareGridCoordinate(1, 1)])
        assert len(coord_list) == 1, 'There should be a single fish'
        coord_list = client.has_fish_in_square(
            sim_id=sid, coordinates=[SquareGridCoordinate(1, 2)])
        assert len(coord_list) == 0, 'There should be no fish here'
        neigh = square_grid_neighbours(grid_size=10,
                                       coordinate=SquareGridCoordinate(2, 2))
        coord_list = client.has_fish_in_square(sim_id=sid, coordinates=neigh)
        assert len(coord_list) == 5, 'There should be 5 fishes here'

        # eating animals
        eaten = client.eat_animal_in_square(sim_id=sid,
                                            coordinate=SquareGridCoordinate(
                                                1, 1))
        assert eaten, 'Fish in 1, 1 should have been eaten'
        # can't eat dead Fish
        eaten = client.eat_animal_in_square(sim_id=sid,
                                            coordinate=SquareGridCoordinate(
                                                1, 1))
        assert not eaten, 'Should not be able to eat a dead Fish'
        client.init_animal(sim_id=sid,
                           current_turn=0,
                           animal_type=Animal.Shark,
                           coordinate=SquareGridCoordinate(5, 5))
        eaten = client.eat_animal_in_square(sim_id=sid,
                                            coordinate=SquareGridCoordinate(
                                                5, 5))
        assert not eaten, 'Should not be able to eat a Shark'
예제 #5
0
    def _move_animal_type(self, animal_type: Animal, already_moved: List[int]):
        """
        Perform move action for a type of animal
        :param animal_type:
        :param already_moved:
        :return:
        """
        _debug = 'Turn: {:<3} - Move - '.format(self._sim_turn)
        simulation_params = self.simulation_params
        animals = self._persistence.get_animals_by_type(sim_id=self._sid, animal_type=animal_type).sample(frac=1)
        for _, animal in animals.iterrows():
            if animal.oid in already_moved:
                # this one has already moved so not moving
                _logger.debug('{}{} already moved'.format(_debug, animal.oid))
                continue
            elif animal.spawn_turn == self._sim_turn:
                # fish was just spawn, not moving
                _logger.debug('{}{} just spawned'.format(_debug, animal.oid))
                continue
            else:
                neighbors = square_grid_neighbours(simulation_params.grid_size, SquareGridCoordinate(animal.coord_x,
                                                                                                     animal.coord_y))
                for neigh in neighbors:
                    if not self.check_if_occupied(neigh):
                        # move animal to this slot
                        # set occupation flag to False
                        occupation_flag = False
                        _logger.debug('{}{} moved to {}'.format(_debug, animal_type.name, neigh))
                        coord_to_remove = self._persistence.move_animal(sim_id=self._sid, animal_id=animal.oid,
                                                      new_position=neigh, occupied=occupation_flag)

                        self.update_occupied_coord(old_coord=coord_to_remove, new_coord=(neigh.x, neigh.y))

                        # set back to None
                        occupation_flag = None
                        # break # AM: why we don't have break here?! Seems like we are making unnecessary operations
                    else:
                        _logger.debug('{}{}: {} had no space to move to'.format(_debug, animal_type.name, animal.oid))
        return
예제 #6
0
 def _move_animal_type(self, animal_type: Animal, already_moved: List[int]):
     """
     Perform move action for a type of animal
     :param animal_type:
     :param already_moved:
     :return:
     """
     _debug = 'Turn: {:<3} - Move - '.format(self._sim_turn)
     simulation_params = self.get_simulation_parameters(self._sid)
     animals = self._persistence.get_animals_by_type(
         sim_id=self._sid, animal_type=animal_type).sample(frac=1)
     for _, animal in animals.iterrows():
         _logger.debug(animal)
         if animal.oid in already_moved:
             # this one has already moved so not moving
             _logger.debug('{}{} already moved'.format(_debug, animal.oid))
             continue
         elif animal.spawn_turn == self._sim_turn:
             # fish was just spawn, not moving
             _logger.debug('{}{} just spawned'.format(_debug, animal.oid))
             continue
         else:
             neighbors = square_grid_neighbours(
                 simulation_params.grid_size,
                 SquareGridCoordinate(animal.coord_x, animal.coord_y))
             for neigh in neighbors:
                 if not self._persistence.coordinate_is_occupied(
                         self._sid, neigh):
                     # move animal to this slot
                     _logger.debug('{}{} oid[{}] moved to {}'.format(
                         _debug, animal_type.name, animal.oid, neigh))
                     self._persistence.move_animal(sim_id=self._sid,
                                                   animal_id=animal.oid,
                                                   new_position=neigh)
                 else:
                     _logger.debug(
                         '{}{}: {} had no space to move to'.format(
                             _debug, animal_type.name, animal.oid))
     return
예제 #7
0
파일: base.py 프로젝트: Nessouille/FishBowl
 def _breed_and_move(
         self, fed_sharks: Dict[int, SquareGridCoordinate]) -> List[int]:
     """
     Sharks or Fish that can breed, do so in same square (and Move), others moves if free space
     - Shark Breed first
     - Then Fish
     :parameter fed_sharks: list of sharks that fed and moved (breed, if possible, on previous position)
     :return: return the list of animals that bred and moved
     """
     # perform breed for
     _debug = 'Turn: {:<3} - Breed - '.format(self._sim_turn)
     simulation_params = self.get_simulation_parameters(self._sid)
     moved = []
     to_update = {}
     # First for sharks
     sharks = self._persistence.get_animals_by_type(
         sim_id=self._sid, animal_type=Animal.Shark).sample(frac=1)
     for idx, shark in sharks.iterrows():
         # can shark breed?
         if (self._sim_turn - shark.spawn_turn
             ) >= simulation_params.shark_breed_maturity:
             # shark can breed
             if random.randint(
                     0, 100) <= simulation_params.shark_breed_probability:
                 # shark is possibly breeding...
                 breed_coord = None
                 if shark.oid in fed_sharks:
                     # ...if shark has eaten...
                     breed_coord = fed_sharks[shark.oid]
                     if self._persistence.coordinate_is_occupied(
                             self._sid, breed_coord):
                         # someone took that space before breeding
                         _logger.debug(
                             '{}This shark {} breeding has fed and moved,' +
                             ' cannot breed in {} because position is taken'
                             .format(_debug, shark.oid, breed_coord))
                         breed_coord = None
                     _logger.debug(
                         '{}This shark {} breeding has fed and moved, breeding in {}'
                         .format(_debug, shark.oid, breed_coord))
                     # shark has already moved to eating position
                     moved.append(shark.oid)
                 else:
                     # ... or if free space is available
                     neighbors = square_grid_neighbours(
                         simulation_params.grid_size,
                         SquareGridCoordinate(shark.coord_x, shark.coord_y))
                     for neigh in neighbors:
                         if not self._persistence.coordinate_is_occupied(
                                 self._sid, neigh):
                             breed_coord = SquareGridCoordinate(
                                 int(shark.coord_x), int(shark.coord_y))
                             # move shark to this slot
                             self._persistence.move_animal(
                                 sim_id=self._sid,
                                 animal_id=shark.oid,
                                 new_position=neigh)
                             moved.append(shark.oid)
                             _logger.debug(
                                 '{}Shark {} not fed breeding in {}, moving to {}'
                                 .format(_debug, shark.oid, breed_coord,
                                         neigh))
                             # break out of loop
                             break
                 if breed_coord is not None:
                     to_update[shark.oid] = {
                         'last_breed': self._sim_turn,
                         'breed_count': shark.breed_count + 1
                     }
                     # spawn new fish in breed_coord
                     new_oid = self._persistence.init_animal(
                         sim_id=self._sid,
                         current_turn=self._sim_turn,
                         animal_type=Animal.Shark,
                         coordinate=breed_coord)
                     _logger.debug('{}Spawning new shark {} {}'.format(
                         _debug, new_oid, breed_coord))
     # Last Fishes, randomize
     fishes = self._persistence.get_animals_by_type(
         sim_id=self._sid, animal_type=Animal.Fish).sample(frac=1)
     for idx, fish in fishes.iterrows():
         # can fish breed?
         if (self._sim_turn -
                 fish.spawn_turn) >= simulation_params.fish_breed_maturity:
             # fish can breed
             if random.randint(
                     0, 100) <= simulation_params.fish_breed_probability:
                 # fish is possibly breeding if free space is available
                 breed_coord = SquareGridCoordinate(int(fish.coord_x),
                                                    int(fish.coord_y))
                 _logger.debug(
                     '{}Fish breeding in {} if space is available'.format(
                         _debug, breed_coord))
                 neighbors = square_grid_neighbours(
                     simulation_params.grid_size,
                     SquareGridCoordinate(fish.coord_x, fish.coord_y))
                 for neigh in neighbors:
                     if not self._persistence.coordinate_is_occupied(
                             self._sid, neigh):
                         _logger.debug(
                             '{}Space found in {}, fish breed and move'.
                             format(_debug, neigh))
                         to_update[fish.oid] = {
                             'last_breed': self._sim_turn,
                             'breed_count': fish.breed_count + 1
                         }
                         # move fish to this slot
                         self._persistence.move_animal(sim_id=self._sid,
                                                       animal_id=fish.oid,
                                                       new_position=neigh)
                         moved.append(fish.oid)
                         # spawn new fish in breed_coord
                         self._persistence.init_animal(
                             sim_id=self._sid,
                             current_turn=self._sim_turn,
                             animal_type=Animal.Fish,
                             coordinate=breed_coord)
                         # break out of loop
                         break
     # now, update all animals
     if len(to_update) > 0:
         _logger.debug('{}{} animals updated after breeding'.format(
             _debug, len(to_update)))
         self._persistence.update_animals(sim_id=self._sid,
                                          update_dict=to_update)
     # add shark that ate and did not breed to the moved list
     for oid in fed_sharks.keys():
         if oid not in moved:
             _logger.debug('{}Shark {} did not breed after movin'.format(
                 _debug, oid))
             moved.append(oid)
     # return animal list that have already bred and moved
     return moved