python - 我已经设置了一个 RNG 和一个继续按钮,但它不会在继续后更新结果
问题描述
#Setting up RNG
loop = "y"
while loop == "y" or loop == "yes":
from random import randint
dice = (randint(1,10))
dice2 = (randint(1,10))
roll = (dice + dice2)
win = 3
loss = 2
cash = 20
if roll == 3 or roll == 7 or roll == 11 or roll == 17:
cash += (win)
else:
cash -= (loss)
#Starting game
print("""Welcome to, Gambling for School!
You have $20 and must earn as much money as possible
If you roll a 3, 7, 11, or 17, you will win $3 but any other number
takes $2
You have a 20% of winning
""")
x = input("Press ENTER to start.")
#Results
if roll == 11 or roll == 8 or roll == 18:
print("You rolled an " + str(roll) + "!")
else:
print("You rolled a " + str(roll) + "!")
print("")
print("Cash - $" + str(cash))
loop = input("Continue? (Y/N) ").lower()
必须更改缩进以将其显示为代码
当它运行时,我按回车键开始游戏,它正确地加减,但是当我选择继续时,它就像我从来没有输过或赢过任何钱一样。如果我的大脑死了,现在是凌晨 1 点,但我想不出任何办法来解决它
解决方案
您在每场比赛前cash
重新初始化变量。20
要修复游戏,只需将该代码移出循环即可。
和的初始化 win
也loss
可以移出循环,因为它们不会改变。
from random import randint
语句也一样,将所有导入语句放在文件顶部被认为是一种好习惯。
from random import randint
#Setting up RNG
loop = "y"
win = 3
loss = 2
cash = 20
while loop == "y" or loop == "yes":
dice = (randint(1,10))
dice2 = (randint(1,10))
roll = (dice + dice2)
if roll == 3 or roll == 7 or roll == 11 or roll == 17:
cash += win
else:
cash -= loss
#Starting game
print("""Welcome to, Gambling for School!
You have $20 and must earn as much money as possible
If you roll a 3, 7, 11, or 17, you will win $3 but any other number
takes $2
You have a 20% of winning
""")
x = input("Press ENTER to start.")
#Results
if roll == 11 or roll == 8 or roll == 18:
print("You rolled an " + str(roll) + "!")
else:
print("You rolled a " + str(roll) + "!")
print("")
print("Cash - $" + str(cash))
loop = input("Continue? (Y/N) ").lower()
推荐阅读
- python - Why plt.savefig reduced the original size of an image?
- java - 如何在 HTML 页面上显示 PDF
- selenium - 超时异常不起作用,元素不可交互硒
- javascript - 这是将类组件转换为钩子组件的最佳方法吗?
- java - 如何在 Java swing 中用 ImageIcon 填充形状?
- c - 数组初始值设定项和指针混淆
- c++ - 如何公开分配资源的线程安全接口?
- ios - 尝试从 Firebase 存储桶上传图片时,Flutter 应用程序崩溃
- python - 如何在 Python 中解决非线性编程问题?
- javascript - 将日期转换为不同的格式会在 Angular 中产生无效的日期错误