我正在制作一个D& D风格的角色生成器,我正在为他们滚动统计数据,并允许他们将它们分配到他们想要的能力分数。我希望能够以相同的统计数据开始,而不是重新整个部分。
这就是我所拥有的
from random import randint
def char_stats():
# roll 4 D6s drop the lowest number and add the highest 3
s1,s2,s3,s4,s5,s6 = ([],[],[],[],[],[])
for x in range(4):
s1.append(randint(1,6))
s2.append(randint(1,6))
s3.append(randint(1,6))
s4.append(randint(1,6))
s5.append(randint(1,6))
s6.append(randint(1,6))
stat1 = sorted(s1)
stat2 = sorted(s2)
stat3 = sorted(s3)
stat4 = sorted(s4)
stat5 = sorted(s5)
stat6 = sorted(s6)
return sum(stat1[1:]),sum(stat2[1:]),sum(stat3[1:]),sum(stat4[1:]),sum(stat5[1:]),sum(stat6[1:])
a = list(char_stats())
print "Please choose one of the following for your stat: {}".format(a)
while len(a) > 0:
try:
Strength = int(raw_input('Please input one of these stats for your Strength:\n'))
if Strength in a:
a.remove(Strength)
print a
Wisdom = int(raw_input('Please input one of these stats for your Wisdom:\n'))
if Wisdom in a:
a.remove(Wisdom)
print a
Intelligence = int(raw_input('Please input one of these stats for your Intelligence:\n'))
if Intelligence in a:
a.remove(Intelligence)
print a
Constitution = int(raw_input('Please input one of these stats for your Constitution:\n'))
if Strength in a:
a.remove(Constitution)
print a
Dexterity = int(raw_input('Please input one of these stats for your Dexterity:\n'))
if Dexterity in a:
a.remove(Dexterity)
print a
Charisma = int(raw_input('Please input one of these stats for your Charisma:\n'))
if Charisma in a:
a.remove(Charisma)
except ValueError:
print "Incorrect Input"
continue
我已经尝试嵌套每个if语句(我认为这是非常糟糕的形式)并且具有类似的结果。我也尝试将所有输入分组到try而不是计算中,并得到了相同的结果。有什么建议吗?
答案 0 :(得分:1)
您需要对输入的格式(int)使用“循环直到有效”逻辑,并且值(在滚动统计列表中是否为?)。基本逻辑是:
while True:
# get input
# check input
# if input is valid,
# break
在您的情况下,这看起来像
while True:
user = input("Please enter a stat to use")
if user.isnumeric():
stat_choice = int(user)
if stat_choice in a:
break
现在,为了使有效使用它,您需要对六个统计数据进行参数化并将它们放入循环中:
stat_name = ["Strength", "Wisdom", ...]
player_stat = [0, 0, 0, 0, 0, 0]
for stat_num in range(len(player_stat)):
while True:
user = input("Please input one of these stats for your" + \
stat_name[stat_num] + ": ")
# Validate input as above
player_stat[stat_num] = stat_choice
请注意,您可以将 char_stats 例程缩短为几行。
这会让你感动吗?
答案 1 :(得分:0)
您的代码中至少有一个函数(char_stats
),所以我觉得您知道如何执行函数。
这是一个使用函数的好地方。
对于这段代码,我的建议是编写一个函数,其中包含try / except,问题的提问以及对统计信息列表的检查。
这样的事情:
def pick_a_stat(stats, prompt):
"""Prompt the user to pick one of the values in the `stats` list,
and return the chosen value. Keep prompting until a valid entry
is made.
"""
pass # Your code goes here.