我编写了一个小游戏给我建议画什么。我还实现了一个随机难度,对于简单难度和中等难度都可以,但是当它选择了困难难度时,它会给我一个错误,告诉我变量没有定义。当我通过vscode调试器运行它时,它运行得非常好
# Importing random module
import random
# User input
difficulty = int(input("Please choose your difficultie: 1 = Easy, 2 = Medium, 3 = Hard, 4 = Random difficulty"))
# Adding the random difficulty option
if difficulty == 4:
difficulty = random.randint(0,4)
if difficulty == 1:
difficult = "Easy"
elif difficulty == 2:
difficult = "Medium"
elif difficulty == 3:
difficult = "Hard"
print("The random difficulty that has been chosen is ", difficult)
# Setting up variables
# Heroes
a = "Spiderman, "
b = "Superman, "
c = "Batman, "
# Villains
aa = "fighting the Green Goblin, "
bb = "fighting Doomsday, "
cc = "fighting The Joker, "
# Circumstances
aaa = "on top of a Skyscraper"
bbb = "in the Streets of Metropolis"
ccc = "inside The Batcave"
# Powers
aaaa = "with weather control powers, "
bbbb = "with sound control powers, "
cccc = "without superpowers, "
# Villain Powers
aaaaa = "who is invisible, "
bbbbb = "who has a big laser-beam, "
ccccc = "who has a remotely controlled tornado, "
# Choosing the random variables for easy difficulty
if difficulty == 1:
final_hero = random.choice([a, b, c])
final_villain = random.choice([aa, bb, cc])
final_circumstance = random.choice([aaa, bbb, ccc])
final_string_easy = final_hero + final_villain + final_circumstance
print(final_string_easy)
# Choosing the random variables for medium difficulty
if difficulty == 2:
final_hero = random.choice([a, b, c])
final_villain = random.choice([aa, bb, cc])
final_circumstance = random.choice([aaa, bbb, ccc])
final_power = random.choice([aaaa, bbbb, cccc])
final_string_medium = final_hero + final_power + final_villain + final_circumstance
print(final_string_medium)
# Choosing the random variables for hard difficulty
if difficulty == 3:
final_hero = random.choice([a, b, c])
final_villain = random.choice([aa, bb, cc])
final_circumstance = random.choice([aaa, bbb, ccc])
final_power = random.choice([aaaa, bbbb, cccc])
final_villain_power = random.choice([aaaaa, bbbbb, ccccc])
final_string_hard = final_hero + final_power + final_villain + final_villain_power + final_circumstance
print(final_string_hard)
我们将不胜感激
您正在生成一个从0到3的随机数。当该数为0时,变量困难将保持未定义状态,因为if子句都不匹配0。因此,在打印时,变量困难仍没有值
您的问题是,您提供的选项是
1, 2, 3
,而您使用randint
来选择0, 1, 2, 3, 4
不匹配的选项总的来说,我认为在这种情况下使用
dictionaries
来消除你所面临的所有重复性会有好处。你可以设置两个字典,一个用来处理最后一个句子的parts
。我们可以使用列表中的键和值。接下来我们可以设置我们的options
,它将是来自parts
的keys
。然后我们可以创建另一个字典mode
,它将告诉我们将使用哪些键通过切片option
从parts
中进行选择我将把变量
difficulty
重命名为football
,将difficult
重命名为bananas
,这样您可以更容易地发现错误如果
football
既不是1、2,也不是3,即它是0或4,那么bananas
就不会被定义因此你的错误
我怀疑你想换成
相关问题 更多 >
编程相关推荐