Пример #1
0
def play_game(screen):
    island = Island(screen, [])
    #Game loop
    sound = pg.mixer.Sound("sounds/background.wav")
    sound.play(-1)
    sound.set_volume(0.3)
    while (True):
        key = pg.event.poll()
        if key.type == KEYDOWN:
            if key.key == K_ESCAPE:
                should_close, updated_data = pause_screen(screen)
                if updated_data != None:
                    island = updated_data
                if should_close:
                    sound.stop()
                    return
            else:
                status = island.work(key.key)
                if len(status):
                    sound.stop()
                    t = game_over_screen(screen, status)
                    island.villager.stop()
                    if t:
                        return
                    else:
                        island = Island(screen, [])
                        sound.play(-1)
        elif key.type == pg.QUIT:
            sound.stop()
            return
        elif key.type == KEYUP:
            if key.key == K_a or key.key == K_d:
                island.villager.stop()
        variables.FRAME_COUNT += 1
        if variables.LEVEL == 5:
            #This will be the end. so play the end screen
            sound.stop()
            t = thanks_for_playing(screen)
            if t:
                return
            else:
                island = Island(screen, [])
                sound.play(-1)
        status = island.draw()
        if len(status):
            sound.stop()
            t = game_over_screen(screen, status)
            island.villager.stop()
            if t:
                return
            else:
                sound.play(-1)
                island = Island(screen, [])
        pg.display.flip()
Пример #2
0
def main():
    timestep = 0.001

    old_settings = termios.tcgetattr(sys.stdin.fileno())
    tty.setcbreak(sys.stdin.fileno())  #Keyboard interaction
    sys.stdout.write("\033c")  #clear terminal
    sys.stdout.write("\033[?25l")  #remove cursor

    player = Player('Alex')
    background = Background(player)

    islandShapes = Island.init_shape('Maps/Island_shapes.txt')
    islands = []
    for shape in range(0, len(islandShapes)):
        x, y = background.putIsland(islandShapes[shape])
        islands.append(Island(x=x, y=y, shape=islandShapes[shape]))

    while True:
        if isData():  #If a key has been pressed
            key = sys.stdin.read(1)  #Reading key
            if key == '\x1b':  #Quit if ESC
                quitGame(old_settings)
            elif key == 'z' or 'q' or 's' or 'd':
                player.changeDrct(key)

        background.move(player)
        background.player = player
        background.show()
        player.show()
        time.sleep(timestep)
Пример #3
0
    def test_cycle_instance(self):
        """Test to show that cycle is an instance for the class AnnualCycle
        """
        i = Island()
        cycle = AnnualCycle(i)

        assert isinstance(cycle, AnnualCycle)
Пример #4
0
async def createIsland(ctx, price: int = None):
    owner = ctx.message.author
    server = getServerByGuild(ctx.guild)

    island = getIslandByOwnerInServer(owner, server)

    if island != None:
        if island.code != None:
            await ctx.send(
                f"{owner.display_name}, please use '{helpMessages.COMMAND_PREFIX}close' before opening another or '{helpMessages.COMMAND_PREFIX}update' to update it."
            )
        else:
            await ctx.send(
                f"{owner.display_name}, you have already created an island. DM this bot with {helpMessages.COMMAND_PREFIX}open <dodo code> to open a queue for your island."
            )
        return

    server.islands.append(Island(owner, price, createIslandId(), ctx.guild))

    newIsland = getIslandByOwnerInServer(owner, server)

    #check if island was successfully created
    if newIsland == None:
        await ctx.send("Failed to create queue for island.")
        logging.error(f"Failed to create island for {owner}.")
        return

    logging.info(
        f"Created new island queue for {owner}. ID: {newIsland.islandId} on server {newIsland.guild}."
    )
    await ctx.send(
        f"Island created with ID: {newIsland.islandId}. DM this bot with {helpMessages.COMMAND_PREFIX}open <dodo code> to open a queue for your island."
    )
Пример #5
0
def test_view_positions():
    STATE = GameState.getinstance()
    STATE.world = Island(10, 10)
    char = Character(MOCK_IMG, 0, 5, 5)
    results = view_positions(char)
    assert (9, 9) == results[0]
    assert (10, 5) == results[2]
    assert (9, 1) == results[4]
Пример #6
0
    def generate_story(self):

        max_island_story_days = 10

        while self.story_words < 50000:
            i = Island()
            island_story = IslandStory(i)
            for i in xrange(0, max_island_story_days):
                self.print_story(island_story.update_day())
Пример #7
0
 def set_up(self, **params):
     # Create queues, islands and threads
     for i in range(self.num_of_islands):
         self.queues_list.append(queue.Queue(maxsize=0))
     for i in range(self.num_of_islands):
         self.islands_list.append(
             Island(i, json_data, self.queues_list[i - 1],
                    self.queues_list[i]))
         thread = threading.Thread(
             target=self.islands_list[i].start_optimization)
         self.threads_list.append(thread)
Пример #8
0
    def test_fodder_growth_refills_fodder(self):
        """Test to show that fodder_growth refills fodder on location
        """
        i = Island()
        loc = (2, 7)
        h = Herbivore(i, loc)
        cycle = AnnualCycle(i)
        full_jungle = i.get_fodder_on_loc(loc)
        h.feed()
        refillable_jungle = i.get_fodder_on_loc(loc)
        cycle.fodder_growth()
        refilled_jungle = i.get_fodder_on_loc(loc)

        assert full_jungle > refillable_jungle
        assert full_jungle == refilled_jungle
Пример #9
0
    def test_sort_by_fitness_sorts(self):
        """Manual test to show that sort_by_fitness sorts all animals on all
        locations.
        """
        loc_1 = (2, 7)
        loc_2 = (2, 9)
        i = Island()
        h_1 = Herbivore(i, loc_1, weight=20)
        h_2 = Herbivore(i, loc_2, weight=5)
        h_3 = Herbivore(i, loc_1, weight=100)
        c = AnnualCycle(i)
        manually_sorted_list = [h_3, h_1, h_2]
        c.sort_by_fitness()
        sorted_list = i.get_all_herb_list()

        assert sorted_list == manually_sorted_list
Пример #10
0
    def test_animal_death_removes_all_dead_animals(self, mocker):
        """Test to show that death removes all dead animals from all locations
        """
        mocker.patch('random.random', return_value=0)
        i = Island()
        cycle = AnnualCycle(i)
        loc_1 = (2, 7)
        loc_2 = (2, 8)
        c_1 = Carnivore(i, loc_1, weight=100)
        h_1 = Herbivore(i, loc_2, weight=100)
        old_herb_count = i.get_num_herb_on_loc(loc_2)
        old_carn_count = i.get_num_carn_on_loc(loc_1)
        cycle.animal_death()

        assert i.get_num_herb_on_loc(loc_2) < old_herb_count
        assert i.get_num_carn_on_loc(loc_1) < old_carn_count
Пример #11
0
    def __init__(self, param):
        if type(MPI) == int:
            param.myrank = 0
        else:
            param.myrank = MPI.COMM_WORLD.Get_rank()

        param.nbproc = param.npx * param.npy

        param.nx = int(param.nx)
        param.ny = int(param.ny)
        self.list_param = [
            'nx', 'ny', 'npx', 'npy', 'Lx', 'Ly', 'myrank', 'nh', 'geometry',
            'mpi', 'enforce_momentum', 'isisland', 'hydroepsilon'
        ]
        param.copy(self, self.list_param)
        self.debug = False

        self.mpitools = Mpitools(param)

        self.nxl = self.nx // self.npx + 2 * self.nh
        self.nyl = self.ny // self.npy + 2 * self.nh
        # local position of the rank in the matrix of subdomains
        self.i0 = self.myrank % self.npx
        self.j0 = (self.myrank // self.npx) % self.npy
        # grid size
        self.dx = self.Lx / self.nx
        self.dy = self.Ly / self.ny

        if self.dx != self.dy:
            if (self.myrank == 0):
                print('dx and dy are different')
                print('the model does not allow it')
                print('model is not yet fully validated')
            # exit(0)

        ishift = self.i0 * self.nx // self.npx
        jshift = self.j0 * self.ny // self.npy
        self.x1d = (np.arange(self.nxl) + 0.5 - self.nh + ishift) * self.dx
        self.y1d = (np.arange(self.nyl) + 0.5 - self.nh + jshift) * self.dy

        self.xr, self.yr = np.meshgrid(self.x1d, self.y1d)

        self.set_msk()

        if self.isisland:
            from island import Island
            self.island = Island(param, self)
Пример #12
0
  def update(self, state):
    state.FONT = pygame.font.SysFont("comicsansms", 24)
    state.FOOD_TEXTURE = pygame_helpers.load_image('food.png')
    state.CHAR_TEXTURES = [
        (False, pygame_helpers.load_image('F_01.png')),
        (True, pygame_helpers.load_image('M_01.png'))
    ]
    state.GID_INDEX = 1
    state.NEAT_CONFIG = neat.Config(
        neat.DefaultGenome,
        neat.DefaultReproduction,
        neat.DefaultSpeciesSet,
        neat.DefaultStagnation,
        "config",
    )
    # load default genome
    pickle_in = open("default_genome.p", "rb")
    default_genome = pickle.load(pickle_in)

    state.screen = pygame.display.get_surface()
    state.clock = pygame.time.Clock()
    state.new_day = False
    state.day = 1
    state.width, state.height = state.screen.get_size()
    # split work for this into processes later
    state.world = Island(state.width, state.height)

    state.sprites, state.plants = pygame.sprite.Group(
    ), pygame.sprite.Group()
    for _ in range(self.population):
      x, y = pygame_helpers.random_position(state)
      new_critter = pygame_helpers.spawn_critter(state, x, y)
      state.sprites.add(new_critter)
      # give each critter a brain based on the input one
      (genome, network) = reproduction.reproduce(
          state.NEAT_CONFIG, state.GID_INDEX, default_genome,
          default_genome
      )

      new_critter.setbrainandgenome(state.GID_INDEX, genome, network)
      state.GID_INDEX += 1
    for _ in range(self.bush_pop):
      x, y = pygame_helpers.random_position(state)
      state.plants.add(Bush(state.FOOD_TEXTURE, state.day, x, y))
    pygame.time.set_timer(pygame.USEREVENT + 1, 5000)
    print('finished loading')
    return Play()
Пример #13
0
    def test_aging_adds_1_year_to_all_animals(self):
        """Test to show that aging adds a year to every animal on every
        location
        """
        i = Island()
        cycle = AnnualCycle(i)
        loc_1 = (2, 7)
        loc_2 = (2, 8)
        h_1 = Carnivore(i, loc_1, weight=100, age=0)
        h_2 = Carnivore(i, loc_1, weight=100, age=0)
        h_3 = Herbivore(i, loc_2, weight=100, age=0)
        h_4 = Herbivore(i, loc_2, weight=100, age=0)
        a_list = [h_1, h_2, h_3, h_4]
        cycle.aging()

        for animal in a_list:
            assert animal.age == 1
Пример #14
0
    def test_weight_loss_changes_for_all_animals(self, mocker):
        """Test to show that weight_loss changes weight for all animals
        on all locations.
        """
        mocker.patch('random.random', return_value=0)
        i = Island()
        cycle = AnnualCycle(i)
        loc_1 = (2, 7)
        loc_2 = (2, 8)
        c_1 = Carnivore(i, loc_1, weight=100)
        h_1 = Herbivore(i, loc_2, weight=100)
        old_weight_1 = c_1.weight
        old_weight_2 = h_1.weight
        cycle.weight_loss()

        assert c_1.weight < old_weight_1
        assert h_1.weight < old_weight_2
Пример #15
0
    def test_herb_feeding_changes_weight_for_all_herbs(self):
        """Test to show that herb_feeding changes weight for all Herbivores on
        all locations
        """
        i = Island()
        cycle = AnnualCycle(i)
        loc_1 = (2, 7)
        loc_2 = (2, 9)
        h_1 = Herbivore(i, loc_1)
        h_2 = Herbivore(i, loc_2)
        old_weight_1 = h_1.weight
        old_weight_2 = h_2.weight
        cycle.herb_feeding()
        new_weight_1 = h_1.weight
        new_weight_2 = h_2.weight

        assert old_weight_1 < new_weight_1
        assert old_weight_2 < new_weight_2
Пример #16
0
    def test_migration_moves_all_animals(self, mocker_1, mocker_2):
        """Test to show that migration moves all animals for all locations
        """
        mocker_1.return_value = True
        mocker_2.return_value = True
        geogr = """\
                               OOOO
                               OJJO
                               OOOO"""
        i = Island(geogr)
        cycle = AnnualCycle(i)
        old_loc = (1, 1)
        new_loc = (1, 2)
        h = Herbivore(i, old_loc)
        c = Carnivore(i, old_loc)
        cycle.migration()

        assert h.get_loc() == new_loc
        assert c.get_loc() == new_loc
Пример #17
0
    def __init__(self, param):
        param.myrank = MPI.COMM_WORLD.Get_rank()
        param.nbproc = param.npx * param.npy

        param.nx = int(param.nx)
        param.ny = int(param.ny)
        self.list_param = [
            'nx', 'ny', 'npx', 'npy', 'Lx', 'Ly', 'myrank', 'nh', 'geometry',
            'mpi', 'enforce_momentum', 'isisland'
        ]
        param.copy(self, self.list_param)

        self.mpitools = Mpitools(param)

        self.nxl = self.nx // self.npx + 2 * self.nh
        self.nyl = self.ny // self.npy + 2 * self.nh
        # local position of the rank in the matrix of subdomains
        self.i0 = self.myrank % self.npx
        self.j0 = (self.myrank // self.npx) % self.npy
        # grid size
        self.dx = self.Lx / self.nx
        self.dy = self.Ly / self.ny

        if self.dx != self.dy:
            if (self.myrank == 0):
                print('dx and dy are different')
                print('the model does not allow it')
                print('I stop!!!')
            exit(0)

        self.x1d = (arange(self.nxl) + 0.5 - self.nh +
                    self.i0 * self.nx // self.npx) * self.dx
        self.y1d = (arange(self.nyl) + 0.5 - self.nh +
                    self.j0 * self.ny // self.npy) * self.dy

        self.xr, self.yr = meshgrid(self.x1d, self.y1d)

        self.set_msk()

        if self.isisland:
            from island import Island
            self.island = Island(param, self)
Пример #18
0
    def test_procreation_all_adds_all_pop(self, mocker):
        """Test to show that procreation_all adds instances of both
        Carnivore and Herbivore for all locations.
        """
        mocker.patch('random.random', return_value=0)
        i = Island()
        cycle = AnnualCycle(i)
        loc_1 = (2, 7)
        loc_2 = (2, 8)
        h_1 = Carnivore(i, loc_1, weight=100)
        h_2 = Carnivore(i, loc_1, weight=100)
        h_3 = Herbivore(i, loc_2, weight=100)
        h_4 = Herbivore(i, loc_2, weight=100)
        old_num_loc_1 = i.get_num_carn_on_loc(loc_1)
        old_num_loc_2 = i.get_num_herb_on_loc(loc_2)
        cycle.procreation_all()
        new_num_loc_1 = i.get_num_carn_on_loc(loc_1)
        new_num_loc_2 = i.get_num_herb_on_loc(loc_2)

        assert old_num_loc_1 < new_num_loc_1
        assert old_num_loc_2 < new_num_loc_2
Пример #19
0
    def test_carn_feeding_changes_weight_for_all_carns(self, mocker):
        """Test to show that carn_feeding changes weight for all Carnivores on
        all locations
        """
        mocker.patch('random.random', return_value=0)
        i = Island()
        cycle = AnnualCycle(i)
        loc_1 = (2, 7)
        loc_2 = (2, 9)
        c_1 = Carnivore(i, loc_1, weight=100)
        c_2 = Carnivore(i, loc_2, weight=100)
        h_1 = Herbivore(i, loc_1, weight=10)
        h_2 = Herbivore(i, loc_2, weight=10)
        old_weight_1 = c_1.weight
        old_weight_2 = c_2.weight
        cycle.carn_feeding()
        new_weight_1 = c_1.weight
        new_weight_2 = c_2.weight

        assert old_weight_1 < new_weight_1
        assert old_weight_2 < new_weight_2
Пример #20
0
    def test_procreation_herb_adds_herb_pop(self, mocker):
        """Test to show that procreation_herb adds a Herbivore instance
        for every location needed.
        """
        mocker.patch('random.random', return_value=0)
        i = Island()
        cycle = AnnualCycle(i)
        loc_1 = (2, 7)
        loc_2 = (2, 8)
        h_1 = Herbivore(i, loc_1, weight=100)
        h_2 = Herbivore(i, loc_1, weight=100)
        h_3 = Herbivore(i, loc_2, weight=100)
        h_4 = Herbivore(i, loc_2, weight=100)
        old_num_loc_1 = i.get_num_herb_on_loc(loc_1)
        old_num_loc_2 = i.get_num_herb_on_loc(loc_2)
        cycle.procreation_herb()
        new_num_loc_1 = i.get_num_herb_on_loc(loc_1)
        new_num_loc_2 = i.get_num_herb_on_loc(loc_2)

        assert old_num_loc_1 < new_num_loc_1
        assert old_num_loc_2 < new_num_loc_2
Пример #21
0
def main(predator_breed_time=6,
         predator_starve_time=3,
         initial_predators=10,
         prey_breed_time=3,
         initial_prey=50,
         size=10,
         ticks=10):
    '''Initialization of the simulation'''

    # Initialize class variables
    Predator.set_breed_time(predator_breed_time)
    Predator.set_starve_time(predator_starve_time)
    Prey.set_breed_time(prey_breed_time)

    seed = int(input("Enter seed for randomness: "))
    random.seed(seed)

    isle = Island(size)
    put_animals_at_random(isle, Prey, initial_prey)
    put_animals_at_random(isle, Predator, initial_predators)
    print(isle)

    # The simulation is carried out 'ticks' times
    for _ in range(ticks):
        for x in range(size):
            for y in range(size):
                animal = isle.animal(x, y)
                if isinstance(animal, Animal):
                    if isinstance(animal, Predator):  # a predator can eat
                        animal.eat()
                        animal.breed()
                    if isinstance(animal, Prey):
                        animal.breed(2)
                    animal.move()
                    animal.clock_tick()

        isle.clear_all_moved_flags()
        print(isle)
Пример #22
0
def pause_screen(screen):
    title_screen = pg.image.load("sprites/pause_screen.png")
    font = pg.font.SysFont(None, 40)
    resume = font.render("Resume", True, (255, 255, 255))
    how = font.render("How to play", True, (255, 255, 255))
    restart = font.render("Restart", True, (255, 255, 255))
    end = font.render("Exit", True, (255, 255, 255))
    text = [(resume, lambda: (False, None)),
            (how, lambda s=screen: (settings_screen(screen, True), None)),
            (restart, lambda s=screen: (False, Island(screen, []))),
            (end, lambda: (True, None))]
    while (True):
        key = pg.event.poll()
        center = variables.SCREEN_WIDTH // 2
        padding = (variables.SCREEN_HEIGHT // 15)
        y = variables.SCREEN_HEIGHT // 4 + padding
        screen.blit(title_screen, (0, 0))
        mouse = pg.mouse.get_pos()
        click = pg.mouse.get_pressed()
        for t, action in text:
            color = (10, 10,
                     10) if not (center + 100 >= mouse[0] >= center - 100
                                 and y + 30 >= mouse[1] >= y - 30) else (
                                     (20, 20, 20) if not click[0] else
                                     (0, 0, 0))
            pg.draw.rect(screen, color, (center - 100, y - 30, 200, 60))
            screen.blit(t, (center - t.get_rect().width // 2,
                            y - t.get_rect().height // 2))
            if color == (0, 0, 0):
                pg.time.wait(100)
                return action()
            y += 60 + padding
        if key.type == KEYDOWN and (key.key == K_ESCAPE):
            return (False, None)
        elif key.type == pg.QUIT:
            return (True, None)
        pg.display.flip()
Пример #23
0
    def init_board(self):
        for i in range(20):
            self.islands.append(Island())

        for i in range(3):
            self.cargo_ships.append(CargoShip())
Пример #24
0
        "message_sending_probability: {}, message_ttl: {}, min_angle: {}\n"
        "individual_soft_restart_probability: {}, soft_restart_sigma: {}".
        format(islands_count, max_iter, topology, min_time_between_restarts,
               message_sending_probability, message_ttl, min_angle,
               individual_soft_restart_probability, soft_restart_sigma))

    diversity_logger = logging.getLogger("diversityLogger")
    diversity_logger.setLevel(logging.INFO)
    dfh = logging.FileHandler("results/diversity.csv", mode='w')
    dfh.setLevel(logging.INFO)
    diversity_logger.addHandler(dfh)
    diversity_logger.info("epoch,diversity")

    controlIslands = [
        Island(toolbox, tools, population_size, i, min_time_between_restarts,
               0, message_ttl, min_angle, dimension, x_min, x_max,
               mutation_probability, crossover_probability,
               individual_soft_restart_probability, soft_restart_sigma)
        for i in range(islands_count)
    ]

    islands = [
        Island(toolbox, tools, population_size, i + islands_count,
               min_time_between_restarts, message_sending_probability,
               message_ttl, min_angle, dimension, x_min, x_max,
               mutation_probability, crossover_probability,
               individual_soft_restart_probability, soft_restart_sigma)
        for i in range(islands_count)
    ]

    make_topology(topology, islands, islands_count)
    #print_neighbours()
Пример #25
0
def main():
    island = Island(6, 6, 5)
    score = epsilongreedy(island, print_island=True)
    print("Score final:", score)
Пример #26
0
  """
    angle_rads = math.radians(angle_deg)
    return (int(math.cos(angle_rads) * hyp + originx + 0.5),
            int((-1 * math.sin(angle_rads) * hyp) + originy + 0.5))


if __name__ == "__main__":
    init_pygame()
    setup()
    # global STATE
    # current_best = neat.DefaultGenome
    print("finished loading")
    # for _, member in WorldType.__members__.items():
    STATE.mode = WorldType.FOOD  # member
    print(f'Setting mode to: {STATE.mode}')
    STATE.world = Island(STATE.width, STATE.height, type=STATE.mode)
    config = neat.Config(
        neat.DefaultGenome,  # current_best,
        neat.DefaultReproduction,
        neat.DefaultSpeciesSet,
        neat.DefaultStagnation,
        "config",
    )
    pop = neat.Population(config)  # create population obj
    winner = pop.run(eval_genomes, NUM_GENERATIONS)
    BUSH_POP = 20
    print(config.genome_type)
    # if similar change set genome type to winner
    print(winner)
    if OUTPUT_WINNER_TO_FILE:
        save_genome(winner)
Пример #27
0
# get numpy version of mapping function
# map values of array one to array two using function
#

import pygame, random, sys
import numpy as np
from island import Island


def handle_events():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()


WIDTH, HEIGHT = 1000, 1000

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

world = Island(WIDTH, HEIGHT)

while (True):
    clock.tick(60)
    handle_events()

    screen.fill((0, 0, 0))
    screen.blit(world.img, world.pos)
    pygame.display.flip()
Пример #28
0
def test_can_get_greyscale_at_point():
  island = Island(5, 5)
  color = island.get_color_at(2, 2)
  grey = island.get_greyscale_at(2, 2)
  assert rgb_to_greyscale(color) == grey
Пример #29
0
def test_create_island_of_size():
  island = Island(5, 5)
  assert 5 == island.width
  assert 5 == island.height
Пример #30
0
def test_can_get_color_at_point():
  island = Island(5, 5)
  color = island.get_color_at(2, 2)
  assert 4 == len(color)