Ejemplo n.º 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()

        # 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)
Ejemplo n.º 2
0
def main():
    out = StarLog(level=1 + DEBUG, timefn=lambda: f"Thread-0 {datetime.now()}")
    out.comment("initialising server", depth=-1)

    # set up a shared matchmaking pool
    pool = MatchmakingPool(num_players=NUM_PLAYERS,
                           special_channels=SPECIAL_CHANNELS)

    # listen for connections incoming on PORT:
    try:
        # Host of "" allows all incoming connections on the chosen port
        connections = Connection.iter_listen(host="", port=DEFAULT_SERVER_PORT)
        out.comment(f"listening on port {DEFAULT_SERVER_PORT}...")
        for connection, address in connections:
            # repeatedly accept a new connection, and hand off to a new thread
            out.comment("new client connected: ", address)
            out.comment("starting a new thread to handle this client...")
            handler = threading.Thread(target=servant, args=(connection, pool))
            handler.daemon = True  # so that new thread exits when main exits
            handler.start()
    except KeyboardInterrupt:
        print()  # end line
        out.comment("bye!")
Ejemplo n.º 3
0
def main():
    out = StarLog(level=1, time=datetime.datetime.now, star="* Thread-0")
    out.comment("initialising server")

    # set up a shared matchmaking pool
    pool = MatchmakingPool()

    # listen for connections incoming on PORT:
    connections = Connection.iter_listen(HOST, PORT)
    out.comment(f"listening on port {PORT}...")
    for connection, address in connections:
        # repeatedly accept a new connection, and hand off to a new thread
        out.comment("new client connected: ", address)

        out.comment("starting a new thread to handle this client...")
        handler = threading.Thread(target=servant, args=(connection, pool))
        handler.daemon = True  # so that this thread exits when main exits
        handler.start()
Ejemplo n.º 4
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)
Ejemplo n.º 5
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~")
Ejemplo n.º 6
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, ansi=options.use_colour)
    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
        p1 = PlayerWrapper('player 1',
                           options.player1_loc,
                           time_limit=options.time,
                           space_limit=options.space,
                           logfn=out.comment)
        p2 = PlayerWrapper('player 2',
                           options.player2_loc,
                           time_limit=options.time,
                           space_limit=options.space,
                           logfn=out.comment)

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

        # Play the game!
        result = play([p1, p2],
                      delay=options.delay,
                      logfilename=options.logfile,
                      out_function=out.comment,
                      print_state=(options.verbosity > 1),
                      use_debugboard=(options.verbosity > 2),
                      use_colour=options.use_colour,
                      use_unicode=options.use_unicode)
        # Display the final result of the game to the user.
        out.comment("game over!", depth=-1)
        out.print(result)

    # 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.comment("game error!", depth=-1)
        out.print("error: invalid action!")
        out.comment(e)
    except ResourceLimitException as e:
        out.comment("game error!", depth=-1)
        out.print("error: resource limit exceeded!")
        out.comment(e)
Ejemplo n.º 7
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, ansi=options.use_colour)
    out.comment("all messages printed by the client after this begin with a *")
    out.comment("(any other lines of output must be from your Player class).")
    out.comment()

    try:
        # Import player classes
        player = PlayerWrapper("your player",
                               options.player_loc,
                               logfn=out.comment)

        # Even though we're not limiting space, the display
        # may still be useful for some users
        set_space_line()

        # Play the game, catching any errors and displaying them to the
        # user:
        result = connect_and_play(player,
                                  options.name,
                                  options.channel,
                                  options.host,
                                  options.port,
                                  logfilename=options.logfile,
                                  out_function=out.comment,
                                  print_state=(options.verbosity > 1),
                                  use_debugboard=(options.verbosity > 2),
                                  use_colour=options.use_colour,
                                  use_unicode=options.use_unicode)

        out.comment("game over!", depth=-1)
        out.print(result)

    except KeyboardInterrupt:
        print()  # (end the line)
        out.comment("bye!")
    except ConnectingException as e:
        out.print("error connecting to server")
        out.comment(e)
    except DisconnectException as e:
        out.print("connection lost", depth=-1)
        out.comment(e)
    except ProtocolException as e:
        out.print("protocol error!", depth=-1)
        out.comment(e)
    except ServerEncounteredError as e:
        out.print("server encountered error!", depth=-1)
        out.comment(e)
Ejemplo n.º 8
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(options.verbosity)
    out.comment("all messages printed by the client after this begin with a *")
    out.comment("(any other lines of output must be from your Player class).")
    out.comment()

    try:
        # Import player classes
        player = PlayerWrapper("your player", options.player_loc, options, out)

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

        # Play the game, catching any errors and displaying them to the
        # user:
        connect_and_play(player, options, out)

    except KeyboardInterrupt:
        print()  # (end the line)
        out.comment("bye!")
    except ConnectingException as e:
        out.print("error connecting to server")
        out.comment(e)
    except DisconnectException:
        out.print("connection lost")
    except ProtocolException as e:
        out.print("protocol error!")
        out.comment(e)
Ejemplo n.º 9
0
def servant(connection, pool):
    # (Each thread gets own print function which includes its thread number)
    timefn = lambda: f"{threading.current_thread().name} {datetime.now()}"
    out = StarLog(level=1 + DEBUG, timefn=timefn)
    out.comment("hello, world!")

    # # #
    # Initiate connection
    #

    # At your service, client! Let us begin the protocol
    # First, could you kindly send me a PLAY request containing your
    # name and matchmaking channel?
    out.comment("begin communication with player", depth=-1)
    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.
    new_player = NetworkPlayer(connection, playmsg["name"])

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

    # # #
    # Conduct matchmaking
    #

    # 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.comment("looking for opponents...", depth=-1)
    try:
        players = pool.match(channel, new_player, 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

    # # #
    # Initialise all players, prepare for game
    #

    # Splendid! Between the few of you, we have enough players for a game!
    # Who will take the first turn? Let us cast the proverbial die:
    out.comment("randomly assigning colours to players...")
    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.comment)

    # What name shall we give to this glorious playing?
    player_names = "_and_".join(p.name for p in players)
    timestamp = str(datetime.now())[:19].replace(" ", "_").replace(":", "-")
    game_name = f"logs/game_at_{timestamp}_with_{player_names}.txt"
    # Attempt to make sure there is a 'logs' folder ready for the game log
    try:
        os.mkdir("logs")
    except:
        pass

    # # #
    # Play game, handle result
    #

    # Without further ado, let us begin!
    try:
        with open(game_name, 'w') as log_file:
            result = play(
                players,
                out_function=out.comment,
                print_state=False,
                log_filename=game_name,
                log_file=log_file,
            )

        # What a delightful result! I hope that was an enjoyable game
        # for all of you. Let's share the final result.
        out.comment("game over!", depth=-1)
        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.comment("game error", depth=-1)
        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.comment("connection error", depth=-1)
        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.comment("protocol error!", depth=-1)
        out.comment(e)
        out.comment("a client did something unexpected")
        for player in players:
            player.error(reason="opponent broke protocol")

    # # #
    # Terminate all players
    #

    # One way or another, that's the end of this meeting. Until next time, my
    # good friends! It has been my deepest pleasure~
    out.comment("disconnection", depth=-1)
    out.comment("disconnecting players...")
    for player in players:
        player.disconnect()
    out.comment("end of thread. bye~")
Ejemplo n.º 10
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)