vendredi 3 septembre 2021

Issue with Nested If/While/If statement

As a D&D aficionado, I have written out a script to perform any attack and damage rolls for any specified die, including what happens in the event of a critical attack roll (20).

from random import randint

atk_roll = 20
hit_mod = 6
atk_hit = atk_roll + hit_mod
die = 'd10'
dmg_mod = 4
rolls = 1

def dice_roller(x, y, z):
    y1 = int(y.strip('d'))
    dict = {}
    results = []
    step = 1
    while step <= z:
        die = randint(1,y1)
        results.append(die)
        step += 1
    if atk_roll == 20:
        total = (sum(results)+dmg_mod) + (y1*z)
        pct_dmg = total / (((y1*z)+dmg_mod) + (y1*z))
    else:
        total = sum(results) + dmg_mod
        pct_dmg = total / ((y1*z)+dmg_mod)
    dict.update({'Attack Roll: ' + f'{atk_roll} + {hit_mod} = {x}':
                {'Damage Roll: ' + f'{z}' + y:
                {'Rolls': results, 'Total Damage': total, 'Pct_Damage': f'{pct_dmg:.0%}'}}})
    print(dict)

print(dice_roller(atk_hit, die, rolls))

{'Attack Roll: 20 + 6 = 26': {'Damage Roll: 1d10': {'Rolls': [4], 'Total Damage': 18, 'Pct_Damage': '75%'}}}
None

The issue becomes when I introduce a new "if/else" statement to account for a missed attack. The only roll that does not work is a critical roll:

from random import randint

atk_roll = 20
hit_mod = 6
atk_hit = atk_roll + hit_mod
die = 'd10'
dmg_mod = 4
rolls = 1
ac = 15

def dice_roller(x, y, z):
    y1 = int(y.strip('d'))
    dict = {}
    results = []
    step = 1
    if x >= ac:
        while step <= z:
            die = randint(1,y1)
            results.append(die)
            step += 1
            if atk_roll == 20:
                total = (sum(results)+dmg_mod) + (y1*z)
                pct_dmg = total / (((y1*z)+dmg_mod) + (y1*z))
            else:
                total = sum(results) + dmg_mod
                pct_dmg = total / ((y1*z)+dmg_mod)
                dict.update({'Attack Roll: ' + f'{atk_roll} + {hit_mod} = {x}':
                            {'Damage Roll: ' + f'{z}' + y:
                            {'Rolls': results, 'Total Damage': total, 'Pct_Damage': f'{pct_dmg:.0%}'}}})
            print(dict)
    else:
        print('Your attack missed')

print(dice_roller((atk_hit), die, rolls))
{}
None

When I change the value of "atk_roll" in the second script back to "randint(1,20)", the code works exactly as intended, noting when an attack misses or returning the dictionary of values if the attack hits. I cannot for the life of me figure out why the code is returning a blank dict only when "atk_roll" = 20. Does it have something to do with the nesting syntax of if/while/if? Thanks!

Aucun commentaire:

Enregistrer un commentaire