Exemplo n.º 1
0
    def make_player(self, name, coords = (0,0,1,0), affiliation = {'Obama': 5, 'Kanye': 4, 'OReilly': 3, 'Gottfried': 2, 'Burbiglia': 1}):

        path = 'players/%s.xml' % name
        if os.path.exists(path):    # Load the player if a save file exists for them, otherwise create a new player
            player = loader.load_player(path)
        else:
            player = Player(name, coords, coords, affiliation)

        self._Characters_Lock.acquire()
        self._Characters[player.name] = player # Add to list of players in the game
        self._Characters_Lock.release()

        self._Rooms[player.coords].players.append(player.name) # Add player to list of players in the room they are in

        self.logger.write_line("Created player '%s' at (%d,%d,%d,%d)" % (player.name, player.coords[0], player.coords[1], player.coords[2], player.coords[3]))
Exemplo n.º 2
0
def main():
    crop_types = loader.load_crop_types()

    for i in crop_types.iloc:
        if i['fall']:
            print(f'{i["name"]} grows in fall')

    player = loader.load_player()
    print(player)

    bonus = 1
    if player.profession == 'tiller':
        bonus = 1.1

    plt.style.use('ggplot')

    fig_cc, ax_cc = plt.subplots()
    fig_ex, ax_ex = plt.subplots()
    fig_ce, ax_ce = plt.subplots()
    fig_vic, ax_vic, = plt.subplots()
    fig_ose, ax_ose, = plt.subplots()

    on_season_end = []

    mask = crop_types[player.season]
    print(f'mask: {mask}')
    crop_types = crop_types[mask]

    for crop_type in crop_types.iloc:

        print('\n---------------------\n'
             f'crop: {crop_type["name"]} - {crop_type["daysToMature"]} days to mature')
        
        days = np.arange(1, 29)
        days_with_excess = []
        excess = []
        cumulative_earnings = np.zeros(28)
        crop_count = np.zeros(28)
        value_in_crops = np.zeros(28)

        # simulate if doesn't regrow
        if crop_type['regrowth'] == -1:

            can_afford = int(np.floor(player.seed_capital / crop_type['seedPrice']))
            tiles_count = min(can_afford, player.max_tiles)

            print(f'staring with {tiles_count} tiles')

            for i in days:
                print(f'day: {i}')

                if i < player.day_of_season:
                    print('\tpass')
                    continue

                # on harvest
                if (i % crop_type['daysToMature']) == 0:
                    print('\tharvest')

                    profit = tiles_count * crop_type['sellPrice'] * bonus

                    # can regrow till the end of season?
                    if 28 - i >= crop_type['daysToMature']:
                        seeds_got = int(tiles_count * crop_type['seedDrop'])
                        can_afford = int(profit / crop_type['seedPrice'])
                        can_plant_total = can_afford + seeds_got
                        will_plant = min(can_plant_total, player.max_tiles)
                        will_buy = max(will_plant - seeds_got, 0)

                        replant_cost = will_buy * crop_type['seedPrice']

                        profit -= replant_cost
                        if profit > 0:
                            excess.append(profit)
                            days_with_excess.append(i)

                        tiles_count = will_plant
                        print(f'\t{tiles_count} new crops')
                    else:
                        excess.append(profit)
                        days_with_excess.append(i)
                        print('\twill not finish regrowing')

                    cumulative_earnings[i - 1] += profit

                crop_count[i - 1] = tiles_count
                value_in_crops[i - 1] = crop_count[i - 1] * crop_type['seedPrice']

                # add earnings from proceding day
                if i > 1:
                    cumulative_earnings[i - 1] += cumulative_earnings[i - 2]

        # simulate if regrows
        if crop_type['regrowth'] > 0:

            can_afford = int(np.floor(player.seed_capital / crop_type['seedPrice']))
            tiles_count = min(can_afford, player.max_tiles)

            print(f'staring with {tiles_count} tiles, regrowth: {crop_type["regrowth"]}')
            
            tiles = [Tile(crop_type, 1)] * tiles_count

            for i in days:
                print(f'days: {i}')

                if i < player.day_of_season:
                    print('\tpass')
                    continue

                harvested = 0
                profit = 0
                for t in tiles:
                    if t.harvest_today(i):
                        harvested += 1
                        profit += crop_type['sellPrice']
                profit *= bonus
                print(f'\tharvested {harvested}')
                
                can_afford = int(profit / crop_type['seedPrice'])
                free_tiles = player.max_tiles - len(tiles)
                new_tile_count = min(free_tiles, can_afford)
                tiles += [Tile(crop_type, i)] * new_tile_count

                crop_count[i - 1] = len(tiles)
                value_in_crops[i - 1] = crop_count[i - 1] * crop_type['seedPrice']

                profit -= new_tile_count * crop_type['seedPrice']
                if profit > 0:
                    excess.append(profit)
                    days_with_excess.append(i)

                if i > 1:
                    cumulative_earnings[i - 1] = profit + cumulative_earnings[i - 2]
                else:
                    cumulative_earnings[i - 1] = 0

        # crop count
        ax_cc.plot(days, crop_count, marker='.', label=crop_type['name'])

        # excess gold on harvest
        ax_ex.scatter(days_with_excess, excess, marker='o', label=crop_type['name'])

        # cumulative earnings
        ax_ce.plot(days, cumulative_earnings, marker='.', label=crop_type['name'])
        on_season_end.append([int(cumulative_earnings[len(days) - 1]), str(crop_type['name'])])

        # value in crops
        ax_vic.plot(days, value_in_crops, marker='.', label=crop_type['name'])

    # draw charts

    # crop count
    ax_cc.set_title(f'crop count ({player.season})')
    ax_cc.set_xticks(days)
    ax_cc.set_xticklabels(days)
    ax_cc.set_xlabel('day')
    ax_cc.set_ylabel('number of crops')
    ax_cc.grid(True)
    # max crop count
    ax_cc.axline((0, player.max_tiles), (27, player.max_tiles),
               color='red', linestyle='--', label='max crop count')
    ax_cc.legend()

    # excess
    ax_ex.set_title(f'excess gold on harvest ({player.season})')
    ax_ex.set_xticks(days)
    ax_ex.set_xticklabels(days)
    ax_ex.set_xlabel('day')
    ax_ex.set_ylabel('excess gold on harvest [gold]')
    ax_ex.grid(True)
    ax_ex.legend()

    # cumulative earnings
    ax_ce.set_title(f'cumulative earnings ({player.season})')
    ax_ce.set_xticks(days)
    ax_ce.set_xticklabels(days)
    ax_ce.set_xlabel('day')
    ax_ce.set_ylabel('cumulative earnings [gold]')
    ax_ce.legend()

    # value in crops
    ax_vic.set_title(f'value in crops ({player.season})')
    ax_vic.set_xticks(days)
    ax_vic.set_xticklabels(days)
    ax_vic.set_xlabel('day')
    ax_vic.set_ylabel('value in crops [gold]')
    ax_vic.legend()

    # ROI
    tab = [(i['sellPrice'] / i['seedPrice'], i['name']) for i in crop_types.iloc]
    tab.sort()
    roi = [i[0] for i in tab]
    roi_names = [i[1] for i in tab]

    fig_roi, ax_roi = plt.subplots()

    ax_roi.barh(roi_names, roi)
    ax_roi.set_yticks(roi_names)
    ax_roi.set_yticklabels(roi_names)
    fig_roi.suptitle(f'crops ROI on first harvest ({player.season})')

    # on season end
    on_season_end.sort()
    ose_values = [i[0] for i in on_season_end]
    ose_names = [i[1] for i in on_season_end]
    print(ose_names)
    print(ose_values)
    ax_ose.barh(np.arange(len(crop_types)), ose_values)
    ax_ose.set_yticks(np.arange(len(crop_types)))
    ax_ose.set_yticklabels(ose_names)
    ax_ose.set_title(f'earnings on season\'s end with capital {player.seed_capital} gold ({player.season})')

    plt.tight_layout()

    # legent might be placed badly
    output = './out'
    fig_roi.savefig(f'{output}/roi.png')
    fig_cc.savefig(f'{output}/crop_count.png')
    fig_ex.savefig(f'{output}/excess.png')
    fig_ce.savefig(f'{output}/cumulative_earnigns.png')
    fig_vic.savefig(f'{output}/value_in_crops.png')
    fig_ose.savefig(f'{output}/on_seasaon_end.png')
    plt.show()
Exemplo n.º 3
0
    def verify_player(self, name, password, connection):

        global _Logged_in
        global _Banned_names
        global _Logger
        global _User_Pings
        global _Player_Loc_Lock
        global _Player_Locations
        global _World_list
        global _Player_Data
        global _Player_Data_Lock
        global _Threads_Lock
        global _Threads

        path = "login_file/%s.txt" % name
        logger.write_line("Verifying player credentials")
        player_affil = {}  # Current player's affiliation data.
        prev_coords = (0, 0, 1, 0)
        items = []
        fih = 30
        vote_history = {}

        if (
            name not in _Logged_in and name not in _Banned_names
        ):  # This person is not already logged in to the game, they may proceed to the next step.
            logger.write_line("This player is not already logged in, or banned. Proceed")
            if os.path.exists(path):  # This file exists
                logger.write_line("This player's login file does indeed exist.")
                fin = open(path)
                pwd = fin.readline()
                fin.close()

                if password == pwd:  # Login successful

                    print "User <%s> authenticated" % name
                    logger.write_line("User <%s> authenticated." % name)
                    _Logged_in.append(name)
                    _Player_Loc_Lock.acquire()
                    _Player_Locations[name] = "lobby"  # Log in to the lobby initially
                    _Player_Loc_Lock.release()
                    _Player_Data_Lock.acquire()
                    _Player_Data[name] = []  # [0]: location tuple, [1]: affiliation dict
                    _Player_Data_Lock.release()
                    player_path = "players/%s.xml" % name
                    try:
                        person = loader.load_player(player_path)
                        logger.write_line("Loading player file %s successful." % player_path)
                        logged_in = True
                        prev_coords = person.prev_coords
                        items = person.items
                        fih = person.fih
                        vote_history = person.vote_history

                    except:
                        logger.write_line("Error loading player file %s, file does not exist" % player_path)
                        print "Error loading player file %s, file does not exist" % player_path
                        return False
                    player_affil = person.affiliation  # Load in the players affiliation
                    location = person.coords

                    _Player_Data_Lock.acquire()
                    _Player_Data[name].append(location)  # Add the location tuple to the list.

                    _Player_Data_Lock.release()

                else:
                    print "User <%s> failed to authenticate." % name
                    logger.write_line("User <%s> failed to authenticate." % name)
                    RAProtocol.sendMessage("_invalid_", connection)
                    return False

            else:  # File does not exist, require them to register
                RAProtocol.sendMessage(
                    "_requires_registration_", connection
                )  # Tell them they are required to register and drop them?
                logger.write_line("User is not registered, ending.")
                return False

            if logged_in:  # They have been logged in and their player data is known.
                _User_Pings_Lock.acquire()
                _User_Pings[name] = time.time()
                _User_Pings_Lock.release()
                _Player_Data_Lock.acquire()
                _Player_Data[name].append(player_affil)  # This may be {}, but we check for that later.
                _Player_Data[name].append(prev_coords)  # (0,0,1,0) unless loaded as otherwise.
                _Player_Data[name].append(items)  # [] if not loaded.
                _Player_Data[name].append(fih)  # 30 if not loaded as otherwise.
                _Player_Data[name].append(vote_history)  # {} if not loaded as otherwise.
                _Player_Data_Lock.release()

                loader.save_player(person)  # Save the file
                logger.write_line("Saving player file for user <%s>" % name)

                # *create player state and add to _Player_States (to be added)
                # add new player I/O queues
                oqueue = Queue.Queue()
                line = "\r\n"
                for world in _World_list:
                    line += "\t" + world + "\r\n"

                oqueue.put(
                    "Welcome to the RenAdventure lobby!\r\nThe following worlds are available (type: join name_of_world):"
                    + line
                )  ###TEST
                _Player_OQueues_Lock.acquire()
                _Player_OQueues[name] = oqueue
                _Player_OQueues_Lock.release()
                line = "The following people are in the lobby: \r\n"
                _Player_Loc_Lock.acquire()
                for person in _Player_Locations:
                    if (
                        _Player_Locations[person] == "lobby" and person != name
                    ):  # This person is in the lobby, and isn't the person we're listing people to.
                        line += "\t" + person + "\r\n"

                _Player_Loc_Lock.release()
                if line != "The following people are in the lobby: \r\n":  # We added players to this line
                    oqueue.put(line)
                else:  # There are no people in the lobby but you
                    oqueue.put("There is no one else in the lobby at present.")

                # oqueue.put(engine_classes.engine_helper.get_room_text(name, location, engine))  #####NEED FILTER
                RAProtocol.sendMessage("_get_ip_", connection)  # Tell them we need their IP for outgoing messages
                logger.write_line("Getting IP from client..")

                ip = RAProtocol.receiveMessage(
                    connection
                )  # Get their IP from the client and make an outgoing connection with it.
                logger.write_line("Received the following IP from the client: %s" % ip)
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    sock.connect((ip, 8888))  # Connect to client on port 8888 for sending messages
                    logger.write_line("Connected to socket.")
                    RAProtocol.sendMessage("_out_conn_made_", connection)
                    ot = PlayerOutput(name, sock)  # Output thread for this player
                    ot.start()

                    _Threads_Lock.acquire()
                    _Threads.append(ot)
                    _Threads_Lock.release()

                except:
                    RAProtocol.sendMessage("_connection_fail_", connection)
                    logger.write_line("Failed to connect")

                _Players_Lock.acquire()
                _Players.append(name)
                _Players_Lock.release()

                return True  # Player has been logged in, et cetera if they made it this far.

        elif name not in _Banned_names:  # Player name is in _Logged_in, and not in _Banned_names
            print "Error, attempt to log in to an account already signed on"
            logger.write_line("Error, attempting to log in to an account already signed on: <%s>" % name)
            RAProtocol.sendMessage("already_logged_in", connection)
            return False

        else:  # player_name in _Banned_names
            print "Attempt to log in with a banned name <%s>, account creation rejected" % name
            logger.write_line("Attempt to log in with a banned name <%s>, account creation rejected" % name)
            RAProtocol.sendMessage("banned_name", connection)
            return False
Exemplo n.º 4
0
    def addPlayer(self, conn, addr):
        """
        Add a new player to the game
        """
        global _Logged_in
        global _Banned_names
        global _Logger
        global _User_Pings
        global _Player_Loc_Lock
        global _Player_Locations
        global _World_list
        global _Player_Data
        global _Player_Data_Lock
        
        # receive message
        logged_in = False
        input_data = RAProtocol.receiveMessage(conn)
        if isinstance(input_data, RAProtocol.command):
            a_string = str(input_data.body)
        else:
            a_string = input_data
        a_string = a_string.split() #Split on space
        player_name = a_string[0]
        player_pass = a_string[1]
        player_affil = {} #Current player's affiliation data.
        prev_coords = (0,0,1,0)
        items = []
        fih = 30
        vote_history = {}

        path = 'login_file/%s.txt' % player_name

        if player_name not in _Logged_in and player_name not in _Banned_names: #This person is not already logged in to the game

            if os.path.exists(path): #This file exists
                fin = open(path)
                pwd = fin.readline()
                fin.close()

                if player_pass == pwd: #Login successful
                    print 'User <%s> logged in' % player_name
                    logger.write_line('User <%s> logged in.'%player_name)
                    logged_in = True
                    _Logged_in.append(player_name)
                    _Player_Loc_Lock.acquire()
                    _Player_Locations[player_name] = "lobby" #Log in to the lobby initially
                    _Player_Loc_Lock.release()
                    _Player_Data_Lock.acquire()
                    _Player_Data[player_name] = [] #[0]: location tuple, [1]: affiliation dict
                    _Player_Data_Lock.release()
                    player_path = 'players/%s.xml'%player_name
                    try:
                        person = loader.load_player(player_path)
                        prev_coords = person.prev_coords
                        items = person.items
                        fih = person.fih
                        vote_history = person.vote_history
                    except:
                        logger.write_line("Error loading player file %s, file does not exist" % player_path)
                        print "Error loading player file %s, file does not exist" % player_path
                    player_affil = person.affiliation #Load in the players affiliation
                    location = person.coords
                    
                    _Player_Data_Lock.acquire()
                    _Player_Data[player_name].append(location) #Add the location tuple to the list.
                    
                    _Player_Data_Lock.release()
                else:
                    print 'User <%s> failed to authenticate.' % player_name
                    logger.write_line('User <%s> failed to authenticate.'%player_name)
                    RAProtocol.sendMessage('invalid', conn)
            else: #File does not exist

                if len(a_string) == 2: #We just got name and password, not affiliation
                    RAProtocol.sendMessage('affiliation_get', conn)
                    print 'Getting user affiliation'
                    logger.write_line('Required user affiliation from <%s>'%player_name)
                elif len(a_string) == 12: #We got the affiliation data this time.
                    print 'Creating user: <%s>'% player_name
                    logger.write_line('Creating user: <%s>'%player_name)

                    cur_person = ''
                    for i in range(2, len(a_string)):
                        if i % 2 == 1: #This is an odd numbered cell, and as such is an affinity.
                            player_affil[cur_person] = int(a_string[i])
                        else: #Even numbered, person
                            cur_person = a_string[i]
                            player_affil[cur_person] = 0
                    
                    fin = open(path, 'w')
                    fin.write(player_pass)
                    fin.close()
                    location = (0,0,1,0)
                    logged_in = True
                    _Logged_in.append(player_name)
                    _Player_Loc_Lock.acquire()
                    _Player_Locations[player_name] = "lobby" #Log in to the lobby initially
                    _Player_Loc_Lock.release()
                    _Player_Data_Lock.acquire()
                    _Player_Data[player_name] = []
                    _Player_Data[player_name].append(location) #Add the location tuple to the list.
                    _Player_Data_Lock.release()
                    person = engine_classes.Player(player_name, (0,0,1,0), (0,0,1,0), player_affil) #Make this person 
                
            if logged_in:
                _User_Pings_Lock.acquire()
                _User_Pings[player_name] = time.time()
                _User_Pings_Lock.release()
                _Player_Data_Lock.acquire()
                _Player_Data[player_name].append(player_affil) #This may be {}, but we check for that later.
                _Player_Data[player_name].append(prev_coords) #(0,0,1,0) unless loaded as otherwise.
                _Player_Data[player_name].append(items) #[] if not loaded.
                _Player_Data[player_name].append(fih) #30 if not loaded as otherwise.
                _Player_Data[player_name].append(vote_history) #{} if not loaded as otherwise.
                _Player_Data_Lock.release()

                loader.save_player(person) #Save the file!
                logger.write_line("Creating player file for user <%s>" % player_name)
                
                # *create player state and add to _Player_States (to be added)
                # add new player I/O queues
                oqueue = Queue.Queue()
                line = "\r\n"
                for world in _World_list:
                    eng = _World_list[world]
                    if eng._IsRunning:
                        line += "\t"+world+"\r\n"
                
                oqueue.put("Welcome to the RenAdventure lobby!\r\nThe following worlds are available (type: join name_of_world):"+line) ###TEST
                line = "The following people are in the lobby: \r\n"
                _Player_Loc_Lock.acquire()
                for person in _Player_Locations:
                    if _Player_Locations[person] == 'lobby' and person != player_name: #This person is in the lobby, and isn't the person we're listing people to.
                        line+= "\t"+person+'\r\n'
                        
                _Player_Loc_Lock.release()
                if line != "The following people are in the lobby: \r\n": #We added players to this line
                    oqueue.put(line)
                else: #There are no people in the lobby but you
                    oqueue.put("There is no one else in the lobby at present.")
                    
                #oqueue.put(engine_classes.engine_helper.get_room_text(player_name, location, engine))  #####NEED FILTER

                _Player_OQueues_Lock.acquire()
                _Player_OQueues[player_name] = oqueue
                _Player_Loc_Lock.acquire()
                for person in _Player_Locations:
                    if _Player_Locations[person] == 'lobby' and person != player_name: #This person is in the lobby and is not who just joined. Tell everyone else.
                        _Player_OQueues[person].put("%s has joined the lobby" % player_name)
                _Player_Loc_Lock.release()
                _Player_OQueues_Lock.release()

                # Get I/O port
                self.spawn_port_lock.acquire()
                iport = self.spawn_port
                oport = self.spawn_port + 1
                self.spawn_port += 2
                self.spawn_port_lock.release()

                # spin off new PlayerI/O threads
                ithread = PlayerInput(iport, player_name)
                othread = PlayerOutput(oqueue, addr, oport, player_name)
                
                _Threads_Lock.acquire()
                _Threads.append(ithread)
                _Threads.append(othread)
                _Threads_Lock.release()

                _InThreads[player_name] = True
                _OutThreads[player_name] = True

                ithread.start()
                othread.start()


                # send new I/O ports to communicate on
                ports = str(iport) + " " + str(oport)
                message = str(ports)
                RAProtocol.sendMessage(message, conn)

                # add player to _Players
                _Players_Lock.acquire()
                _Players.append(player_name)
                _Players_Lock.release()

                conn.close()

                print player_name + " added to the game."
                logger.write_line('<'+player_name+'>'+" added to the game.")

        elif player_name not in _Banned_names: #Player name is in _Logged_in, and not in _Banned_names
            print 'Error, attempt to log in to an account already signed on'
            logger.write_line('Error, attempting to log in to an account already signed on: <%s>'%player_name)
            RAProtocol.sendMessage('already_logged_in', conn)

        else: #player_name in _Banned_names
            print 'Attempt to log in with a banned name <%s>, account creation rejected' % player_name
            logger.write_line('Attempt to log in with a banned name <%s>, account creation rejected'%player_name)
            RAProtocol.sendMessage('banned_name',conn)