How to use pelita - 10 common examples

To help you get started, we’ve selected a few pelita examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ASPP / pelita / test / test_game.py View on Github external
#  0.2 #
    # 3.1  #
    ########
    """
    bot_turn = bot_to_move // 2
    team_to_move = bot_to_move % 2
    def move(bot, s):
        if team_to_move == 0 and bot.is_blue and bot_turn == bot._bot_turn:
            return (4, 1)
            # eat the food between 0 and 2
        if team_to_move == 1 and (not bot.is_blue) and bot_turn == bot._bot_turn:
            # eat the food between 3 and 1
            return (3, 2)
        return bot.position

    l = layout.parse_layout(l)
    final_state = run_game([move, move], layout_dict=l, max_rounds=20)
    assert final_state['round'] == 1
    assert final_state['turn'] == bot_to_move
github ASPP / pelita / test / test_json.py View on Github external
def test_encoding_methods(self):
        converter = JsonConverter()

        def encoder(obj):
            return {"a": [val * 2 for val in obj.a]}

        def decoder(obj):
            obj["a"] = [val // 2 for val in obj["a"]]
            return A(**obj)

        converter.register(A, encoder=encoder, decoder=decoder)
        a = A([1, 2, 3])
        res = converter.dumps(a)
        res_dict = json.loads(res)

        self.assertEqual(res_dict, {"__id__": "pelita.test.A", "__value__": {"a": [2, 4, 6]}})

        reencoded = converter.loads(res)
github ASPP / pelita / demo / messaging / demo_ping_pong.py View on Github external
    @expose
    def Ping(self):
        if self.pong_count % 100 == 0:
            delta = datetime.now() - self.old_time
            self.old_time = datetime.now()
            print "Pong: ping " + str(self.pong_count) + " from " + str(self.ref.channel) + \
                    str(delta.seconds) + "." + str(delta.microseconds // 1000)

        self.ref.channel.notify("Pong", channel=self.ref)
        self.pong_count += 1
github ASPP / pelita / demo / demo_simplegame.py View on Github external
#  ##### ## #  # .# . .#  .  . ..#
    #.   . .   .## #    #### ## # ## #
    ######### #  .    #    .  #    #.#
    #           ## #   . #    # #   .#
    #0#####     #  #    ### #   # ## #
    #2       #  #     #.      #   ...#
    ##################################
    """

    server = SimpleServer(layout_string=layout, rounds=3000)

    def star_to_localhost(str):
        # server might publish to tcp://* in which case we simply try localhost for the clients
        return str.replace("*", "localhost")

    client = SimpleClient(SimpleTeam("the good ones", NQRandomPlayer(), BFSPlayer()), address=star_to_localhost(server.bind_addresses[0]))
    client.autoplay_process()

    client2 = SimpleClient(SimpleTeam("the bad ones", BFSPlayer(), BasicDefensePlayer()), address=star_to_localhost(server.bind_addresses[1]))
    client2.autoplay_process()

    server.run()
    print(server.game_master.universe.pretty)
    print(server.game_master.game_state)
github ASPP / pelita / demo / demo_simplegame.py View on Github external
#           ## #   . #    # #   .#
    #0#####     #  #    ### #   # ## #
    #2       #  #     #.      #   ...#
    ##################################
    """

    server = SimpleServer(layout_string=layout, rounds=3000)

    def star_to_localhost(str):
        # server might publish to tcp://* in which case we simply try localhost for the clients
        return str.replace("*", "localhost")

    client = SimpleClient(SimpleTeam("the good ones", NQRandomPlayer(), BFSPlayer()), address=star_to_localhost(server.bind_addresses[0]))
    client.autoplay_process()

    client2 = SimpleClient(SimpleTeam("the bad ones", BFSPlayer(), BasicDefensePlayer()), address=star_to_localhost(server.bind_addresses[1]))
    client2.autoplay_process()

    server.run()
    print(server.game_master.universe.pretty)
    print(server.game_master.game_state)
github ASPP / pelita / demo / demo_simplegame.py View on Github external
# ## # ## ####    # ##.   . .   .#
    #.. .  .  #. . #. #  # ## #####  #
    # ## #### #.## #     #  .  . . ..#
    #..  ..   # #  #  #    ##### #####
    ##### #####    #  #  # #   ..  ..#
    #.. . .  .  #     # ##.# #### ## #
    #  ##### ## #  # .# . .#  .  . ..#
    #.   . .   .## #    #### ## # ## #
    ######### #  .    #    .  #    #.#
    #           ## #   . #    # #   .#
    #0#####     #  #    ### #   # ## #
    #2       #  #     #.      #   ...#
    ##################################
    """

    server = SimpleServer(layout_string=layout, rounds=3000)

    def star_to_localhost(str):
        # server might publish to tcp://* in which case we simply try localhost for the clients
        return str.replace("*", "localhost")

    client = SimpleClient(SimpleTeam("the good ones", NQRandomPlayer(), BFSPlayer()), address=star_to_localhost(server.bind_addresses[0]))
    client.autoplay_process()

    client2 = SimpleClient(SimpleTeam("the bad ones", BFSPlayer(), BasicDefensePlayer()), address=star_to_localhost(server.bind_addresses[1]))
    client2.autoplay_process()

    server.run()
    print(server.game_master.universe.pretty)
    print(server.game_master.game_state)
github ASPP / pelita / pelita / game.py View on Github external
if bot_initialization:
        # We assume that we are in get_initial phase
        turn = idx
        bot_turn = None
        seed = game_state['rnd'].randint(0, sys.maxsize)
    else:
        turn = game_state['turn']
        bot_turn = game_state['turn'] // 2
        seed = None

    bot_position = game_state['bots'][turn]
    own_team = turn % 2
    enemy_team = 1 - own_team
    enemy_positions = game_state['bots'][enemy_team::2]
    noised_positions = noiser(walls=game_state['walls'],
                              bot_position=bot_position,
                              enemy_positions=enemy_positions,
                              noise_radius=game_state['noise_radius'],
                              sight_distance=game_state['sight_distance'],
                              rnd=game_state['rnd'])

    team_state = {
        'team_index': own_team,
        'bot_positions': game_state['bots'][own_team::2],
        'score': game_state['score'][own_team],
        'kills': game_state['kills'][own_team::2],
        'deaths': game_state['deaths'][own_team::2],
        'bot_was_killed': game_state['bot_was_killed'][own_team::2],
        'error_count': len(game_state['errors'][own_team]),
        'food': list(game_state['food'][own_team]),
        'name': game_state['team_names'][own_team]
github ASPP / pelita / test / test_remote_game.py View on Github external
TEAM_NAME="p2"
    def move(b, s):
        print(f"{b.round} {b.turn} p2", file=sys.stdout)
        print("p2err", file=sys.stderr)
        return b.position
    """)
    out_folder = tempfile.TemporaryDirectory()

    with tempfile.NamedTemporaryFile('w+', suffix='.py') as f:
        with tempfile.NamedTemporaryFile('w+', suffix='.py') as g:
            print(p1, file=f, flush=True)
            print(p2, file=g, flush=True)

            state = pelita.game.run_game([f.name, g.name],
                                         max_rounds=2,
                                         layout_dict=pelita.layout.parse_layout(layout),
                                         store_output=out_folder.name)

    assert state['whowins'] == 2
    assert state['fatal_errors'] == [[], []]
    assert state['errors'] == [{}, {}]

    path = Path(out_folder.name)
    blue_lines = (path / 'blue.out').read_text().split('\n')
    red_lines = (path / 'red.out').read_text().split('\n')
    # The first line contains the welcome message 'blue team 'path' -> 'name''
    assert 'blue team' in blue_lines[0]
    assert 'red team' in red_lines[0]
    # now check what has been printed
    assert blue_lines[1:] == ['1 0 p1', '1 1 p1', '2 0 p1', '2 1 p1', '']
    assert red_lines[1:] == ['1 0 p2', '1 1 p2', '2 0 p2', '2 1 p2', '']
github ASPP / pelita / test / test_player_base.py View on Github external
################ """)
        def init_rng_players():
            player_rngs = []
            def rng_test(bot, state):
                player_rngs.append(bot.random)
                return bot.position, state
            team = [
                rng_test,
                rng_test
            ]
            return team, player_rngs

        team0, player_rngs0 = init_rng_players()
        state = setup_game(team0, layout_dict=parse_layout(test_layout), max_rounds=5, seed=20)
        # play two steps
        play_turn(play_turn(state))
        assert len(player_rngs0) == 2
        # generate some random numbers for each player
        random_numbers0 = [rng.randint(0, 10000) for rng in player_rngs0]
        # teams should have generated a different number
        assert random_numbers0[0] != random_numbers0[1]

        team1, player_rngs1 = init_rng_players()
        state = setup_game(team1, layout_dict=parse_layout(test_layout), max_rounds=5, seed=20)
        # play two steps
        play_turn(play_turn(state))
        assert len(player_rngs1) == 2
        # generate some random numbers for each player
        random_numbers1 = [rng.randint(0, 10000) for rng in player_rngs1]
        # teams should have generated the same numbers as before
        assert random_numbers0 == random_numbers1
github ASPP / pelita / test / test_actor.py View on Github external
def test_raise_no_trap_exit(self):
        collectingActor1 = actor_of(CollectingActor)
        collectingActor1.trap_exit = False
        collectingActor1.start()

        collectingActor2 = actor_of(CollectingActor)
        collectingActor2.trap_exit = False
        collectingActor2.start()

        collectingActor3 = actor_of(CollectingActor)
        collectingActor3.trap_exit = True
        collectingActor3.start()

        collectingActor4 = actor_of(CollectingActor)
        collectingActor4.trap_exit = True
        collectingActor4.start()

        raisingActor = actor_of(RaisingActor)
        raisingActor.link(collectingActor1)
        collectingActor1.link(collectingActor2)
        collectingActor2.link(collectingActor3)
        collectingActor3.link(collectingActor4)

        raisingActor.start()
        raisingActor.notify("Msg")