Kyros Ervin
Kyros Ervin

Reputation: 1

Python I'm trying to make a dice roller that adds the totals and rolls multiple kinds of dice

As a way to get more familiar with python, I wanted to make a dice roller for Dungeon and Dragons but I ran into a problem. I had gotten to the point where I input something like "d4 + d6" and get something like 1+5 as a string but, I wanted the random numbers to be added together. However, when I tried to print them as an int I got. Traceback (most recent call last): File "C:\Users[redacted]\PycharmProjects\DndDice\main.py", line 11, in print(int(roll)) ValueError: invalid literal for int() with base 10: '1 + 3' My code is

import random 
while 1 == 1
d4 = random.randrange(1, 4)
d6 = random.randrange(1, 6)
roll = input("Roll a >")
if "d4" in roll:
    roll = roll.replace("d4", '{d4}')
if "d6" in roll:
    roll = roll.replace("d6", '{d6}')
roll = roll.format(d4 = d4, d6 = d6)
print(int(roll))

Upvotes: 0

Views: 282

Answers (1)

William Currier
William Currier

Reputation: 66

I think your main issue is that you're trying to convert a string into an int. Although this is possible with some parsing; I think the easiest way to do it is to store the numbers as you roll them. Since you're already parsing for "d4" and "d6" just store the numbers you roll as you parse rather than reassembling a new string and parsing again.

Here's an example:

import random 
while 1 == 1:
    roll = 0
    d4 = random.randrange(1, 5)
    d6 = random.randrange(1, 7)
    
    roll_text = input("Roll a > ")
    if "d4" in roll_text:
        roll += d4
    if "d6" in roll_text:
        roll += d6
    print(roll)

One issue with this is that it's only parsing for one "d4" and "d6" per input, but I believe that could be fixed with some sort of for loop rather than the if statement.

Side note: I believe that randrange is non inclusive on the upper limit.

Upvotes: 1

Related Questions