Cameron Locke
Cameron Locke

Reputation: 13

D&D dice roll python

Trying to roll dice like in dungeons and dragon but display each roll. I dont quite know what im doing wrong and appreciate all the help.

from random import randint
def d(y): #basic die roll
    return randint(1, y)
def die(x, y): #multiple die roll 2d20 could roll 13 and 7 being 20 
    for [x*d(y)]:
        print (sum(int(y)))

print (die(3, 20))

ok so i took the advice and changed it but still recieving an error on my return line

#
#trying to roll dice like in dungeons and dragon but display each roll
from random import randint 
def d(sides): 
    return randint(1, sides) 
def roll(n, sides): 
    return tuple(d(sides) for _ in range(n))
def dice(n, sides):
    print (roll(n, sides))
    return sum(dice)
print(dice(3,20))

Upvotes: 0

Views: 6550

Answers (2)

NanotechMagus
NanotechMagus

Reputation: 61

Note: This is using Python 3.6 or higher

from random import randint

def roll(roll)

    rolling = []

    try:
        for x in range(int(roll.split('d')[0])):
            rolling.append(randint(1,int(roll.split('d')[1])))
    except Exception as err:
        print(f'I got bungled @_@ \n Error: {err}')

    print(f'You rolled {" ".join(str(x) for x in rolling)} which has a total'
          f' of {sum(rolling)}')

What this function does is take in any dice roll combination (such as 3d10, 10d10, ect), and prints, using an fstring, each of the dice rolled, and then prints the combined total.

Edit: f-strings can be used to condense this down even more as necessary

Upvotes: 1

AChampion
AChampion

Reputation: 30258

You can't just multiple the result of a single call to d(), you need to make n different calls to the d():

from random import randint

def d(sides):
    return randint(1, sides)

def roll(n, sides):
    return tuple(d(sides) for _ in range(n))

dice = roll(3, 20)
print(dice, sum(dice))
# (20, 18, 1) 39

Upvotes: 1

Related Questions