import random
def rps():
user_score = 0
comp_score = 0
scoreboard = f'You: {user_score} \nComp: {comp_score}'
while user_score < 3 or comp_score < 3:
choice = ['r', 'p', 's']
user = input('Choose [r] [p] or [s]: ')
user = user.lower()
comp = random.choice(choice)
outcome = f"You chose {user} and I chose {comp}"
if user == comp:
print(scoreboard)
print(outcome)
print('Tie Game')
elif user == 'r' and comp == choice[2] or user == 'p' and comp == choice[0] or user == 's' and comp == choice[1]:
user_score += 1
print(scoreboard)
print(outcome, '\nYou win!')
else:
comp_score += 1
print(scoreboard)
print(outcome, '\nI win')
print(scoreboard)
字符串
我试着把分数和记分板放在while循环中,把它放在函数之外。我不知道还能做什么
2条答案
按热度按时间qybjjes11#
在代码中,
scoreboard
在开始时被设置为'You: 0 \nComp: 0'
。当包含的变量发生变化时,它不会自动更新。要更新scoreboard
,你应该在循环中移动F-String(并且只移动F-String):字符串
这稍微改变了打印的顺序,因为我想避免复制F字符串。您可以将
scoreboard = ...
和print
放入一个函数,比如print_scoreboard
,然后调用它来恢复打印的顺序。gcuhipw92#
分数不会更新,因为记分板是在函数中定义的。有很多方法可以解决这个问题,一种方法是定义你自己的函数来更新记分板,如下所示:
字符串
就我个人而言,我会把scoreboard、user_score和comp_score这些变量都放在def之外,然后把变量传递到函数中。然而,我提供的示例与您编写它的风格一致。