예제 #1
0
def main():
    # Parse command-line options into a namespace for use throughout this
    # program
    options = get_options()

    # Create a star-log for controlling the format of output from within this
    # program
    out = StarLog(level=options.verbosity, star="*")
    out.comment(
        "all messages printed by the referee after this begin with a *")
    out.comment(
        "(any other lines of output must be from your Player classes).")
    out.comment()

    try:
        # Import player classes
        p_R = PlayerWrapper('red player', options.playerR_loc, options, out)
        p_G = PlayerWrapper('green player', options.playerG_loc, options, out)
        p_B = PlayerWrapper('blue player', options.playerB_loc, options, out)

        # We'll start measuring space usage from now, after all
        # library imports should be finished:
        set_space_line()

        # open('simulation.tsv', 'w').close()

        # with open('simulation.tsv', 'wt') as out_file:
        #     tsv_writer = csv.writer(out_file, delimiter='\t')

        #     for i in range(-3,4):
        #         for j in range(-3,4):
        #             if i+j <4 and i+j>-4:
        #                 tsv_writer.writerow([(i,j),0])

        # Play the game!
        open('result2.txt', 'w').close()
        n = 10
        for i in range(0, n):
            play([p_R, p_G, p_B], options, out)

    # In case the game ends in an abnormal way, print a clean error
    # message for the user (rather than a trace).
    except KeyboardInterrupt:
        print()  # (end the line)
        out.comment("bye!")
    except IllegalActionException as e:
        out.section("game error")
        out.print("error: invalid action!")
        out.comment(e)
    except ResourceLimitException as e:
        out.section("game error")
        out.print("error: resource limit exceeded!")
        out.comment(e)
예제 #2
0
def main():
    # Parse command-line options into a namespace for use throughout this
    # program
    options = get_options()

    # Create a star-log for controlling the format of output from within this
    # program
    out = StarLog(level=options.verbosity, star="*")
    out.comment(
        "all messages printed by the referee after this begin with a *")
    out.comment(
        "(any other lines of output must be from your Player classes).")
    out.comment()

    try:
        # Import player classes
        p_R = PlayerWrapper('red player', options.playerR_loc, options, out)
        p_G = PlayerWrapper('green player', options.playerG_loc, options, out)
        p_B = PlayerWrapper('blue player', options.playerB_loc, options, out)

        # We'll start measuring space usage from now, after all
        # library imports should be finished:
        set_space_line()

        # Play the game!
        play([p_R, p_G, p_B], options, out)

    # In case the game ends in an abnormal way, print a clean error
    # message for the user (rather than a trace).
    except KeyboardInterrupt:
        print()  # (end the line)
        out.comment("bye!")
    except IllegalActionException as e:
        out.section("game error")
        out.print("error: invalid action!")
        out.comment(e)
    except ResourceLimitException as e:
        out.section("game error")
        out.print("error: resource limit exceeded!")
        out.comment(e)
예제 #3
0
def servant(connection, pool):
    thread_name = f"* {threading.current_thread().name}"
    out = StarLog(level=1, time=datetime.datetime.now, star=thread_name)
    out.comment("hello, world!")

    # At your service, client! let's begin the protocol
    # First thing's first, could you send me a PLAY request containing your
    # name and matchmaking channel?
    out.section("begin communication with player")
    out.comment("waiting for PLAY request...")
    try:
        playmsg = connection.recv(M.PLAY)
        out.comment("successfully received PLAY request:", playmsg)
        out.comment("sending OKAY back.")
        connection.send(M.OKAY)
    except DisconnectException:
        out.comment("client disconnected. bye!")
        connection.disconnect()
        return
    except ProtocolException as e:
        out.comment("protocol error! that was unexpected...? bye!")
        connection.disconnect()
        return

    # Now that you're officially a player, let's wrap you up in an object so
    # that we won't forget your name.
    player1 = NetPlayer(connection, playmsg['name'])

    # And we'll need to note that channel for matchmaking purposes!
    channel = playmsg['channel']

    # Okay then. Now, if it pleases you just to wait one moment, I'll look for
    # some suitable opponents for you to play with...
    out.section("looking for opponents...")
    try:
        player2, player3 = pool.match(channel, player1, out)
        out.comment("opponents found!")
    except NotEnoughPlayers:
        # I'm afraid this is as far as I can take you, good sir/madam.
        # If you wait here for just a short time, I'm sure another thread
        # will come by and pick you up quite soon.
        # It has been my eternal pleasure. Farewell~    Your humble servant.
        out.comment("leaving in pool for another thread. bye~!")
        return

    # Splendid! Between the three of you, we have enough players for a game!
    # Who will take the first turn? Let us cast the proverbial three-sided die:
    out.comment("randomly assigning colours to players...")
    colours = ['red', 'green', 'blue']
    players = [player1, player2, player3]
    random.shuffle(players)
    cols_players = list(zip(colours, players))

    # Then, shall we introduce you to one another?
    col_name_map = {colour: player.name for colour, player in cols_players}
    for colour, player in cols_players:
        player.game(col_name_map, out)

    # What name shall we give to this glorious playing?
    player_names = '_x_'.join(p.name for p in players)
    start_time = time.asctime().replace(' ', '-')
    game_name = f"logs/game_{player_names}_at_{start_time}.txt"

    # Without further ado, let us begin!
    try:
        result = play(cols_players, game_name, out)

        # What a delightful result! I hope that was an enjoyable game
        # for all of you. Let's share the final result.
        out.section("game over!")
        out.comment(result)
        out.comment("sending out result...")
        for player in players:
            player.game_over(result=result)
    except IllegalActionException:
        # Ah! The game has ended early. We had better
        # make sure everyone is on the same page:
        out.section("game error")
        out.comment("game error: invalid action")
        for player in players:
            player.game_over(result="game error: invalid action")
    except DisconnectException:
        # In the unfortunate event of a disconnection, we had better
        # make sure everyone is on the same page:
        out.section("connection error")
        out.comment("a client disconnected")
        for player in players:
            try:
                player.error(reason="opponent disconnected")
            except BrokenPipeError:
                # this connection must have been the one that reset; skip it
                continue
    except ProtocolException as e:
        out.section("protocol error!")
        out.comment(e)
        out.comment("a client did something unexpected")
        for player in players:
            player.error(reason="opponent broke protocol")

    # One way or another, that's the end of this meeting. Until next time, my
    # good friends! It has been my deepest pleasure~
    out.section("disconnection")
    out.comment("disconnecting players...")
    for player in players:
        player.disconnect()
    out.comment("end of thread. bye~")
예제 #4
0
def run_game(weights, random_board=False):
    # Code copied from __main__() in referee.py
    # Modified to allow for training
    algorithm = Algorithm()
    options = get_options()
    real_reward = {"r": 0, "g": 0, "b": 0}

    # Create a star-log for controlling the format of output from within this
    # program
    out = StarLog(level=options.verbosity, star="*")
    out.comment(
        "all messages printed by the referee after this begin with a *")
    out.comment(
        "(any other lines of output must be from your Player classes).")
    out.comment()

    try:
        # Import player classes
        p_R = PlayerWrapper('red player', options.playerR_loc, options, out)
        p_G = PlayerWrapper('green player', options.playerG_loc, options, out)
        p_B = PlayerWrapper('blue player', options.playerB_loc, options, out)

        # Play the game!
        players = [p_R, p_G, p_B]

        board = None
        if random_board:
            board = Board.get_random_board()
        play(players, options, out, training=True, random_board=board)

        exits = p_R.player.board.exits
        draw = all(exits.values()) < 4

        if not draw:
            items = exits.items()
            winner = max(items, key=lambda score: items[1])[0]
            print("# DEBUG WINNER", winner)
            for color in "rgb":
                real_reward[color] = -1
            real_reward[winner] = 1
        else:
            for color in "rgb":
                real_reward[color] = 0

        # game finished, now we update weights
        assert (len(players) > 0)
        for wrapper in players:
            features = wrapper.player.features
            rewards = wrapper.player.rewards
            weights = algorithm.weight_update(
                weights, features, rewards,
                real_reward[wrapper.player.color[0]])

        return weights

    # In case the game ends in an abnormal way, print a clean error
    # message for the user (rather than a trace).
    except KeyboardInterrupt:
        print()  # (end the line)
        out.comment("bye!")
    except IllegalActionException as e:
        out.section("game error")
        out.print("error: invalid action!")
        out.comment(e)