我有个问题。我的代码有一个def main():即使在用户输入重新启动后,我也希望保留分数。问题是循环结束后分数再次变为100。我怎样才能解决这个问题
import random
print("Welcome to Python Acey Ducey Card Game")
print()
print("Acey-ducey is played in the following manner: the dealer (computer) deals two cards faced up and you have an option to bet or not bet depending on whether or not you feel the card will have a value between the first two. If you do not want to bet, enter a $0 bet.")
print()
def main():
bankbalance = 100
print("These cards are open on the table:")
print()
print("First card:")
firstcard = random.randint(1,13)
print(firstcard)
print("Second card:")
secondcard = random.randint(1,13)
print(secondcard)
playerinput = input("Enter your bet: ")
playerinput = int(playerinput)
dealercard = random.randint(1,13)
dealercard = int(dealercard)
print("The card you drew was", (dealercard), "!")
if dealercard > firstcard and dealercard < secondcard or dealercard < firstcard and dealercard > secondcard:
print("You win!")
bankbalance = bankbalance + playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again yes/no: ")
if playagain == ("yes"):
main()
else:
exit
else:
print("You lost!")
bankbalance = bankbalance - playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again yes/no: ")
if playagain == ("yes"):
main()
else:
exit
main()
正如khelwood在评论中指出的,在这种情况下,实际循环比重复循环要好。如果在
main
内部调用main
,则在不需要的情况下,会越来越深入地进行嵌套函数调用。通过while
循环,您可以继续执行某些操作,直到某个条件不再为真。一个函数既可以接受参数,也可以返回一个值,这样每次游戏都可以从不同的平衡点开始我做了一些其他的调整。我用链式
<
比较重写了你的赢/输支票,并将它们分成两行以便于阅读。在括号内,可以添加换行符,而不会影响代码执行。Python也会自动组合以这种方式分解的字符串,这就是我在介绍文本中所做的。我还修改了一些变量打印以使用f-strings另外,请注意,您的代码目前允许您下注超过您的赌注,并且在您为负数时继续下注。如果这不是故意的,想想你可以如何避免
我刚刚完成了与上面类似的解决方案。在玩了2轮或更多轮之后,递归调用会很明显
将分数定义为
main
之外的全局变量:编辑:我知道有更好的方法来实现OP想要的东西。不过,我的目标是帮助他改进自己的代码,首先向他解释代码的问题所在,从而帮助OP从错误中吸取教训
相关问题 更多 >
编程相关推荐