コード例 #1
0
 def test_cache(self):
     """Test that evaluation returns the same result on successive runs"""
     roll('6d(6d6)t')
     ast = Total(Dice(6, Dice(6, 6)))
     evals = [ast.evaluate_cached() for i in range(100)]
     assert len(set(evals)) == 1
     assert ast.evaluate_cached() is ast.evaluate_cached()
コード例 #2
0
ファイル: terrestrial.py プロジェクト: tolcreator/gurps_space
def GenerateDensity(mainType, subType):
    core = "Large"
    if mainType == "Tiny":
        if subType == "Ice" or subType == "Sulfur":
            core = "Icy"
        else:
            core = "Small"
    elif mainType == "Small":
        if subType == "Ice" or subType == "Hadean":
            core = "Icy"
        else:
            core = "Small"
    elif mainType == "Standard":
        if subType == "Hadean" or subType == "Ammonia":
            core = "Icy"
    elif mainType == "Large":
        if subType == "Ammonia":
            core == "Icy"

    r = dice.roll(3, 6)
    if core == "Large":
        initial = GetInitialLargeIronCoreDensity(r)
    elif core == "Small":
        initial = GetInitialSmallIronCoreDensity(r)
    else:
        initial = GetInitialIcyCoreDensity(r)
    r = dice.roll(1, 20) - 10
    var = float(r) / 200
    return initial + var   
コード例 #3
0
ファイル: terrestrial.py プロジェクト: tolcreator/gurps_space
def GenerateAtmosphericMass(mainType, subType):
    if mainType == "Small" and subType == "Ice":
        disqualified = False
    elif mainType == "Standard":
        if subType == "Hadean" or subType == "Chthonian":
            disqualified = True
        else:
            disqualified = False
    elif mainType == "Large":
        if subType == "Chthonian":
            disqualified = True
        else:
            disqualified = False
    else:
        disqualified = True
    if disqualified:
        return 0.0

    if mainType == "Standard" and subType == "Garden":
        r = dice.roll(3, 12) - 9
    else:
        r = dice.roll(3, 6)
    mass = float(r) / 10
    r = dice.roll(1, 20) - 10
    var = float(r) / 200
    return mass + var    
コード例 #4
0
ファイル: terrestrial.py プロジェクト: tolcreator/gurps_space
def GetAtmosphericPressure(mainType, subType, atmosphericMass, gravity):
    """ No Atmosphere """
    if mainType == "Tiny":
        return 0.0
    if mainType == "Small" and subType == "Hadean":
        return 0.0
    """ Trace Atmosphere """
    """ Gurps gives no means to work this out. """
    """ Just says it's less than 0.01 """
    if mainType == "Small" and subType == "Rock":
        r = dice.roll(1, 100) - 1
        return float(r) / 10000
    if mainType == "Standard" and subType == "Chthonian":
        r = dice.roll(1, 100) - 1
        return float(r) / 10000
    if mainType == "Large" and subType == "Chthonian":
        r = dice.roll(1, 100) - 1
        return float(r) / 10000

    if mainType == "Small" and subType == "Ice":
        PF = 10
    if mainType == "Standard":
        if subType == "Greenhouse":
            PF = 100
        else:
            PF = 1
    if mainType == "Large":
        if subType == "Greenhouse":
            PF = 500
        else:
            PF = 5
    
    return PF * atmosphericMass * gravity
コード例 #5
0
ファイル: terrestrial.py プロジェクト: tolcreator/gurps_space
def GenerateDiameter(mainType, blackBodyTemperature, density): 
    if mainType == "Large":
        minimum = 0.065
        maximum = 0.091
    elif mainType == "Standard":
        minimum = 0.030
        maximum = 0.065
    elif mainType == "Small":
        minimum = 0.024
        maximum = 0.030
    else:
        minimum = 0.004
        maximum = 0.024

    var = math.sqrt(blackBodyTemperature / density)
    myMin = minimum * var
    myMax = maximum * var
    step = (myMax - myMin) / 10

    r = dice.roll(2, 6) - 2
    step =  step * float(r)

    r = dice.roll(1, 20) - 10
    var = float(r) / 200
    step = step * (1.0 + var)

    return myMin + step
コード例 #6
0
ファイル: system.py プロジェクト: tolcreator/gurps_space
def GetWorldEccentricity(mod):
    r = dice.roll(3, 6) + mod
    upvar = 0.025
    downvar = 0.025
    if r <= 3:
        rough = 0.0
    elif r <= 6:
        rough = 0.05
    elif r <= 9:
        rough = 0.1
    elif r <= 11:
        rough = 0.15
    elif r <= 12:
        rough = 0.2
        upvar = 0.05
    elif r >= 18:
        rough = 0.8
        upvar = 0.05
        downvar = 0.05
    else:
        rough = float(r - 10) / 10
        upvar = 0.05
        downvar = 0.05
    r = dice.roll(1, 2)
    if r == 1:
        r = dice.roll(1, 100)
        upvar = (upvar / 100) * float(r)
        ret = rough + upvar
    else:
        r = dice.roll(1, 100)
        downvar = (downvar / 100) * float(r)
        ret = rough - downvar
    return max(ret, 0)
コード例 #7
0
ファイル: main.py プロジェクト: Ziul/DeDBot
def main():
    global logger
    # load the logging configuration
    real_path = os.path.dirname(os.path.realpath(__file__))
    logging.config.fileConfig(real_path + '/logging.ini')
    logger = logging.getLogger(__name__)

    # Get the dispatcher to register handlers
    updater = Updater(token="TOKEN")
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.addTelegramCommandHandler("start", start)
    dp.addTelegramCommandHandler("roll", Dice.roll)

    # log all errors
    dp.addErrorHandler(error)

    logger.info('Starting new bot')
    roll()
    # Start the Bot
    updater.start_polling()

    # Block until the you presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()
コード例 #8
0
ファイル: system.py プロジェクト: tolcreator/gurps_space
def GeneratePrimaryMass(brownDwarfFlag):
    """ Half of all stars are brown dwarfs """
    r = dice.roll(1, 6)
    if brownDwarfFlag and r <= 3:
        return GenerateBrownDwarfMass(0)
    f = dice.roll(3, 6)
    s = dice.roll(3, 6)
    return stellarMassTable[f][s]
コード例 #9
0
    def test_toomanydice(self):
        with raises(DiceFatalException):
            roll('%id6' % (MAX_ROLL_DICE + 1))

        with raises(DiceFatalException):
            roll('7d6', max_dice=6)

        with raises(ValueError):
            Roll.roll(6, 1, 6, max_dice=4)
コード例 #10
0
ファイル: terrestrial.py プロジェクト: tolcreator/gurps_space
    def GenerateBasic(self):
        if self.parentWorld:
            solarRadius = self.parentWorld.GetOrbit().GetRadius()
        else:
            solarRadius = self.GetOrbit().GetRadius()
        blackBodyTemperature = 278 * ( pow(self.parentStar.GetLuminosity(), 0.25) / pow(solarRadius, 0.5) )
        self.subType = GetWorldSubtype(self.mainType, blackBodyTemperature)

        """ Corrections """
        """ Fix Ammonia worlds now """
        if self.subType == "Ammonia" and self.parentStar.GetMass() > 0.65:
            self.subType = "Ice"
        """ Find Sulfur World now """
        if self.mainType == "Tiny" and self.subType == "Ice" and self.parentWorld and self.parentWorld.GetType() == "Gas Giant" and self.parentWorld.GetNumSulfurWorlds() == 0:
            r = dice.roll(1, 6)
            if r <= 3:
                self.subType = "Sulfur"
                self.parentWorld.IncNumSulfurWorlds()

        """ Find Garden World Now """
        """ TODO: Use First In method """
        if not self.parentStar.GetType() == "L" and not self.parentStar.GetType() == "T" and not self.parentStar.GetType() == "Y":
            if self.mainType == "Standard" and self.subType == "Ocean":
                r = dice.roll(3, 6)
                mod = int(self.parentStar.GetAge() / 0.5)
                mod = max(mod, 10)
                r = r + mod
                if r > 18:
                    self.subType = "Garden"
            if self.mainType == "Large" and self.subType == "Ocean":
                r = dice.roll(3, 6)
                mod = int(self.parentStar.GetAge() / 0.5)
                mod = max(mod, 5)
                r = r + mod
                if r > 18:
                    self.subType = "Garden"
         
        self.density = GenerateDensity(self.mainType, self.subType)
        if blackBodyTemperature < 3.0:
            """ Damn White Dwarves """
            """ TODO: Maybe use the III temperature instead """
            originalBlackBodyTemperature = 278 * ( pow(self.parentStar.GetInitialLuminosity(), 0.25) / pow(solarRadius, 0.5) )
            self.diameter = GenerateDiameter(self.mainType, originalBlackBodyTemperature, self.density)
        else:     
            self.diameter = GenerateDiameter(self.mainType, blackBodyTemperature, self.density)
        self.gravity = world.GetGravity(self.density, self.diameter)
        self.mass = world.GetMass(self.density, self.diameter)
         
        atmosphericMass = GenerateAtmosphericMass(self.mainType, self.subType)
        self.hydrosphere = GenerateHydrosphere(self.mainType, self.subType)
        blackBodyCorrection = GetBlackBodyCorrection(self.mainType, self.subType, self.hydrosphere, atmosphericMass)
        self.averageTemperature = blackBodyTemperature * blackBodyCorrection
        self.climate = world.GetClimate(self.averageTemperature)
        self.atmosphericPressure = GetAtmosphericPressure(self.mainType, self.subType, atmosphericMass, self.gravity)
        self.atmosphericCategory = GetAtmosphericCategory(self.atmosphericPressure)
コード例 #11
0
ファイル: itemGen.py プロジェクト: Vbitz/Pythfinder
 def on_hit(self, attacker, defender):
     # do anything triggered by a hit (except regular damage)
     if (AXIOMATIC & self.ego and CHAOTIC & defender.alignment) or (ANARCHIC & self.ego and LAWFUL & defender.alignment) or (HOLY & self.ego and EVIL & defender.alignment) or (UNHOLY & self.ego and GOOD & defender.ALIGNMENT):
         pass
     if FIERY & self.ego:
         defender.take_damage(dice.roll('1d6')[0], 'fire')
     elif FREEZING & self.ego:
         defender.take_damage(dice.roll('1d6')[0], 'cold')
     elif SHOCKING & self.ego:
         defender.take_damage(dice.roll('1d6')[0], 'electric')
     elif WOUNDING & self.ego:
         pass
コード例 #12
0
ファイル: system.py プロジェクト: tolcreator/gurps_space
def GenerateGasGiantOuterMoonOrbitRadius(existingOrbits):
    legal = False
    while not legal:
        r = dice.roll(3, 6) + 3
        if r >= 15:
            r = r + dice.roll(2, 6)
        rad = float(r) * 3.34
        legal = True
        for e in existingOrbits:
            if e == rad:
                legal = False
    existingOrbits.append(rad)
    return rad
コード例 #13
0
ファイル: combat.py プロジェクト: bpa/renegade
    def run(self):
        monster = self.monster
        hero = self.hero
        dialog.message('You have been attacked by a %s!' % monster.get_name())
        hero_initiative = hero.get_initiative()
        monster_initiative = monster.get_initiative()
        while True:
            if hero_initiative > monster_initiative:
                monster_initiative = monster_initiative + monster.get_initiative()
                action = dialog.question('What is your bidding?', \
                                ( 'Hack', 'Slash', 'Stab' ))
                if action == 0:
                    thaco = hero.get_thaco() - 2
                    mult = 1.0
                elif action == 1:
                    thaco = hero.get_thaco()
                    mult = 1.5
                elif action == 2:
                    thaco = hero.get_thaco() + 2
                    mult = 2.0
                if thaco - monster.ac <= dice.roll('1d20'):
                    damage = int(hero.weapon.get_damage() * mult * hero.strength / 10.0)
                    if monster.damage(damage):
                        gold = monster.get_gold()
                        hero.add_gold(gold)
                        hero.gain_exp(monster.get_exp_value())
                        mess = 'You hit the %s for %d points of damage, ' + \
                               'killing it!  You find %d gold.  For valor ' + \
                               'in combat, you receive %d experience points.'
                        mess = mess % (monster.get_name(), damage, gold, monster.get_exp_value())
                        dialog.message(mess)
                        hero.check_level()
                        return 'win'
                    else:
                        dialog.message('You hit the %s for %d points of damage.' % \
                               (monster.get_name(), damage))

                else:
                    dialog.message('You missed!')
            else:
                hero_initiative = hero_initiative + hero.get_initiative()
                if monster.thaco - hero.get_ac() <= dice.roll('1d20'):
                    damage = monster.do_damage()
                    message = monster.damage_text(damage)
                    if hero.damage(damage):
                        dialog.message(message + '  You have died!')
                        return 'lose'
                    else: dialog.message(message)
                else:
                    dialog.message('The %s misses you!' % monster.get_name())
コード例 #14
0
ファイル: terrestrial.py プロジェクト: tolcreator/gurps_space
 def GenerateVulcanism(self):
     if self.parentStar.GetAge() == 0:
         mod = 40
     else:
         mod = int((self.gravity / self.parentStar.GetAge()) * 40)
     majorMoons = self.GetNumMajorMoons()
     if majorMoons == 1:
         mod = mod + 5
     elif majorMoons > 1:
         mod = mod + 10
     if self.subType == "Sulfur":
         mod = mod + 60
     elif self.parentWorld:
         if self.parentWorld.GetType == "Gas Giant":
             mod = mod + 5 
     r = dice.roll(3, 6) + mod
     if r <= 16:
         self.vulcanism =  "None"
     elif r <= 20:
         self.vulcanism = "Light"
     elif r <= 26:
         self.vulcanism = "Moderate"
     elif r <= 70:
         self.vulcanism = "Heavy"
     else:
         self.vulcanism = "Extreme"
     """ TODO figure out if atmosphere is marginal """
コード例 #15
0
ファイル: terrestrial.py プロジェクト: tolcreator/gurps_space
 def GenerateTectonicActivity(self):
     if self.mainType == "Tiny" or self.mainType == "Small":
         self.tectonics = "None"
         return
     mod = 0
     if self.vulcanism == "None":
         mod = mod - 8
     elif self.vulcanism == "Light":
         mod = mod - 4
     elif self.vulcanism == "Heavy":
         mod = mod + 4
     elif self.vulcanism == "Extreme":
         mod = mod + 8
     if self.hydrosphere == 0:
         mod = mod - 4
     elif self.hydrosphere <= 50:
         mod = mod - 2
     majorMoons = self.GetNumMajorMoons()
     if majorMoons == 1:
         mod = mod + 2
     elif majorMoons > 1:
         mod = mod + 4
     r = dice.roll(3, 6) + mod
     if r <= 6:
         self.tectonics = "None"
     elif r <= 10:
         self.tectonics = "Light"
     elif r <= 14:
         self.tectonics = "Moderate"
     elif r <= 18:
         self.tectonics = "Heavy"
     else:
         self.tectonics = "Extreme"
コード例 #16
0
ファイル: terrestrial.py プロジェクト: tolcreator/gurps_space
 def GenerateVolcanicPollutants(self):
     r = dice.roll(3, 6)
     target = 0
     if self.vulcanism == "Heavy":
         target = 8
     if self.vulcanism == "Extreme":
         target = 14
     if r <= target:
         self.atmosphericComposition.append("Marginal")
         r = dice.roll(1, 6)
         if r <= 3:
             self.atmosphericComposition.append("Pollutants")
             self.atmosphericComposition.append("Mildly Toxic")
         else:
             self.atmosphericComposition.append("Sulfur Compounds")
             self.atmosphericComposition.append("Mildly Toxic")
コード例 #17
0
ファイル: terrestrial.py プロジェクト: tolcreator/gurps_space
 def GenerateResourceValue(self):
     mod = 0
     if self.vulcanism == "None":
         mod = -2
     elif self.vulcanism == "Light":
         mod = -1
     elif self.vulcanism == "Heavy":
         mod = 1
     elif self.vulcanism == "Extreme":
         mod = 2
     r = dice.roll(3, 6) + mod
     if r <= 2:
         self.overallValue = "Scant"
         self.resourceValue = -3
     elif r <= 4:
         self.overallValue = "Very Poor"
         self.resourceValue = -2
     elif r <= 7:
         self.overallValue = "Poor"
         self.resourceValue = -1
     elif r <= 13:
         self.overallValue = "Average"
         self.resourceValue = 0
     elif r <= 16:
         self.overallValue = "Abundant"
         self.resourceValue = 1
     elif r <= 18:
         self.overallValue = "Very Abundant"
         self.resourceValue = 2
     else:
         self.overallValue = "Rich"
         self.resourceValue = 3
コード例 #18
0
ファイル: story.py プロジェクト: Sahnvour/GameBook
    def id(self, vars={}):
        if self.threshold:
            thres = put_vars(self.threshold, vars)
            return (True, self.success) if dice.roll(thres) else (
            False, self.failure)

        return (True, self.page)
コード例 #19
0
ファイル: commands.py プロジェクト: tokyodreams/hangouts_bot
def roll(bot, event, *args):
    r = dice.roll(''.join(args))
    output = ""
    for i in r:
        output += " " + str(i)
    output += "] = " + str(int(r))
    bot.send_message(event.conv, "[" + output.strip())
コード例 #20
0
ファイル: impl.py プロジェクト: wqi/tgbot
def parse(s):
    arr = s.split(" ");
    if len(arr) == 0: return

    if arr[0] == "roll":
        if (len(arr) < 1):
            die("roll noargs")

        send(dice.roll(arr[1]))
    elif arr[0] == "do":
        if len(arr) < 3:
            die("do badargs")

        try:
            n = int(arr[1])
        except:
            die("do badnum")
            return

        if arr[2] == "do":
            die("do do")

        if n > 10:
            die("do toobig")

        cmd = " ".join(arr[2:])

        for i in range(n):
            parse(cmd)
    else:
        die("undef \"" + " ".join(arr) + "\"")
コード例 #21
0
ファイル: world.py プロジェクト: tolcreator/gurps_space
def GenerateSpecialRotationalPeriod(initial):
    r = dice.roll(3, 6)
    if r <= 6:
        return float(initial) / 24
    d = dice.roll(1, 6)
    if r <= 7:
        return d * 2
    if r <= 8:
        return d * 5
    if r <= 9:
        return d * 10
    if r <= 10:
        return d * 20
    if r <= 11:
        return d * 50
    return d * 100
コード例 #22
0
ファイル: channel_message.py プロジェクト: Tmplt/Toothless
def roll(bot, event, command, args):
    #hardcapped safeguaard, the best kind.
    match = DICEROLL.match(args)
    try:
        dicenum = int(match.group('dicenum'))
    except:
        dicenum = 1
    try:
        diceface = int(match.group('diceface'))
    except:
        diceface = 0
    #yeah, i'm that paranoid
    
    if dicenum <= 20 and dicenum >= 1 and diceface <= 1024 and diceface >= 1:
        try:
            roll = dice.roll(args)
            rresult = ', '.join(map(str, roll))
            bot.send_channel_action(bot.config.messages.roll, result = rresult, nick = event.source)
            return True
        except OverflowError:
            bot.send_channel_action(bot.config.messages.nodice, nick = event.source)
            return False
        except:
            bot.send_channel_action(bot.config.messages.diceerr, nick = event.source)
            return False
    else:
        bot.send_channel_action(bot.config.messages.diceerr, nick = event.source)
        return False
コード例 #23
0
def h_e_rolls(hskill, eskill):

    total = []

    hroll = dice.roll('2d6')
    eroll = dice.roll('2d6')

    htotal = hroll[0] + hroll[1] + hskill
    etotal = eroll[0] + eroll[1] + eskill

    total.append(htotal)
    total.append(etotal)

    print total

    return total
コード例 #24
0
ファイル: chatbot.py プロジェクト: bigdogdk/DHBot
	async def roll_dice(self, client, message):
		droll = message.content.partition(' ')[2]
		clean = droll.split('d')
		if 0 < int(clean[0]) < 51 and 0 < int(clean[1]) < 1001:
			await client.send_message(message.channel, str(dice.roll(droll)))
		else:
			await client.send_message(message.channel, 'Not an appropriate amount or size of dice.')
コード例 #25
0
ファイル: monster.py プロジェクト: mwrouse/Python
    def __init__(self, name="", image="", attackSound="", specialSound="", xPos=450, yPos=250, dX=0, dY=1):
        # Initialize Sprite
        super(Monster, self).__init__(image=games.load_image(image), x=xPos, y=yPos, dx=dX, dy=dY)

        # General Variables
        self.name = name.title()
        self.health = randint(20, 53)
        self.money = dice.roll(20) # Roll d20 for amount of coins owned
        self.alive = True
        self.moving = False

        # Attack Variables
        self.attacking = False
        self.attackDelay = 0
        self.attackBonus = 0
        self.defenseBonus = 10

        # Sounds
        self.attackSound = games.load_sound(attackSound)
        self.specialSound = games.load_sound(specialSound)
        self.deathSound = games.load_sound("sounds/dragon_death.wav")

        # Sprite to show damage was inflicted
        self.damageSprite = games.Sprite(image=games.load_image("sprites/damage.png"), x=self.x, y=self.y)
        self.damageSpriteCounter = -1

        # Sprite to show health info above head
        self.healthLabel = games.Text(value="HP: " + str(self.health), size=30, x=self.x,
                                      y=self.top - 20, color=color.white)
        games.screen.add(self.healthLabel)
コード例 #26
0
ファイル: system.py プロジェクト: tolcreator/gurps_space
def GenerateBrownDwarfMass(primaryMass):
    """ i.e. there is no primary """
    if primaryMass == 0:
        primaryMass = 0.08
    legal = False
    mass = 0
    while not legal:
        r = dice.roll(3, 6)
        if r <= 8:
            mass =  0.015
        elif r <= 10:
            mass =  0.02
        elif r <= 12:
            mass = 0.03
        elif r <= 14:
            mass = 0.04
        elif r <= 15:
            mass = 0.05
        elif r <= 16:
            mass =  0.06
        else:
            mass = 0.07
        if mass <= primaryMass:
            legal = True
    return mass
コード例 #27
0
ファイル: system.py プロジェクト: tolcreator/gurps_space
def GenerateNumStars():
    d = dice.roll(3, 6)
    if d <= 10:
        return 1
    if d <= 15:
        return 2
    return 3
コード例 #28
0
ファイル: voyageur.py プロジェクト: GaelPICOT/voyage
 def __init__(self):
     self._carac = Caracteristiques()
     self._competances = Competances()
     self._fatigue = FatigueCount()
     # points
     self._points = {"destinee": Compteur(0, 7),
                     "chance": Compteur(self._carac["Chance"].valeur)}
     # seuils
     self._seuils = {}
     # ajout gestion vie est endurence
     self._carac["Taille"].value_changed.connect(self.calculate_vie)
     self._carac["Constitution"].value_changed.connect(self.calculate_vie)
     self._carac["Volonte"].value_changed.connect(self.calculate_vie)
     self.calculate_vie()
     # ajout gestion rêve
     self._carac["Reve"].value_changed.connect(self.calculate_reve)
     self.calculate_reve()
     # + dom et enc
     self._carac["Taille"].value_changed.connect(self.calculate_p_dom)
     self._carac["Force"].value_changed.connect(self.calculate_p_dom)
     self.calculate_p_dom()
     # signe particulier
     self._signes_particuliers = SignesParticuliers()
     self._list_event = []
     if dice.roll("1d12").pop() == 1:
         self._mainhand = "ambidextre"
     else:
         self._mainhand = "droite"
     self._time = DateTime()
     self._statu_revant = VraiRevant()
コード例 #29
0
ファイル: roll.py プロジェクト: DasFranck/ConDeBot
    async def on_message(self, message, cmd):
        if (not cmd or not cmd.triggered
                or cmd.action not in ["roll"]):
            return

        if len(cmd.args) == 0:
            await self.cdb.send_message(cmd.msg.channel,
                                        "Try with an argument for this command next time.")
            return

        try:
            result = roll(" ".join(cmd.args))
        except DiceBaseException as e:
            await self.cdb.send_message(cmd.msg.channel,
                                        "Error: \n```" + e.pretty_print() + "```")
            return

        if type(result) is Integer:
            await self.cdb.send_message(cmd.msg.channel,
                                        "The result is: " + str(result))
        elif type(result) in [Roll, list]:
            await self.cdb.send_message(cmd.msg.channel,
                                        "The dices are: " + ", ".join(str(dice) for dice in result[:]))
        else:
            await self.cdb.send_message(cmd.msg.channel,
                                        "That seems to be an unexpected result, please contact DasFranck.")
            print(result)
            print(type(result))
        return
コード例 #30
0
ファイル: command.py プロジェクト: imclab/python-dice
def main(argv=None):
    """Run roll() from a command line interface"""
    args = docopt.docopt(__doc__, argv=argv, version=__version__)
    result = dice.roll(args['<expression>'], verbose=args['--verbose'])
    if args['--verbose']:
        print("Result:", end=" ")
    return str(result)
コード例 #31
0
def test_roll():
    for single, raw in itertools.product((True, False), (True, False)):
        assert roll('6d6', single=single, raw=raw)
        assert roll_min('6d6', single=single, raw=raw)
        assert roll_max('6d6', single=single, raw=raw)
コード例 #32
0
print("Wisdom: " + str(RaccoonNPC.wis))
print("Strength: " + str(RaccoonNPC.strt))
print("Dexterity: " + str(RaccoonNPC.dex))
print("Constitiution: " + str(RaccoonNPC.con))
print("Race: " + RaccoonNPC.race)
print("Class: " + RaccoonNPC.class1)
print("Weapon: " + RaccoonNPC.weapon)
turn = 1
counter = 0
while (RaccoonNPC.hitpoints > 0):
    print("=" * 22 + "Turn:" + str(turn) + "=" * 22)
    action = input(
        "What would you like to do?: \ntype 'roll' to attack\ntype 'run' to...run\ntype 'spec' to perform a special attack\n"
    )
    if (action == "roll"):
        PCroll = dice.roll(4, 2)
        print("You deal: " + str(PCroll) + " damage to your opponent")
        RaccoonNPC.hitpoints -= PCroll
    elif (action == "run"):
        PCroll = dice.roll(PCUpdated.dex, 1)
        if (PCroll > 5):
            print("You succesfully escape")
            print("~" * 50)
            break
        else:
            print("You don't escape")
    elif (action == "spec"):
        if (counter == 1):
            print("You've already used your special attack")
            continue
        print(
コード例 #33
0
def combat():
    monster_ID = randint(0, 2)

    global player_health, inventory, armory, bestiary
    round = 1
    monster_health = bestiary[monster_ID]['health']

    print(
        f"A ferocious {bestiary[monster_ID]['name']} approaches! COMBAT HAS BEGUN!\n"
    )
    while True:
        print(f"ROUND {round}")
        print("Player Health: [" + str(player_health) + "]")
        print("Monster Health: [" + str(monster_health) + "]")

        print("Type: RUN, CAST [spell], or USE [weapon]"
              )  # gotta write code for cast
        move = input().lower().split(
            " ", 1
        )  # converts move into a lower-case list to deal with each item in list separately
        monster_damage = sum(dice.roll(bestiary[monster_ID]['damage']))
        print("\n=========================")

        if move[0] == 'use':  #
            if move[1] in inventory:  # checks if weapon is in your inventory
                player_damage = dice.roll(armory[move[1]]['damage'])
                print(
                    f"You hit a {bestiary[monster_ID]['name']} for {player_damage} damage!"
                )
            if move[1] not in inventory:
                print(f"There is no {move[1]} in your inventory!")

        if move[0] == 'cast':  #
            if move[1] in spellbook:  # checks if spell is in your spellbook
                if move[1].lower() == 'fireball':
                    player_damage = sum(
                        dice.roll(spell_lookup[move[1]]['damage']))
                    print(
                        f"Summoning eldritch forces, you scorch the {bestiary[monster_ID]['name']} for {player_damage} damage!"
                    )
            if move[1] not in spellbook:
                print(f"You don't know the {move[1]} spell!")

        if move[0] == 'run':  #
            escape_chance = randint(
                1, 10
            )  #+ player_speed # if I set this variable later, here's where it would work

            if escape_chance >= 10:
                print("You make a flawless escape!")
                break
            if escape_chance >= 5:
                print(
                    "You expose your back as you turn and flee- the monster takes advantage."
                )
                print(
                    f"A {bestiary[monster_ID]['name']} hits you for {monster_damage} damage!"
                )
                player_health -= int(monster_damage)
                if player_health >= 1:
                    print("You managed to escape.")
                    break
                if player_health < 1:
                    print("You have been slain.")
                    print("\nGAME OVER")
                    sys.exit()
            if escape_chance >= 0:
                print(
                    "The monster out-maneuvers you and attacks! You do not escape."
                )

        try:
            monster_health -= int(player_damage)
        except:
            pass
        if monster_health <= 0:
            print(
                f"The {bestiary[monster_ID]['name']} lies dead. You are victorious!\n"
            )
            break

        print(
            f"A {bestiary[monster_ID]['name']} hits you for {monster_damage} damage!"
        )
        print("=========================\n")
        round += 1
        player_health -= int(monster_damage)

        if player_health <= 0:
            print("You have been vanquished! You are dead.")
            sys.exit()
コード例 #34
0
ファイル: pool.py プロジェクト: pdusen/pdusen-cogs
    async def pool(self, ctx, *, arg):
        """Rolls a WoD-style Dice Pool of 10-sided dice"""
        output_strings = []
        try:
            match = self.pattern.match(arg)
            if not match:
                await self.bot.say("You did it wrong!")
                return

            output_strings.append('Dice roll called by ')
            output_strings.append(ctx.message.author.name)
            output_strings.append('.\n')

            success_threshold = 6
            if match.group(2):
                success_threshold = int(match.group(2))

            pool_size = match.group(1)

            if int(pool_size) > 50:
                await self.bot.say(
                    'ERROR: Invalid dice pool size; the maximum is 50!')
                return

            result = dice.roll(pool_size + 'd10s')
            result.reverse()
            rolls = deque(result)

            one_count = sum(1 for i in rolls if i == 1)
            success_count = sum(1 for i in rolls if i >= success_threshold)

            removed_successes = []
            removed_ones = []
            remaining_successes = []
            remaining_failures = []

            while len(rolls) > 1 and rolls[0] >= success_threshold and rolls[
                    -1] == 1:
                removed_successes.append(rolls.popleft())
                removed_ones.append(rolls.pop())

            while len(rolls) > 0 and rolls[0] >= success_threshold:
                remaining_successes.append(rolls.popleft())

            while len(rolls) > 0:
                remaining_failures.append(rolls.popleft())

            successes_remaining = len(remaining_successes)

            string_bits = []

            for roll in removed_successes:
                string_bits.append('~~{}~~'.format(roll))

            for roll in remaining_successes:
                string_bits.append('**{}**'.format(roll))

            for roll in remaining_failures:
                string_bits.append(str(roll))

            for roll in removed_ones:
                string_bits.append('~~1~~')

            output_strings.append('  '.join(string_bits))
            output_strings.append('\n')

            remaining_successes_count = len(remaining_successes)

            if one_count > 0 and success_count == 0:
                output_strings.append('```diff\n- B O T C H E D -\n```')
            elif successes_remaining == 0:
                output_strings.append('```css\n[ FAILED ({}) ]\n```'.format(
                    remaining_successes_count))
            elif successes_remaining >= 5:
                output_strings.append(
                    '```asciidoc\n= P H E N O M I N A L   S U C C E S S  ({}) =\n```'
                    .format(remaining_successes_count))
            elif successes_remaining == 4:
                output_strings.append(
                    '```cs\n" EXCEPTIONAL SUCCESS ({}) "\n```'.format(
                        remaining_successes_count))
            elif successes_remaining == 3:
                output_strings.append(
                    '```diff\n+ Complete Success ({}) +\n```'.format(
                        remaining_successes_count))
            elif successes_remaining == 2:
                output_strings.append(
                    '```bash\n# Moderate Success ({}) #\n```'.format(
                        remaining_successes_count))
            elif successes_remaining == 1:
                output_strings.append(
                    '```\nMarginal success... ({})\n```'.format(
                        remaining_successes_count))
        except Exception as error:
            output_strings.append('\n')
            output_strings.append(str(error))
        finally:
            await self.bot.say(''.join(output_strings))
コード例 #35
0
ファイル: test_grammar.py プロジェクト: roaet/python-dice
 def test_add(self):
     assert roll('2 + 2') == 4
コード例 #36
0
ファイル: test_grammar.py プロジェクト: roaet/python-dice
 def test_dice_type(self):
     assert isinstance(roll('d6'), Roll)
     assert isinstance(roll('1d6'), Roll)
コード例 #37
0
def roll_human():
    print(roll_human_background(roll('1d20t')))
    print(roll_human_personality(roll('3d6t')))
    print(roll_human_religion(roll('3d6t')))
    print(roll_human_appearance(roll('3d6t')))
    print(roll_human_age(roll('3d6t')))
コード例 #38
0
ファイル: battle.py プロジェクト: kostrom/DnDStuff
battles = 1
detailedTracking = (1 == battles)
p1.detailedTracking = detailedTracking
p2.detailedTracking = detailedTracking

# there is a much easier way to do this, but im lazy atm.
for x in range(battles): #rematches
    i = 0

    # init time!
    if detailedTracking:
        print()
        print("~~~~~~~~~~~~~~~~~~~~")
        print("~~~~FRESH INITS!~~~~")
        print("~~~~~~~~~~~~~~~~~~~~")
    p1flatInit = roll(1,20)
    p1.init = p1flatInit+p1.initBonus
    if detailedTracking:print(p1.name+" init: ("+str(p1flatInit)+")+"+str(p1.initBonus)+" total: "+str(p1.init))

    p2flatInit = roll(1,20)
    p2.init = p2flatInit+p2.initBonus
    if detailedTracking:print(p2.name+" init: ("+str(p2flatInit)+")+"+str(p2.initBonus)+" total: "+str(p2.init))

    if p1.init > p2.init:
        if detailedTracking:print(p1.name+" goes first!")
        firstPlayer = "p1"
        p1.wentFirst += 1
    elif p1.init < p2.init:
        if detailedTracking:print(p2.name+" goes first!")
        firstPlayer = "p2"
        p2.wentFirst += 1
コード例 #39
0
ファイル: test_dice.py プロジェクト: anatidae/entchen
 def test_simple(self):
     x = roll('d6')
     r = re.findall(r'\( [1-6] \) = [1-6]', x)
     assert len(r) == 1
コード例 #40
0
ファイル: test_dice.py プロジェクト: anatidae/entchen
 def test_addition(self):
     x = roll('2w20+5')
     r = re.findall(r'\( (\d+) \+ (\d+) \) \+ (5) = (\d+)', x)
     assert len(r) == 1
     assert int(r[0][0]) + int(r[0][1]) + int(r[0][2]) == int(r[0][-1])
コード例 #41
0
ファイル: test_dice.py プロジェクト: anatidae/entchen
 def test_bigger(self):
     x = roll('2w1000')
     r = re.findall(r'\( (\d+) \+ (\d+) \) = (\d+)', x)
     assert len(r) == 1
     assert int(r[0][0]) + int(r[0][1]) == int(r[0][-1])
コード例 #42
0
ファイル: test_dice.py プロジェクト: anatidae/entchen
 def test_result(self):
     x = roll('2d6')
     r = re.findall(r'\( ([1-6]) \+ ([1-6]) \) = (\d+)', x)
     assert len(r) == 1
     assert int(r[0][0]) + int(r[0][1]) == int(r[0][-1])
コード例 #43
0
 def roll_armor_type(self):
     armor_roll = sum(dice.roll('1d8'))
     return self.roll_on_table_with_range(armor_roll, 'Armor')
コード例 #44
0
ファイル: test_grammar.py プロジェクト: roaet/python-dice
 def test_type(self):
     assert isinstance(roll('1'), int)
     assert isinstance(roll('1'), Integer)
コード例 #45
0
ファイル: test_grammar.py プロジェクト: roaet/python-dice
 def test_dice_value(self):
     assert 0 < int(roll('d6')) <= 6
     assert 0 < int(roll('1d6')) <= 6
コード例 #46
0
ファイル: test_command.py プロジェクト: camillescott/zardoz
def test_roll():
    for single, raw in product((True, False), (True, False)):
        assert roll("6d6", single=single, raw=raw)
        assert roll_min("6d6", single=single, raw=raw)
        assert roll_max("6d6", single=single, raw=raw)
コード例 #47
0
ファイル: test_grammar.py プロジェクト: roaet/python-dice
 def test_dice_values(self):
     for die in roll('6d6'):
         assert 0 < die <= 6
コード例 #48
0
 async def on_message(self,message):
     if message.author == self.user:
         return
     elif re.match(r'^gamble\b', message.content) is not None:
         if len(message.content.split()) == 1:
             await message.channel.send(self.commands_msg)
         elif message.content.split()[1] == 'btc':
             time,price =  self.get_cached_btc_price()
             embed = discord.Embed()
             embed.description = "Powered by [CoinDesk](https://www.coindesk.com/price/bitcoin)"
             content = "The price of BTC at %s was %s USD\nThis bot will only query the price if cached data is older than %s minutes to avoid overuse of the API."%(time.ctime(),price,str(self.time_delay))
             await message.channel.send(content=content,embed=embed)
         elif message.content.split()[1] == 'roll':
             if len(message.content.split()) == 2:
                  await message.channel.send("Roll usage:\n```gamble roll xdy: rolls x dice with a range from 1 to y```")
             elif re.match(r'^\d+d\d+$',message.content.split()[2]) is not None:
                 string = message.content.split()[2]
                 x,y = string.split("d")
                 if x == 1:
                     await message.channel.send("Rolling %s die with %s faces each...\n%s!"%(x,y,sum(dice.roll(string))))
                 else:
                     await message.channel.send("Rolling %s dice with %s faces each...\n%s!"%(x,y,sum(dice.roll(string))))
             else:
                 await message.channel.send("Roll usage:\n```gamble roll xdy: rolls x dice with a range from 1 to y```")
         else:
             await message.channel.send(self.commands_msg)
     elif message.content == "ping":
         await message.channel.send('pong')
コード例 #49
0
 def get_random_item_type(self):
     roll = dice.roll('1d%')
     self.item_type = self.roll_on_table_with_range(sum(roll), 'item_types')
     if self.item_type is None:
         raise Exception(
             'Unable to get random item type. Check magic_subtable')
コード例 #50
0
def roll_dice(query, sender):
    try:
        result = dice.roll(query)
        CENA.set_text(str(result))
    except Exception:
        CENA.set_text("They rolled off the table...")
コード例 #51
0
	sleep(delay)
	bet = take_bet(capital, played=played)
	sleep(delay)
	print('Computer has matched your bet.')
	capital -= bet
	pool += 2 * bet

	sleep(delay)
	print(Fore.GREEN + '<<Round 1 betting ends>>')
	
	# Roll dice for round 1

	sleep(delay)
	print(Fore.GREEN + '<<Rolling dices>>')

	hand_p = dice.roll()
	hand_c = dice.roll()
	
	sleep(delay)
	show_hands(hand_p, hand_c)

	# Round 2 of the game.

	sleep(delay)
	print('\n ' + Back.GREEN + Fore.BLACK + '------------- Round 2 -------------' + Style.RESET_ALL + '\n')

	show_capital(capital)

	# Take bet for round 2

	sleep(delay)
コード例 #52
0
ファイル: arena.py プロジェクト: NoahABerkley/DnDStuff
def attack_rolls(player, enemy, detailed_tracking):
    """attack_rolls runs a fight to the death between two players"""
    for atk in player.attacks:
        flat_roll = roll(1, 20)
        attack_roll = flat_roll + atk[0]
        damage_range = [atk[1], atk[2] * atk[1]]
        sneak_attack_damage_range = [
            player.sneakAtkDice, 6 * player.sneakAtkDice
        ]
        if attack_roll >= enemy.ac or flat_roll >= player.critRange:  #auto hit on crits'
            if flat_roll >= player.critRange:
                if detailed_tracking:
                    print("{} Atk: ({}), total: {} CRITICAL HIT!".format(
                        player.name, flat_roll, attack_roll))
                damage_roll = roll(damage_range[0] * 2, damage_range[1] * 2)
                player.critCounter += 1
                damage_string = "Crit Dmg: {}d{}+{} (range: {}-{})".format(
                    atk[1] * 2, atk[2], atk[3], damage_range[0] * 2 + atk[3],
                    damage_range[1] * 2 + atk[3])
                if player.sneakAtkDice > 0:
                    sneak_attack_damage_roll = roll(
                        sneak_attack_damage_range[0] * 2,
                        sneak_attack_damage_range[1] * 2)
                    if detailed_tracking:
                        print("Sneak Attack dice: {}d{}, damage: {}".format(
                            sneak_attack_damage_range[0] * 2, 6,
                            sneak_attack_damage_roll))
                    enemy.take_damage(sneak_attack_damage_roll)
            else:
                if detailed_tracking:
                    print("{} Atk: ({}), total: {} HIT!".format(
                        player.name, flat_roll, attack_roll))
                damage_roll = roll(damage_range[0], damage_range[1])
                damage_string = "Dmg: {}d{}+{} (range: {}-{})".format(
                    atk[1], atk[2], atk[3], damage_range[0] + atk[3],
                    damage_range[1] + atk[3])
                if player.sneakAtkDice > 0:
                    sneak_attack_damage_roll = roll(
                        sneak_attack_damage_range[0],
                        sneak_attack_damage_range[1])
                    if detailed_tracking:
                        print("Sneak Attack dice: {}d{}, damage: {}".format(
                            sneak_attack_damage_range[0], 6,
                            sneak_attack_damage_roll))
                    enemy.take_damage(sneak_attack_damage_roll)
            attack_damage = damage_roll + atk[3]
            if detailed_tracking:
                print(damage_string)
                print("Dealt {} dmg, ({})+{}".format(attack_damage,
                                                     damage_roll, atk[3]))
            enemy.take_damage(attack_damage)
            player.hitsCounter += 1
        else:
            if detailed_tracking:
                print(player.name + " missed.")
        if detailed_tracking:
            print()
        if enemy.hp <= 0:
            return "death"
    if enemy.hp <= 0:
        return "death"
    return "everybody lives!"
コード例 #53
0
        self.strength = strength
        self.dexterity = dexterity
        self.constitution = constitution
        self.intelligence = intelligence
        self.wisdom = wisdom
        self.charisma = charisma
        if self.strength < 8:
            self.strength = 8
        if self.dexterity < 8:
            self.dexterity = 8
        if self.constitution < 10:
            self.constitution = 10
        if self.intelligence < 8:
            self.intelligence = 8
        if self.wisdom < 8:
            self.wisdom = 8
        if self.charisma < 8:
            self.charisma = 8
        self.hp = 8 + (self.constitution - 10) / 2

    def __str__(self):
        return "STR: %i\nDEX: %i\nCON: %i\nINT: %i\nWIS: %i\nCHA: %i\n-----------------------\nHP: %i" % (
            self.strength, self.dexterity, self.constitution,
            self.intelligence, self.wisdom, self.charisma, self.hp)


roll = dice.roll(6, 3, True)

stat_set = StatGenerationPlayer()
print(stat_set)
コード例 #54
0
ファイル: town.py プロジェクト: hmtavares/sob_experiments
    def random_factory(tn_id, jobs, job_mandatory, allow_ruins=False):
        """Create a random town

        Args:
            tn_id - The id of the town on the hexcrawl map
            jobs - The collection of mandatory and non-mandatory jobs
            allow_ruins - True if a town can be generated as
                          type 'Ruins'
            job_mandatory - The % chance that a town will have a mandatory
                            job. 0% indicates that the method defind in the
                            Hexcrawl document should be used (roll +/- 1)
        """

        tn = TOWNS[tn_id]
        if not allow_ruins:
            #
            # Ruins are not allowed for this town so
            # add Ruins to the disallowed type list
            #
            tn['disallowed'].append("Ruins")
        #
        # Town Size and how many buildings
        #
        town_size, size_low, size_high = random.choice(TOWN_SIZES)

        num_buildings = random.randint(size_low, size_high)

        #
        #  Generate town kind.
        #  Keep trying until a valid type is generated
        #
        while (True):
            roll = dice.roll('2d6')
            town_type = TOWN_TYPES[sum(roll)]
            if town_type not in tn['disallowed']:
                break

        #
        # Generate Town Trait
        # Keep trying until a valid trait is generated
        #
        while (True):
            roll = dice.roll('2d6')
            trait_roll = roll[0] * 10 + roll[1]
            town_trait = TOWN_TRAITS[trait_roll]

            #
            # Check for special trait considerations
            #
            disallowed = town_trait.get('disallowed')
            if not disallowed:
                #
                # No special considerations.
                # Keep the trait
                #
                break
            if town_type not in disallowed:
                #
                # No special consideration violations
                # Keep the trait.
                #
                break
        #
        # Generate buildings
        #
        # Copy the building list so we can 'draw' from it
        # without modifying the reference list.
        draw_buildings = TOWN_BUILDINGS[:]
        town_buildings = []

        #
        # Check if the town has special building considerations
        #
        special_tn = TOWN_TYPE_BLDGS.get(town_type)
        if special_tn:
            #
            # Get manditory buildings then remove
            # them from the available buildings
            #
            for bldg in special_tn['include']:
                draw_buildings.remove(bldg)
                town_buildings.append(bldg)
                num_buildings -= 1

            #
            # Get excluded buildings and take them out of the
            # available buildings
            #
            for bldg in special_tn['exclude']:
                draw_buildings.remove(bldg)

        #
        # Randomize the remaining buildings
        # and draw enough to fill the town
        #
        random.shuffle(draw_buildings)
        for i in range(num_buildings):
            town_buildings.append(draw_buildings.pop())

        #
        # Roll for the town job
        #
        # TODO: Create a seperate "Manditory" roll to
        #       check if the town has a manditory job
        #
        town_job = Town.generate_jobs(jobs, job_mandatory)

        #
        # Fix town coordinates to be normalized 3-tuple coordinates
        #
        (q, r) = tn['coord']
        coord = (q, r, 0 - (q + r))
        return Town(tn_id, tn['name'], coord, town_type, trait_roll, town_job,
                    town_buildings)
コード例 #55
0
def her_execution(board, position, role, eng_type, scot_type):
    '''
    Activates the HERALD card.
    position:  'opp' or 'comp' - ai or player
    board:  Board object
    '''

    #List of available nobles to steal
    enemy_nobles = []
    if role == 'SCOTLAND':
        enemy_role = 'ENGLAND'
    else:
        enemy_role = 'SCOTLAND'

    for enemy_region in board.get_controlled_regions(enemy_role):
        for block in enemy_region.blocks_present:

            if type(block) == blocks.Noble and block.name != 'MORAY' and block.allegiance != role:
                enemy_nobles.append(block)

    if position == 'opp':

        #Print out available nobles
        for noble in enemy_nobles:
            print(noble.name)

        #Take input
        valid_input = False
        while not valid_input:
            name_input = input('Which noble will you try to take?: ').strip().upper()

            #Check if the input is valid
            for noble in enemy_nobles:

                if name_input == noble.name:
                    valid_input = True
                    noble_to_steal = noble
                    

            if not valid_input:
                print('Invalid input. Please try again.')

    elif position == 'comp':
        ###
        ###
        ### PICK A RANDOM NOBLE - TEMPORARY
        ###
        ###
        num_nobles = len(enemy_nobles)
        rand_selection = random.randint(0,num_nobles-1)
        noble_to_steal = enemy_nobles[rand_selection]
        print('Computer picked ' + noble_to_steal.name)
        ###
        ###
        ###
        ###
        ###

    #Roll the die and take the number from the list
    print('Roll a die to take the noble. 1-4 = success, 5-6 = failure.\n>')

    rand_num = dice.roll(1)[0]
    print('DIE ROLL: ' + str(rand_num))

    if rand_num <= 4:
        #STEAL NOBLE
        noble_to_steal.change_allegiance()

        print('Success')
        print(noble_to_steal.name, 'changed allegiance.' )

        #Find the noble's region
        noble_region = combat.find_location(board, noble_to_steal)



        if len(board.regions[noble_region.regionID].blocks_present) > 1:
            for block in noble_region.blocks_present:
                if block == noble_to_steal:
                    print(block.name + ' added to attacking dict')
                    board.regions[noble_region.regionID].combat_dict['Attacking'].append(block)
                else:
                    print(block.name + ' added to defending dict')
                    board.regions[noble_region.regionID].combat_dict['Defending'].append(block)

            print('DID HERALD BATTLE IN HERALD FUNCTION')
            board.regions[noble_region.regionID].combat_dict['Attacking'][0].change_allegiance()
            combat.battle(board.regions[noble_region.regionID].combat_dict['Attacking'], board.regions[noble_region.regionID].combat_dict['Defending'], list(), list(), board, eng_type, scot_type)

        #Move the noble to its own region - will sort it into attacker/defender
        #board.move_block(noble_to_steal, noble_region.regionID, noble_region.regionID, position)

    else:
        print('Failure')
コード例 #56
0
ファイル: base.py プロジェクト: evilchili/telisar
 def HP(self):
     if not self._HP:
         self._HP = str(sum(dice.roll('2d8')) + 2) + ' (2d8+2)'
     return self._HP
コード例 #57
0
ファイル: general.py プロジェクト: Stonedestroyer/SinbadCogs
 def handler(exp):
     real = as_iterable(dice.roll(exp))
     mn = as_iterable(dice.roll_min(exp))
     mx = as_iterable(dice.roll_max(exp))
     yield from zip(real, mn, mx)
コード例 #58
0
def initiative(dexterity):
    """
    This function is used to determine initiative
    """

    return roll(f'1d20+{str(dexterity)}')
コード例 #59
0
ファイル: test_dice.py プロジェクト: anatidae/entchen
 def test_two(self):
     x = roll('2d6')
     r = re.findall(r'\( [1-6] \+ [1-6] \) = \d+', x)
     assert len(r) == 1
コード例 #60
0
ファイル: zcrit.py プロジェクト: TCohen20/zardoz
    def roll(self, modifers=None):
        rolled_val = int(dice.roll(self.die))
        name, effect = self.get(rolled_val)

        return rolled_val, name, effect