コード例 #1
0
    def _choose_block(self):
        """Choose the next block for the path.

        If any bound has been crosed, make a turn. Return
        straight block otherwise.

        Returns:
            str: Chosen block name.
        """
        for bound in self._bounds:
            if self._prev_bound != bound:
                if bound.is_crossed(self._prev, self.current):
                    self._step, model = bound.make_turn(self._prev_bound)
                    self._prev_bound = bound
                    return model

        if self._station_threshold <= 0 and chance(30):
            self._station_threshold = 83
            return "station"

        if self._city_threshold <= 0 and chance(50):
            self._city_threshold = 205
            return "city"

        return random.choice(("rs", "ls")) if chance(10) else "direct"
コード例 #2
0
def gen_servername(test_mode=False):
    server_labels = []

    if chance(parameters.frequency['servername_use_www']):
        server_labels.append('www')

    # Append at least one hostname
    server_labels.append(gen_hostname())

    if chance(parameters.frequency['servername_multiple_labels']):
        for _ in range(
                random.randint(0, parameters.max_val['servername_labels'])):
            # Keeping track of how long the servername currently is
            server_len = len(''.join(server_labels))

            if server_len < MAX_SERVER_CHARS:
                label = gen_hostname()

                # If there's room for this label, append it
                if server_len + len(label) < MAX_SERVER_CHARS:
                    server_labels.append(label)

    server_labels.append(
        chance_choose(
            'com',
            chance_choose(random.choice(common_tlds), random.choice(all_tlds),
                          parameters.frequency['servername_common_tld']),
            parameters.frequency['serverame_dot_com']))

    return '.'.join(server_labels)
コード例 #3
0
    def comment(self, roll=1):
        if not self.ready:
            log.info("comments need to be initialized")
            self.init()

        if chance(roll):
            log.info("going to make a comment")

            # keep searching posts until we find one with comments
            post_with_comments = False
            while not post_with_comments:
                # pick a subreddit to comment on
                subreddit = get_subreddit(getsubclass=True)
                # get a random hot post from the subreddit
                post = random.choice(list(subreddit.hot()))
                # replace the "MoreReplies" with all of the submission replies
                post.comments.replace_more(limit=0)

                if len(post.comments.list()) > 0:
                    post_with_comments = True

            # choose if we're replying to the post or to a comment
            if chance(self.config.get('reddit_reply_to_comment')):
                # reply to the post with a response based on the post title
                log.info('replying directly to post')
                post.reply(self.comments.get_reply(post.title))
            else:
                # get a random comment from the post
                comment = random.choice(post.comments.list())
                # reply to the comment
                log.info('replying to comment')
                comment.reply(self.comments.get_reply(comment.body))
コード例 #4
0
ファイル: shape.py プロジェクト: afreewill333/PolygonPainter
	def mutate(self, major=False):
		commands = []
		if chance(10):
			if chance(1):
				commands.append(Shape.RemovePointCommand(self))
			else:
				commands.append(Shape.InsertPointCommand(self))
		else:
			commands.append(Shape.MovePointCommand(self, isMajor=major))
		commands.append(Shape.RebuildCommand(self))
		return commands
コード例 #5
0
 def mutate(self, major=False):
     commands = []
     if chance(10):
         if chance(1):
             commands.append(Shape.RemovePointCommand(self))
         else:
             commands.append(Shape.InsertPointCommand(self))
     else:
         commands.append(Shape.MovePointCommand(self, isMajor=major))
     commands.append(Shape.RebuildCommand(self))
     return commands
コード例 #6
0
    def _choose_branch_block(self):
        """Generate a world block for a branch.

        There are no turns, nor cities on branch railways.
        """
        self._station_threshold -= 1

        if self._station_threshold <= 0 and chance(30):
            self._station_threshold = 93
            return "station"

        return random.choice(("rs", "ls")) if chance(10) else "direct"
コード例 #7
0
    async def on_message(self, message):
        if self.bot.user.id == message.author.id:
            # Do not respond to self
            return

        message_author_ids = set()
        message_content = set()
        async for past_message in message.channel.history(limit=REPLY_CHAIN_LENGTH):
            # Contribute to message chains
            message_author_ids.add(past_message.author.id)
            message_content.add(past_message.content)

        if len(message_content) == 1 and len(message_author_ids) >= REPLY_CHAIN_LENGTH:
            return await message.channel.send(message_content.pop())

        if chance(2 / 3):
            # Chance to say ooo 😂
            return await message.channel.send("ooo :joy:")

        # if "AAA" in message.content.upper():
        #     """ Scream in response to screams """
        #     return await message.channel.send(generate_scream())

        if "eggs benedict" in message.content.upper():
            # Say "ooo 😂" in response to "eggs benedict", per aquaa's request
            return await message.channel.send("ooo :joy:")

        if "EEE" in message.content.upper():
            # Screech in response to screeches
            return await message.channel.send(generate_screech())

        if "@someone" in message.content:
            # @someone: ping random user
            random_member = random.choice(message.guild.members)
            return await message.channel.send(random_member.mention)
コード例 #8
0
    def act(self, last_reward, next_observation):
        # Update model based on last_reward:

        one_hot_obs = self._preprocess(next_observation)

        if self._last_obs is not None:
            target = last_reward + self._discount * self._target_network.predict(
                one_hot_obs).max()
            target_vec = self._target_network.predict(self._last_obs)
            target_vec[0, self._last_action] = target
            self._prediction_network.train_on_batch(self._last_obs, target_vec)
            self._unsaved_history['observation'].append(self._last_obs[0])
            self._unsaved_history['action'].append(self._last_action)
            self._unsaved_history['reward'].append(last_reward)
            self._unsaved_history['next_observation'].append(one_hot_obs[0])

        # Now, choose next action, and store last_* info for next iteration
        self._last_obs = one_hot_obs
        if chance(self._epsilon):
            self._last_action = np.random.randint(len(ACTIONS))
        else:
            self._last_action = self._prediction_network.predict(
                one_hot_obs).argmax()

        # Update epsilon after using it for chance
        # Increment counter for target update
        self._iters_since_target_update += 1
        self._maybe_update_pn()

        return ACTIONS[self._last_action]
コード例 #9
0
ファイル: block.py プロジェクト: IlyaFaer/ForwardOnlyGame
    def _gen_env_mods(self, vertices):
        """Randomly select and arrange environment models.

        Args:
            vertices (list): Vertices of the terrain model.

        Returns:
            list:
                Lists in which the first element is an environment
                model name, and the second is its position.
        """
        models = []
        et_suf = "et_" if self.enemy_territory else ""

        for models_conf in LOCATION_CONF[et_suf + "with_quantity"]:
            for _ in range(random.randint(*models_conf["quantity"])):
                models.append((
                    random.choice(models_conf["models"]),
                    take_random(vertices[models_conf["square"]]),
                ))
        for models_conf in LOCATION_CONF[et_suf + "with_chance"]:
            if chance(models_conf["chance"]):
                models.append((
                    random.choice(models_conf["models"]),
                    take_random(vertices[models_conf["square"]]),
                ))
        return models
コード例 #10
0
ファイル: character.py プロジェクト: IlyaFaer/ForwardOnlyGame
    def _missed_shot(self):
        """Calculate if character missed the current shot.

        Returns:
            bool: True if character missed, False otherwise.
        """
        miss_chance = 0
        if self.class_ == "soldier":
            if (
                abs(self._target.node.getX()) < 0.56
                and abs(self._target.node.getY()) < 0.95
            ):
                miss_chance += 20
        elif self.class_ == "raider":
            if (
                abs(self._target.node.getX()) > 0.56
                and abs(self._target.node.getY()) > 0.95
            ):
                miss_chance += 20

        if base.world.sun.is_dark:  # noqa: F821
            if base.labels.TRAITS[1][0] in self.traits:  # noqa: F821
                # Cat eyes
                miss_chance -= 5
            elif base.train.lights_on:  # noqa: F821
                if "Floodlights" not in base.train.upgrades:  # noqa: F821
                    miss_chance += 10
            else:
                miss_chance += 20

        miss_chance += (100 - self.energy) // 5
        if self._team.cover_fire:
            miss_chance = min(100, max(0, miss_chance - 25))

        return chance(miss_chance)
コード例 #11
0
ファイル: block.py プロジェクト: IlyaFaer/ForwardOnlyGame
    def _gen_railways_model(self):
        """Select railways model and generate its coordinates.

        Returns:
            list: Railways model name, x and y coords, angle.
        """
        if (self.name != "direct" or chance(83) or self.enemy_territory
                or self.is_station):
            return

        model = random.choice((
            "arch1",
            "sign1",
            "sign2",
            "sign3",
            "light_post{}".format(random.randint(1, 2)),
            "lamp_post1",
            "transparant1",
        ))
        if model in ("arch1", "transparant1"):
            coor = 0
        else:
            coor = random.choice((0.15, -0.15))

        if model == "lamp_post1" and coor > 0:
            angle = 180
        else:
            angle = 0

        return (address(model), (coor, random.randint(0, 8)), angle)
コード例 #12
0
    def __init__(self, id_, class_, class_data, model, y_positions,
                 enemy_handler):
        EnemyUnit.__init__(self, id_, class_, class_data, model, y_positions,
                           enemy_handler)
        if chance(50):
            taskMgr.doMethodLater(  # noqa: F821
                random.randint(26, 28), self._play_idle_anim,
                self.id + "_idle")
            self._cry_snd = base.sound_mgr.loadSfx(  # noqa: F821
                "sounds/combat/enemy_cry{num}.ogg".format(
                    num=random.randint(1, 3)))
            self._cry_snd.setVolume(0.4)
            base.sound_mgr.attachSoundToObject(self._cry_snd,
                                               self.model)  # noqa: F821
        else:
            self._cry_snd = None

        taskMgr.doMethodLater(  # noqa: F821
            random.randint(27, 29),
            base.world.play_fight_music,  # noqa: F821
            "play_music",
        )
        self._col_node = self._init_col_node(SHOT_RANGE_MASK, MOUSE_MASK,
                                             CollisionSphere(0, 0, 0.05, 0.05))
        base.common_ctrl.traverser.addCollider(  # noqa: F821
            self._col_node, enemy_handler)
        self._explosion = base.effects_mgr.explosion(self)  # noqa: F821
コード例 #13
0
    async def on_message(self, message):
        message_authorIDs = set()
        message_content = set()
        async for m in message.channel.history(limit=REPLY_CHAIN_LENGTH):
            """ Contribute to message chains """
            message_authorIDs.add(m.author.id)
            message_content.add(m.content)

        if self.bot.user.id in message_authorIDs:
            """ Do not reply to self """
            return

        if len(message_content
               ) == 1 and len(message_authorIDs) >= REPLY_CHAIN_LENGTH:
            return await message.channel.send(message_content.pop())

        if chance(2):
            """ Chance to say a funny """
            function = random.choice(
                [generate_scream, generate_screech, ooojoy])
            text = function()
            return await message.channel.send(text)

        #if "AAA" in message.content.upper():
        #    """ Scream in response to screams """
        #    return await message.channel.send(generate_scream())

        if "EEE" in message.content.upper():
            """ Screech in response to screeches """
            return await message.channel.send(generate_screech())

        if "@someone" in message.content:
            """ @someone: ping random user """
            member = random.choice(message.channel.members)
            return await message.channel.send(f"<@{member.id}>")
コード例 #14
0
    def _choose_target(self, task):
        """Choose a character/Train as a target.

        Character will be chosen from the list of
        characters set to the TrainPart, in which
        range this enemy is now.
        """
        if self.current_part.is_covered:
            if self._target != base.train:  # noqa: F821
                self._target = base.train  # noqa: F821

                # (re-)start shooting
                self._stop_tasks("_shoot")
                taskMgr.doMethodLater(  # noqa: F821
                    0.5, self._shoot, self.id + "_shoot")
        else:
            targets = self.current_part.chars + [base.train]  # noqa: F821

            if self._target not in targets or chance(5):
                self._target = random.choice(targets)

                # (re-)start shooting
                self._stop_tasks("_shoot")
                taskMgr.doMethodLater(  # noqa: F821
                    0.5, self._shoot, self.id + "_shoot")

        task.delayTime = 0.5
        return task.again
コード例 #15
0
ファイル: player.py プロジェクト: Mojimoe/AdventureBot
    def embark(self):

        message = ""
        self.roll()
        try:
            if self.next is not None:
                # QUEST CHAIN
                adventure_instance = world.get_adventure(self.next)
                self.next = None
                message = self.run_adventure(adventure_instance)
            elif self.wounded:
                # Handle wounded
                message = self.run_hospital()
            elif self.wants_to_visit_shop() and utils.chance(1 / 3):
                # Handle shop
                message = self.run_shop()
            else:
                # Handle default.
                category = self.get_valid_category()
                adventure_instance = self.get_valid_adventure_from_category(
                    category)
                message = self.run_adventure(adventure_instance)

            self.schedule_next_adventure()
            return message
        except Exception as e:
            utils.log_exception(e)
            return None
コード例 #16
0
    async def react_to_words(self, ctx: commands.Context):
        """
        React to words by chance.
        Example: If someone types out "FRIDAY", the bot will has a chance
         to reply with a friday smiley.
        """
        chances_dict_setting = self.db.Setting("random_reactions_chances")
        chances_dict: Optional[Dict[str, int]] = None

        random_reaction_words = (self.db.get_global_default_setting(
            "random_reactions_chances").keys())

        smiley_emojis = []
        regex_pattern = '|'.join(fr'(?:\b{word}\b)'
                                 for word in random_reaction_words)
        reaction_words = (match.group().lower() for match in re.finditer(
            regex_pattern, ctx.message.content, re.IGNORECASE))

        for random_reaction_name in iter_unique_values(reaction_words):
            # Read random_reactions_chances setting if not read yet
            chances_dict = chances_dict or await chances_dict_setting.read()
            chances = chances_dict[random_reaction_name]

            if not chance(chances):
                continue

            smiley_emojis.append(
                self.get_smiley_reaction_emoji(random_reaction_name))

        if smiley_emojis:
            await self.send_smileys_based_on_mode(ctx,
                                                  smiley_emojis,
                                                  always_no_title=True)
コード例 #17
0
ファイル: block.py プロジェクト: IlyaFaer/ForwardOnlyGame
    def prepare_physical_objects(self):
        """Prepare physical objects on this block.

        This method must be called only after reparenting
        the main rails_mod node of the block. Otherwise
        all the children physical nodes will be positioned
        relative to the game render.
        """
        if (self.enemy_territory
                and base.world.enemy.score >= BARRIER_THRESHOLD  # noqa: F821
                and chance(2)):
            self._phys_objs.append(Barrier(self))

        if (self.enemy_territory
                and base.world.enemy.score >= ROCKET_THRESHOLD  # noqa: F821
                and chance(2)):
            Rocket()
コード例 #18
0
    def scream(self, message):
        message = message.lower()
        scrms = [c.action(message)['text'] for c in self._other_commands] + self._screams

        def react():
            for t in self._triggers:
                if any(map(lambda p: re.search(message, p), t.patterns)):
                    return t.probability, t.answer
            return 0, None

        probability, reply = react()

        if self.pattern in message or chance(probability):
            return wrap_t(reply or random.choice(scrms))
        elif chance(self._probability):
            return wrap_t(random.choice(scrms))
        else:
            return None
コード例 #19
0
    def _do_damage_to_train(self, task):
        """Deal machine gun damage to the Train."""
        if self.current_part.is_covered:
            if chance(40):
                base.train.get_damage(2)  # noqa: F821
        else:
            base.train.get_damage(2)  # noqa: F821

        base.train.get_shot(self._y_pos > 0)  # noqa: F821
        return task.again
コード例 #20
0
    def _missed_shot(self):
        """Calculate if enemy missed the current shot.

        Returns:
            bool: True if enemy missed, False otherwise.
        """
        if self.current_part.is_covered:
            return chance(50)

        return False
コード例 #21
0
def generator(template=clf_string, test_mode=False):

    # These will be the final output strings.
    # We copy them instead of using joined lists to preserve
    # whitespace.
    generated, final_truth = [], []

    # Split into a list of characters
    elements = list(template)
    for char in elements:
        replaced = char
        # If this section of the template string could not be replaced,
        # it will appear as question marks in the final ground
        # truth
        truth = string_to_field(replaced, '?')

        if char in fields:
            # Replace the field with its generated equivalent
            replaced = replaced.replace(char,
                                        str(fields[char](test_mode=test_mode)))

            # If the current character is a datetime, and the
            # format is not CLF
            if char == 't' and template != clf_string:
                # Reset replaced
                replaced = char

                # There's a 30% chance that the datetime will be
                # in ISO format
                replaced = replaced.replace(
                    char,
                    str(fields[char](
                        test_mode=test_mode,
                        use_iso=(chance(
                            parameters.frequency['use_iso_string'])))))

            truth = string_to_field(replaced, char)
        # It's valid for the current element to be whitespace only
        elif char == ' ':
            truth = string_to_field(replaced, '_')
        elif char == '[' or char == ']' or char == '"':
            truth = char
        else:
            print(
                "Failed to replace token %s. Please fix this part of your template string: %s."
                % (char, char))

        # Place the generated string and the truth string into their
        # respective outputs
        generated.append(replaced)
        final_truth.append(truth)

    # Return the generated string and the final truth, with all whitespace
    # replaced with underscores.
    return [''.join(generated), ''.join(final_truth)]
コード例 #22
0
def generate_screech() -> str:
    # Vanilla screech half the time
    if chance(50):
        return "E" * random.randint(1, 100)

    # One of these choices repeated 1-100 times
    body = "E" * random.randint(1, 100)

    # Chance to wrap the message in one of these Markdown strings
    formatter = "" if chance(50) else random.choice(["*", "**", "***"])

    # Chance to put an "R" at the beginning of the message
    prefix = "" if chance(50) else "R"

    # Example: "**REEEEEEEEEEEEEEEEEEE**"
    text = formatter + prefix + body + formatter

    if chance(50):
        text = text.lower()

    return text
コード例 #23
0
def generate_scream() -> str:
    # Vanilla scream half the time
    if chance(50):
        return "A" * random.randint(1, 100)

    # One of these choices repeated 1-100 times
    body = random.choice(["A", "O"]) * random.randint(1, 100)

    # Chance to wrap the message in one of these Markdown strings
    formatter = "" if chance(50) else random.choice(["*", "**", "***"])

    # Chance to put one of these at the end of the message
    suffix = "" if chance(50) else random.choice(["H", "RGH"])

    # Example: "**AAAAAAAAAAAARGH**"
    text = formatter + body + suffix + formatter

    if chance(50):
        text = text.lower()

    return text
コード例 #24
0
    def repost(self, roll=1, subreddit=None):
        if chance(roll):
            log.info("running repost")
            # log.info("running _repost")
            post = self.get_post(subreddit=subreddit)
            if not post: return
            api_call = requests.get(post.url).status_code
            if api_call != 200:
                if api_call == 429:
                    print('too many requests to pushshift')
                    s(random.uniform(3, 8))
                else:
                    print('pushshift http error: ' + str(api_call))
                return
            else:
                log.info(f"reposting post: {post.id}")

                if post.is_self:
                    if post.selftext not in ('[removed]',
                                             '[deleted]') and bool(
                                                 re.findall(
                                                     r'20[0-9][0-9]|v.redd.it',
                                                     post.selftext)) == False:
                        params = {
                            "title": edit_text(post.title, 'title'),
                            "selftext": edit_text(post.selftext, 'body')
                        }
                    else:
                        print(
                            'Info: skipping post; it was malformed or date indicated'
                        )
                        # print(post.selftext)
                else:
                    params = {
                        "title": edit_text(post.title, 'title'),
                        "url": post.url
                    }

                sub = post.subreddit

                # randomly choose a potential subreddit to cross post
                if CONFIG['reddit_crosspost_enabled']:
                    sub = self.rapi.subreddit(self.crosspost(sub.display_name))
                try:
                    self.rapi.subreddit(sub.display_name).submit(**params)
                    return
                except (UnboundLocalError, TypeError):
                    pass
                except APIException as e:
                    log.info(f"REPOST ERROR: {e}")
                    return
        else:
            pass
コード例 #25
0
    def _float_move(self, task):
        """Make enemy floatly move along the Train."""
        if chance(80):
            shift = random.choice((-0.05, 0.05))
            if self._y_pos + shift in self._y_positions:
                self._y_positions.append(self._y_pos)
                self._y_pos = self._y_pos + shift
                self._y_positions.remove(self._y_pos)

        self._move(
            random.randint(3, 6), (self._y_pos, random.uniform(*self._x_range), 0)
        )
        task.delayTime = random.randint(7, 9)
        return task.again
コード例 #26
0
		def execute(self):
			self.oldValues = self.colour.getTuple()
			if chance(2):
				self.colour.initChannels()
			else:
				r = randint(0,4)
				if r == 0: 
					self.colour.r = randint(0, 255)
				elif r == 1: 
					self.colour.g = randint(0, 255)
				elif r == 2:
					self.colour.b = randint(0, 255)
				elif r == 3:
					self.colour.a = randint(config.TRANSPARENCY_MIN, config.TRANSPARENCY_MAX)
コード例 #27
0
    def _prepare_et_block(self):
        """Prepare an enemy territory block.

        Returns:
            world.block.Block: Prepared enemy territory block.
        """
        if self._et_blocks > 8:
            if not self._et_rusty_blocks and chance(3):
                self._et_rusty_blocks = random.randint(4, 8)

            if not self._et_stench_blocks and chance(2):
                self._et_stench_blocks = random.randint(4, 7)

        block = Block(
            name="direct",
            z_coor=0,
            z_dir=0,
            id_=-1,
            directions={},
            path=self._paths["direct"],
            cam_path=self._paths["cam_" + "direct"],
            surf_vertices=self._surf_vertices,
            enemy_territory=True,
            is_rusty=self._et_rusty_blocks > 0,
            is_stenchy=self._et_stench_blocks > 0,
        ).prepare()

        self._loaded_blocks.append(block)

        if self._et_rusty_blocks:
            self._et_rusty_blocks -= 1

        if self._et_stench_blocks:
            self._et_stench_blocks -= 1

        self._map.insert(self._block_num, block)
        return block
コード例 #28
0
def gen_random_template():
    keys = fields.keys()
    # Number of elements: 3 to max_fields_available
    elements = random.sample(keys, k=random.randint(3, len(keys)))
    pretty_elements = []
    for el in elements:
        pretty = el
        # There is a 70% chance that a `request` string is wrapped in quotes.
        # Otherwise, there is a 10% chance that it's wrapped in quotes.
        #
        # The idea is that, since in CLF format the request string `%r` is
        # wrapped in quotes, it has a 70% chance of being wrapped in quotes
        # in whatever random template is used. However, if the current character
        # is not the request string, say `%s` or `%h`, it only has a 10% chance
        # of being wrapped in quotes.
        wrap_in_quotes = chance(parameters.frequency['other_field_in_quotes'])

        # Using the logic in the comment above, we overwrite the chance that
        # the value is wrapped in quotes if it's a request string
        if el == 'r':
            wrap_in_quotes = chance(parameters.frequency['request_in_quotes'])

        if wrap_in_quotes:
            pretty = '"{}"'.format(pretty)

        # Like with quotations and the `request` string, there is a
        # 40% chance that a `datetime` string is wrapped in brackets.
        # Otherwise, there is a 5% chance that it's wrapped in brackets.
        #
        # This is based off of the sample logs from Ocatak on GitHub,
        # which has all datetime strings wrapped in square brackets.
        wrap_in_brackets = chance(
            parameters.frequency['other_field_in_brackets'])

        # Using the logic in the comment above, we overwrite the chance that
        # the value is wrapped in brackets if it's a datetime string
        if el == 't':
            wrap_in_brackets = chance(
                parameters.frequency['datetime_in_brackets'])

        if wrap_in_brackets:
            pretty = '[{}]'.format(pretty)

        # Randomly add extra whitespace 0% of the time
        if chance(parameters.frequency['extra_whitespace']):
            pretty = '{}{}'.format(
                pretty, ' ' *
                random.randint(0, parameters.max_val['extra_whitespace']))

        pretty_elements.append(pretty)

    # There's a 30% chance that the entire template will be
    # wrapped in quotation marks
    if chance(parameters.frequency['template_in_quotes']):
        return '"{}"'.format(' '.join(pretty_elements))

    return ' '.join(pretty_elements)
コード例 #29
0
    def __init__(self, birthday, father=None, mother=None):
        self.name = utils.name_generator()
        self.birthday = birthday
        self.deathday = None
        self.age = settings.HUMAN_BIRTH_AGE
        self.sex = random.choice(['M', 'F'])
        self.father = father
        self.mother = mother
        self.spouse = None
        self.position = mother.position if mother else utils.rand_pos(settings.WORLD_SIZE)
        self.mothered = 0

        if isinstance(father, Humanoid) and isinstance(mother, Humanoid):
            parent_vit = self._choose_parent().vitality
            parent_str = self._choose_parent().strength
            parent_int = self._choose_parent().intelligence

            self.vitality = random.choice(range(1, parent_vit + 2)) + (
                random.choice(range(0, parent_vit + 1)) if utils.chance(50) else 0
            )
            self.strength = random.choice(range(1, parent_str + 2)) + (
                random.choice(range(0, parent_str + 1)) if utils.chance(50) else 0
            )
            self.intelligence = random.choice(range(1, parent_int + 2)) + (
                random.choice(range(0, parent_int + 1)) if utils.chance(50) else 0
            )
        else:
            self.vitality = random.choice(range(1, self.stat_modifiers['vit']))
            self.strength = random.choice(range(1, self.stat_modifiers['str']))
            self.intelligence = random.choice(range(1, self.stat_modifiers['int']))

        self.hp = random.choice(range(1, self.stat_modifiers['hp'])) + self.vitality
        self.ap = random.choice(range(1, self.stat_modifiers['ap'])) + (
            int(self.strength * 0.5) + int(self.intelligence * 0.5)
        )
        self.hunger = random.choice(range(40, 70))
コード例 #30
0
    def plan_outing(self):
        """Generate an outing.

        Returns:
            str: if outing planned, None otherwise.
        """
        self._threshold -= 1

        if self._threshold <= 0:
            self._threshold = random.randint(18, 26)

            if self._prefered and chance(11):
                return self._prefered

            return random.choice(("Meet", "Enemy Camp", "Looting"))
コード例 #31
0
ファイル: crew.py プロジェクト: IlyaFaer/ForwardOnlyGame
    def _calc_cohesion(self, task):
        """Calculate the current crew cohesion.

        Relations between all the characters are tracked.
        While characters are staying together, cohesion
        between them increases. Total cohesion is calculated
        as a sum of all relations relatively to the number
        of all relations in the crew. Different unit classes
        have different cohesion factors.
        """
        for char1 in self.chars.values():
            for char2 in self.chars.values():
                if char1.id == char2.id:
                    continue

                rel_id = tuple(sorted([char1.id, char2.id]))
                factor = 1.35 if char1.current_part == char2.current_part else 1

                if (
                    base.labels.TRAITS[4][0]  # noqa: F821
                    in char1.traits + char2.traits
                    and char1.class_ != char2.class_
                ):
                    # Liberal
                    factor *= 1.15

                if rel_id in self._relations:
                    plus = COHESION_FACTORS[(char1.class_, char2.class_)] * factor
                    self._relations[rel_id] = min(100, plus + self._relations[rel_id])

                    # propagate traits from one character to another
                    if self._relations[rel_id] > 80 and chance(50):
                        pair = [char1, char2]
                        from_char = take_random(pair)
                        if from_char.traits:
                            trait = random.choice(from_char.traits)
                            if trait not in pair[0].traits and len(pair[0].traits) < 3:
                                pair[0].traits.append(trait)
                else:
                    self._relations[rel_id] = (
                        COHESION_FACTORS[(char1.class_, char2.class_)] * factor
                    )

        self._calc_total_cohesion()
        task.delayTime = 160
        return task.again
コード例 #32
0
ファイル: character.py プロジェクト: IlyaFaer/ForwardOnlyGame
    def get_sick(self, is_infect=False):
        """Calculations to get this character sick.

        The worse condition the character has the higher is the chance
        for him to get sick. Sick character has lower energy maximum,
        and all his positive traits are disabled until getting well.

        Args:
            is_infect (bool):
                True if the disease came from a
                character on the same Train part.
        """
        if self.is_diseased:
            return

        cond_percent = (self.energy + self.health) / (100 + self.class_data["health"])
        percent = (1 - cond_percent) * 30

        sick_chance = max(
            0,  # not less than zero
            (
                percent
                + (20 if is_infect else 0)
                # Immunity
                - (40 if base.labels.TRAITS[3][0] in self.traits else 0)  # noqa: F821
                # Weak immunity
                + (20 if base.labels.TRAITS[3][1] in self.traits else 0)  # noqa: F821
            ),
        )

        if chance(sick_chance):
            self.is_diseased = True
            self.get_well_score = 0

            for traits_pair in base.labels.TRAITS:  # noqa: F821
                if traits_pair[0] in self.traits:

                    self.traits.remove(traits_pair[0])
                    self.disabled_traits.append(traits_pair[0])

            taskMgr.doMethodLater(  # noqa: F821
                60, self.get_well, self.id + "_get_well"
            )
            taskMgr.doMethodLater(240, self.infect, self.id + "_infect")  # noqa: F821
            self.energy = min(self.energy, 80)
コード例 #33
0
 def shadow_check(self, roll=1):
     if chance(roll):
         log.info("performing a shadowban check")
         response = requests.get(
             f"https://www.reddit.com/user/{self.username}/about.json",
             headers={
                 'User-agent': f"hiiii its {self.username}"
             }).json()
         if "error" in response:
             if response["error"] == 404:
                 log.info(
                     f"account {self.username} is shadowbanned. poor bot :( shutting down the script..."
                 )
                 sys.exit()
             else:
                 log.info(response)
         else:
             log.info(f"{self.username} is not shadowbanned! We think..")
コード例 #34
0
ファイル: artist.py プロジェクト: afreewill333/PolygonPainter
	def mutate(self):
		commands = []
		if chance(2):
			r = randint(0, 5)
			if r == 0:
				commands.append(Artist.AddShapeCommand(self))
			elif r == 1:
				commands.append(Artist.RemoveShapeCommand(self))
			elif r == 2:
				commands.append(Artist.RemoveShapeCommand(self))
				commands.append(Artist.AddShapeCommand(self))
			else:
				commands.append(Artist.MoveShapeZCommand(self))
		elif len(self.shapes) > 0:
			shape = choice(self.shapes)
			r = randint(0, 12)
			if r <= 1:
				commands.append(shape.colour.mutate())
			elif r <= 7: 
				commands.extend(shape.mutate(major=True))
			else:
				commands.extend(shape.mutate(major=False))
		commands.append(Artist.RebuildCommand(self))
		return commands
コード例 #35
0
ファイル: lesmisgame.py プロジェクト: nick-hu/py-workspace
            print hpdisp + frdisp + xpdisp + '\n\n\n'  # Status display

            print utils.scenes[scid][0] + '\n\n'
            col = 0
            for opt in utils.scenes[scid][1]:  # Options
                let, letcol = choices[col][0], choices[col][1]
                print utils.color(let + '. ' + opt[0] + '\n', letcol, 1)
                col = col + 1

            while True:
                query = raw_input('\nAction [A/B/C/D]: ').upper()
                if query in 'ABCD' and len(query) == 1:
                    break

            act = utils.scenes[scid][1][index[query]][1]
            hp = hp + utils.chance(act[0], act[3])
            fr = fr + utils.chance(act[1], act[4])
            xp = xp + utils.chance(act[2], act[5])
            scid = act[6]

            debtcount = debtcount + 1 if fr <= 0 else 0
            if hp > 100:
                hp = 100
            if hp < 0:
                hp = 0

        score = xp + hp + fr
        print '\033[2J'
        print hpdisp + frdisp + xpdisp + '\n\n\n'

        if gamestate == 'l':