简体   繁体   English

Python 我正在尝试制作一个骰子滚轮,它可以增加总数并掷出多种骰子

[英]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.为了更熟悉python,我想为龙与地下城制作一个掷骰子,但遇到了问题。 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.我已经到了输入诸如“d4 + d6”之类的东西并以字符串形式获取诸如 1+5 之类的东西的地步,但是,我希望将随机数加在一起。 However, when I tried to print them as an int I got.但是,当我尝试将它们打印为 int 时,我得到了。 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回溯(最近一次调用最后一次):文件“C:\\Users[redacted]\\PycharmProjects\\DndDice\\main.py”,第 11 行,在 print(int(roll)) 中 ValueError: invalid literal for int() with base 10: '1 + 3' 我的代码是

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))

I think your main issue is that you're trying to convert a string into an int.我认为您的主要问题是您试图将字符串转换为 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.由于您已经在解析“d4”和“d6”,因此只需在解析时存储您滚动的数字,而不是重新组合新字符串并再次解析。

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.一个问题是它只解析每个输入的一个“d4”和“d6”,但我相信这可以通过某种 for 循环而不是 if 语句来解决。

Side note: I believe that randrange is non inclusive on the upper limit.旁注:我相信 randrange 不包含上限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM