コード例 #1
0
def start():
    init(autoreset=True)
    c = Character()
    with open('art/dungeon.txt') as f:
        print(f.read())
    print('')

    print('#' * 80 + '\n#' + ' ' * 78 + '#' + '\n#\tWelcome to Command-Line Dungeon Diver! '\
    'Begin by selecting a class:     #\n' + '#' + ' ' * 78 + '#' + '\n' + '#' * 80)

    announce('Mage, Warrior, Fighter, Cleric, Ranger or Paladin?')
    classtoplay = input('>>> ')
    character = dict()
    if classtoplay.lower() == 'mage':
        character['stats'] = c.mage()
    elif classtoplay.lower() == 'warrior':
        character['stats'] = c.warrior()
    elif classtoplay.lower() == 'fighter':
        character['stats'] = c.fighter()
    elif classtoplay.lower() == 'cleric':
        character['stats'] = c.cleric()
    elif classtoplay.lower() == 'ranger':
        character['stats'] = c.ranger()
    elif classtoplay.lower() == 'paladin':
        character['stats'] = c.paladin()
    else:
        start()

    announce('Ah, a {classtoplay}. What shall we call you?'.format(classtoplay=classtoplay))
    character['name'] = input('>>> ')
    character['stats']['health'] = math.floor(character['stats']['vitality'] -
        .15 * character['stats']['vitality'])
    character['experience'] = 0
    character['level'] = 1
    character['type'] = classtoplay.lower()

    announce('Here are your stats, {name}..\n'.format(name=character['name']))
    for k, v in character['stats'].items():
        announce('\t{stat}: {value}'.format(stat=k, value=v))

    env = Environments(level=character['level'])
    environment = env.dungeon()
    announce("You've entered a {env}! Clear out all of the enemies!".format(env=environment['name']))

    shuffle(environment['mobs'])
    for mob in environment['mobs']:
        announce('Uh-oh! {mobname} attacks!'.format(mobname=mob['name']))
        if mob['name'] == 'Bat':
            with open('art/bat.txt', mode='r') as f:
                print(f.read())
        elif mob['name'] == 'Skeleton':
            with open('art/skeleton.txt', mode='r') as f:
                print(f.read())
        fight(character, mob)

    announce("\nYou've cleared out all of the enemies, now its time for the boss!")
    if environment['boss']['name'] == 'Ogre':
        with open('art/ogre.txt', mode='r') as f:
            print(f.read())
    fight(character, environment['boss'])
コード例 #2
0
def evaluate(name, environment, n=0, uncertainty=0):
    disablePrint()
    name = name + '-' + str(n)
    agent = pickle.load(
        open(f"outputs/{'-'.join(name.split('-')[:-1])}/Agents/{name}.agent",
             "rb"))
    agent.explore = agent.exploration.greedy
    agent.uncertainty = True
    agent.state_avoidance = False
    agent.uncertainty_weight = uncertainty
    env = Environments(render=False,
                       envs=[environment for _ in range(20)],
                       agent=agent)
    rews, dones = [], []
    for i in range(20000):
        obs, hn, cn = env.start()
        act, obs_old, h0, c0, hn, cn, _, _ = agent.chooseMulti(obs, hn, cn)
        obs, rew, done, info = env.step(act, hn, cn)
        rews.append(sum(rew))
        dones.append(sum(done))
    enablePrint()
    score = sum(rews) / sum(dones)
    print(
        name.ljust(20, ' '),
        int(100 * (score - rMin[environment]) /
            (rMax[environment] - rMin[environment])) / 100, "  ", score)
コード例 #3
0
 def main():
     name, environment, hours, total_agents, done = params['name'], params['environment'], params['hours'], params['total_agents'], None
     agent = Agent(**params)
     env = Environments(render=False, envs=[environment for _ in range(total_agents)], agent=agent)
     collector = Collector(**params)
     tid, f = time() + 3600 * hours - 300, 0
     while time() < tid:
         f += 1
         obs, hn, cn = env.start()
         act, obs_old, h0, c0, hn, cn, before_trace, after_trace = agent.chooseMulti(obs, hn, cn, done=done)
         obs, rew, done, info = env.step(act, hn, cn)
         collector.collect(rew, done, act, agent.onpolicy)
         if not agent.onpolicy and f > 10:
             agent.rememberMulti(obs_old, act, obs, rew, h0, c0, hn, cn, done, before_trace, after_trace)
         agent.learn()
     saveAgent(agent, name)
     saveCollector(collector, name)
コード例 #4
0
    def GetPlatform(returnName=False):
        """Returns the platform that XBMC returns as it's host:

        Keyword Arguments:
        returnName : boolean - If true a string value is returned

        Returns:
        A string representing the host OS:
        * linux   - Normal Linux
        * Xbox    - Native Xbox
        * OS X    - Apple OS
        * Windows - Windows OS
        * unknown - in case it's undetermined

        """

        if not EnvController.__CurrentPlatform:
            # let's cache the current environment as the call to the xbmc library is very slow.
            platform = Environments.Unknown
            # it's in the .\xbmc\GUIInfoManager.cpp
            if xbmc.getCondVisibility("system.platform.linux"):
                platform = Environments.Linux
            elif xbmc.getCondVisibility("system.platform.xbox"):
                platform = Environments.Xbox
            elif xbmc.getCondVisibility("system.platform.windows"):
                platform = Environments.Windows
            elif xbmc.getCondVisibility("system.platform.ios"):
                platform = Environments.IOS
            elif xbmc.getCondVisibility("system.platform.atv2"):
                platform = Environments.ATV2
            elif xbmc.getCondVisibility("system.platform.tvos"):
                platform = Environments.TVOS
            elif xbmc.getCondVisibility("system.platform.osx"):
                platform = Environments.OSX
            elif xbmc.getCondVisibility("system.platform.android"):
                platform = Environments.Android

            EnvController.__CurrentPlatform = platform
            Logger.Info("Current platform determined to be: %s",
                        Environments.Name(EnvController.__CurrentPlatform))

        if returnName:
            return Environments.Name(EnvController.__CurrentPlatform)
        else:
            return EnvController.__CurrentPlatform
コード例 #5
0
    def get_platform(return_name=False):
        """ Returns the platform that Kodi returns as it's host:

        * linux   - Normal Linux
        * UWP     - Windows Store App
        * OS X    - Apple OS
        * Windows - Windows OS
        * unknown - in case it's undetermined

        :param bool return_name:    If true a string value is returned
        :return: A string representing the host OS:
        :rtype: int|str

        """

        if not EnvController.__CurrentPlatform:
            # let's cache the current environment as the call to the Kodi library is very slow.
            platform = Environments.Unknown
            # it's in the .\xbmc\GUIInfoManager.cpp
            if xbmc.getCondVisibility("system.platform.linux"):
                platform = Environments.Linux
            elif xbmc.getCondVisibility("system.platform.uwp"):
                platform = Environments.UWP
            elif xbmc.getCondVisibility("system.platform.windows"):
                platform = Environments.Windows
            elif xbmc.getCondVisibility("system.platform.ios"):
                platform = Environments.IOS
            elif xbmc.getCondVisibility("system.platform.tvos"):
                platform = Environments.TVOS
            elif xbmc.getCondVisibility("system.platform.osx"):
                platform = Environments.OSX
            elif xbmc.getCondVisibility("system.platform.android"):
                platform = Environments.Android

            EnvController.__CurrentPlatform = platform
            Logger.info("Current platform determined to be: %s",
                        Environments.name(EnvController.__CurrentPlatform))

        if return_name:
            return Environments.name(EnvController.__CurrentPlatform)
        else:
            return EnvController.__CurrentPlatform
コード例 #6
0
    def __ValidateChannelInfo(self, channelInfo, platform):
        """ Checks if the value is valid for the current environment, if it is enabled and so on.

        @param channelInfo: The channel info meta data to check
        @param platform:    The platform to validate against

        @rtype : Boolean indicating the channel is valid. It might still be disabled from the settings.

        """

        if not channelInfo.guid:
            Logger.Error("Not loading: %s -> No guid present", channelInfo)
            return False

        if channelInfo in self.__allChannels:
            existingChannel = self.__allChannels[self.__allChannels.index(channelInfo)]
            Logger.Error("Not loading: %s -> a channel with the same guid already exist:\n%s.",
                         channelInfo, existingChannel)
            return False

        # store all the channels except the out of date and duplicate ones, we might need them somewhere
        self.__allChannels.append(channelInfo)

        if not channelInfo.compatiblePlatforms & platform == platform:
            Logger.Warning("Not loading: %s -> platform '%s' is not compatible", channelInfo,
                           Environments.Name(platform))
            return False

        # now it is a valid channel for this platform.
        self.__validChannels.append(channelInfo)

        if not (AddonSettings.ShowChannel(channelInfo) and AddonSettings.ShowChannelWithLanguage(
                channelInfo.language)):
            Logger.Warning("Not loading: %s -> Channel was disabled from settings.", channelInfo)
            return True

        Logger.Debug("Loading: %s", channelInfo)

        # add to channelPath list
        self.__enabledChannels.append(channelInfo)
        return True
コード例 #7
0
        x = self.decoder(x)
        return x


total_agents, display_every = 20, 5000
agent = Agent(memory=50000,
              discount=0.995,
              uncertainty=False,
              update_every=100,
              double=True,
              use_distribution=False,
              reward_normalization=True)
env = Environments(render=True,
                   envs=[
                       'bigfish', 'bossfight', 'caveflyer', 'chaser',
                       'climber', 'coinrun', 'dodgeball', 'fruitbot', 'heist',
                       'jumper', 'leaper', 'maze', 'miner', 'ninja', 'plunder',
                       'starpilot'
                   ],
                   agent=agent)
network = NetWork().to(device)
print("Number of parameters in network:", count_parameters(network))
print("Number of parameters in encoder:", count_parameters(network.encoder))
print("Number of parameters in decoder:", count_parameters(network.decoder))
criterion = MSELoss()
optimizer = Adam(network.parameters(), lr=1e-4, weight_decay=1e-5)
for f in range(0, 10000000):
    obs, hn, cn = env.start()
    act, obs_old, h0, c0, hn, cn = agent.chooseMulti(obs, hn, cn)
    obs, rew, done, info = env.step(act, hn, cn)
    agent.rememberMulti(obs_old, act, obs, rew, h0, c0, hn, cn, done)
    obs, action, obs_next, reward, h0, c0, hn, sn, done = agent.memory.sample(
コード例 #8
0
    def get_channels(self, include_disabled=False, **kwargs):  # NOSONAR
        """ Retrieves all enabled channels within Retrospect.

        If updated channels are found, the those channels are indexed and the
        channel index is rebuild.

        :param bool include_disabled:   Boolean to indicate if we should include those channels
                                        that are explicitly disabled from the settings.
        :param dict kwargs:             Here for backward compatibility.

        :return: a list of ChannelInfo objects of enabled channels.
        :rtype: list[ChannelInfo]

        """

        sw = StopWatch("ChannelIndex.get_channels Importer", Logger.instance())
        Logger.info("Fetching all enabled channels.")

        self.__allChannels = []
        valid_channels = []

        # What platform are we
        platform = envcontroller.EnvController.get_platform()

        channels_updated = False
        country_visibility = {}

        for channel_set in self.__channelIndex[self.__CHANNEL_INDEX_CHANNEL_KEY]:
            channel_set = self.__channelIndex[self.__CHANNEL_INDEX_CHANNEL_KEY][channel_set]
            channel_set_info_path = channel_set[self.__CHANNEL_INDEX_CHANNEL_INFO_KEY]
            channel_set_version = channel_set[self.__CHANNEL_INDEX_CHANNEL_VERSION_KEY]

            # Check if file exists. If not, rebuild index
            if not os.path.isfile(channel_set_info_path) and not self.__reindexed:
                Logger.warning("Missing channelSet file: %s.", channel_set_info_path)
                self.__rebuild_index()
                return self.get_channels()

            channel_infos = ChannelInfo.from_json(channel_set_info_path, channel_set_version)

            # Check if the channel was updated
            if self.__is_channel_set_updated(channel_infos[0]):
                # let's see if the index has already been updated this section, of not, do it and
                # restart the ChannelRetrieval.
                if not self.__reindexed:
                    # rebuild and restart
                    Logger.warning("Re-index channel index due to channelSet update: %s.", channel_set_info_path)
                    self.__rebuild_index()
                    return self.get_channels()
                else:
                    Logger.warning("Found updated channelSet: %s.", channel_set_info_path)

                if not channels_updated:
                    # this was the first update found (otherwise channelsUpdated was True) show a message:
                    title = LanguageHelper.get_localized_string(LanguageHelper.InitChannelTitle)
                    text = LanguageHelper.get_localized_string(LanguageHelper.InitChannelText)
                    XbmcWrapper.show_notification(title, text, display_time=15000, logger=Logger.instance())
                channels_updated |= True

                # Initialise the channelset.
                self.__initialise_channel_set(channel_infos[0])

                # And perform all first actions for the included channels in the set
                for channel_info in channel_infos:
                    self.__initialise_channel(channel_info)

            # Check the channel validity
            for channel_info in channel_infos:
                if not self.__channel_is_correct(channel_info):
                    continue
                self.__allChannels.append(channel_info)

                # valid channel for this platform ?
                if not channel_info.compatiblePlatforms & platform == platform:
                    Logger.warning("Not loading: %s -> platform '%s' is not compatible.",
                                   channel_info, Environments.name(platform))
                    continue
                valid_channels.append(channel_info)

                # was the channel hidden based on language settings? We do some caching to speed
                # things up.
                if channel_info.language not in country_visibility:
                    country_visibility[channel_info.language] = AddonSettings.show_channel_with_language(channel_info.language)
                channel_info.visible = country_visibility[channel_info.language]

                # was the channel explicitly disabled from the settings?
                channel_info.enabled = AddonSettings.get_channel_visibility(channel_info)

                Logger.debug("Found channel: %s", channel_info)

        if channels_updated:
            Logger.info("New or updated channels found. Updating add-on configuration for all channels and user agent.")
            AddonSettings.update_add_on_settings_with_channels(valid_channels, Config)
            AddonSettings.update_user_agent()
        else:
            Logger.debug("No channel changes found. Skipping add-on configuration for channels.")
            # TODO: perhaps we should check that the settings.xml is correct and not broken?

        valid_channels.sort(key=lambda c: c.sort_key)
        visible_channels = [ci for ci in valid_channels if ci.visible and ci.enabled]
        Logger.info("Fetch a total of %d channels of which %d are visible.",
                    len(valid_channels),
                    len(visible_channels))

        sw.stop()

        if include_disabled:
            return valid_channels

        return visible_channels
コード例 #9
0
    if keyboard.Key.f3 == key:
        save = True


keyboard.Listener(on_press=on_press).start()

total_agents, display_every = 20, 5000
agent = Agent(memory=40000,
              discount=0.995,
              uncertainty=False,
              update_every=100,
              double=True,
              use_distribution=False,
              reward_normalization=False)
env = Environments(render=True,
                   envs=['maze' for _ in range(total_agents)],
                   agent=agent)
collector = Collector(calculate_every=500, total_agents=total_agents)
for f in range(10000000):
    obs, hn, cn = env.start()
    act, obs_old, h0, c0, hn, cn = agent.chooseMulti(obs, hn, cn)
    obs, rew, done, info = env.step(act, hn, cn)
    collector.collect(rew, done, act)
    agent.rememberMulti(obs_old, act, obs, rew, h0, c0, hn, cn, done)
    agent.learn()

    if showPrint:
        plt.close('all')
        displayer(obs[0].cpu(), agent, collector)
        fig = plt.figure()
        move_figure(fig, 0, 0)
コード例 #10
0
# env.close()
# obs = clean(env.reset())
# hn = torch.zeros(1, 1, hidden_size, device=device)
# cn = torch.zeros(1, 1, hidden_size, device=device)
# disablePrint()
# t0 = time.time()
# obs, hn, cn = [obs for _ in range(k)], [hn for _ in range(k)], [cn for _ in range(k)]
# for i in range(n // k):
#     agent.chooseMulti(obs, hn, cn)
# t1 = time.time()
# enablePrint()
# print("Choose", t1 - t0)  # 17.568519115447998


agent = Agent()
env = Environments(render=True, envs=['fruitbot' for _ in range(20)])
all_return, all_dones = [], []
update_every = 100
disablePrint()
frames = 1000000
dones, total_rew = 0, 0
for f in range(1, frames + 1):
    obs, hn, cn = env.start()
    act, obs_old, h0, c0, hn, cn = agent.chooseMulti(obs, hn, cn)
    obs, rew, done, info = env.step(act, hn, cn)
    total_rew += sum(rew) / len(rew)
    dones += sum(done) / len(done)
    agent.rememberMulti(obs_old, act, obs, rew, h0, c0, hn, cn, done)
    if f > update_every:
        for _ in range(2):
            agent.learn(double=True)
コード例 #11
0
 def __init__(self):
     Environments.__init__(self, "river")
     Identifiable.__init__(self)
コード例 #12
0
 def __init__(self):
     Environments.__init__(self, "swamp")
     Identifiable.__init__(self)
コード例 #13
0
    def GetChannels(self, includeDisabled=False, **kwargs):
        # type: (object) -> list
        """ Retrieves all enabled channels within Retrospect.

        If updated channels are found, the those channels are indexed and the
        channel index is rebuild.

        @type kwargs: here for backward compatibility

        @return: a list of ChannelInfo objects of enabled channels.

        """

        sw = StopWatch("ChannelIndex.GetChannels Importer", Logger.Instance())
        Logger.Info("Fetching all enabled channels.")

        self.__enabledChannels = []
        self.__allChannels = []
        self.__validChannels = []

        # What platform are we
        platform = envcontroller.EnvController.GetPlatform()

        channelsUpdated = False
        for channelSet in self.__channelIndex[self.__CHANNEL_INDEX_CHANNEL_KEY]:
            channelSet = self.__channelIndex[self.__CHANNEL_INDEX_CHANNEL_KEY][channelSet]
            channelSetInfoPath = channelSet[self.__CHANNEL_INDEX_CHANNEL_INFO_KEY]
            channelSetVersion = channelSet[self.__CHANNEL_INDEX_CHANNEL_VERSION_KEY]

            # Check if file exists. If not, rebuild index
            if not os.path.isfile(channelSetInfoPath) and not self.__reindexed:
                Logger.Warning("Missing channelSet file: %s.", channelSetInfoPath)
                self.__RebuildIndex()
                return self.GetChannels()

            channelInfos = ChannelInfo.FromJson(channelSetInfoPath, channelSetVersion)

            # Check if the channel was updated
            if self.__IsChannelSetUpdated(channelInfos[0]):
                # let's see if the index has already been updated this section, of not, do it and
                # restart the ChannelRetrieval.
                if not self.__reindexed:
                    # rebuild and restart
                    Logger.Warning("Re-index channel index due to channelSet update: %s.", channelSetInfoPath)
                    self.__RebuildIndex()
                    return self.GetChannels()
                else:
                    Logger.Warning("Found updated channelSet: %s.", channelSetInfoPath)

                if not channelsUpdated:
                    # this was the first update found (otherwise channelsUpdated was True) show a message:
                    title = LanguageHelper.GetLocalizedString(LanguageHelper.InitChannelTitle)
                    text = LanguageHelper.GetLocalizedString(LanguageHelper.InitChannelText)
                    XbmcWrapper.ShowNotification(title, text, displayTime=15000, logger=Logger.Instance())
                channelsUpdated |= True

                # Initialise the channelset.
                self.__InitialiseChannelSet(channelInfos[0])

                # And perform all first actions for the included channels in the set
                for channelInfo in channelInfos:
                    self.__InitialiseChannel(channelInfo)

            # Check the channel validity
            for channelInfo in channelInfos:
                if not self.__ChannelIsCorrect(channelInfo):
                    continue
                self.__allChannels.append(channelInfo)

                # valid channel for this platform ?
                if not channelInfo.compatiblePlatforms & platform == platform:
                    Logger.Warning("Not loading: %s -> platform '%s' is not compatible.",
                                   channelInfo, Environments.Name(platform))
                    continue
                self.__validChannels.append(channelInfo)

                # was the channel disabled?
                if not (AddonSettings.ShowChannel(
                        channelInfo) and AddonSettings.ShowChannelWithLanguage(
                        channelInfo.language)):
                    Logger.Warning("Not loading: %s -> Channel was disabled from settings.",
                                   channelInfo)
                    continue
                self.__enabledChannels.append(channelInfo)

                Logger.Debug("Loading: %s", channelInfo)

        if channelsUpdated:
            Logger.Info("New or updated channels found. Updating add-on configuration for all channels and user agent.")
            AddonSettings.UpdateAddOnSettingsWithChannels(self.__validChannels, Config)
            AddonSettings.UpdateUserAgent()
        else:
            Logger.Debug("No channel changes found. Skipping add-on configuration for channels.")
            # TODO: perhaps we should check that the settings.xml is correct and not broken?

        self.__enabledChannels.sort()
        Logger.Info("Fetch a total of %d channels of which %d are enabled.",
                    len(self.__allChannels),
                    len(self.__enabledChannels))

        sw.Stop()
        if includeDisabled:
            return self.__validChannels
        return self.__enabledChannels
コード例 #14
0
 def __init__(self):
     Environments.__init__(self, "mountain")
     Identifiable.__init__(self)
コード例 #15
0
 def __init__(self):
     Environments.__init__(self, "grassland")
     Identifiable.__init__(self)
コード例 #16
0
 def __init__(self):
     Environments.__init__(self, "coastline")
     Identifiable.__init__(self)
コード例 #17
0
 def __init__(self):
     Environments.__init__(self, "forest")
     Identifiable.__init__(self)