python - 在 Python 返回分数时遇到石头剪刀布代码问题
问题描述
我正在用 Python 创建一个石头剪刀布程序,这部分当然非常简单。问题在于我需要在列表末尾返回分数。我让玩家可以根据他们的输入选择玩多少次,最后根据玩过的次数给出最终分数。每当我运行代码时,我都会在每场比赛后获得分数,以确保它运行正确,但是当我输入“2”退出时,分数显示为 0 0 0。任何帮助将不胜感激。这是代码。
import random as r
def main():
"""
Asks user if they want to play and keeps track of score until player exits
"""
tie_score = 0
human = 0
opponent = 0
choice = input('Enter 1 to play or 2 to exit: ')
play_again = ['1', '2']
while choice not in play_again:
# determine if user input is valid to start the game
print('Invalid choice.')
choice = input('Enter 1 to play or 2 to exit: ')
else:
while choice == '1':
play_game(tie_score, human, opponent)
choice = input('Enter 1 to play or 2 to exit: ')
def computer_choice():
"""
computer generates rock, paper, or scissors by using random module
"""
options = ['Rock', 'Paper', 'Scissors']
choice = r.choice(options)
return choice
def play_game(tie_score, human, opponent):
"""
Determines win, lose, or tie based on user input. Returns score
"""
user_options = ['Rock', 'Paper', 'Scissors']
user = input('Enter Rock, Paper, or Scissors: ')
computer = computer_choice()
while user not in user_options:
# Validates user input, allowing only rock, paper, or scissors
print('Please enter Rock, Paper, or Scissors')
user = input('Enter Rock, Paper, or Scissors: ')
else:
# determines who wins, or tie
if user == computer:
print('Computer chooses %s, tie' % computer)
tie_score += 1
elif (user == 'Rock') and (computer == 'Scissors'):
print('Computer chooses %s, win' % computer)
human += 1
elif (user == 'Paper') and (computer == 'Rock'):
print('Computer chooses %s, win' % computer)
human += 1
elif (user == 'Scissors') and (computer == 'Paper'):
print('Computer chooses %s, win' % computer)
human += 1
else:
print('Computer chooses %s, lose' % computer)
opponent += 1
return tie_score, human, opponent
main()
解决方案
这里的问题是您从未真正保存从play_game()
函数返回的分数。当您调用play_game()
函数main()
时,您需要为结果分配一个变量,例如:
scores = play_game()
然后您可以访问分数,以便将它们添加到主函数中的列表中,以便在主 while 循环退出时打印或返回:
def main():
...
score_list = []
...
scores = play_game()
score_list.append(scores)
一般来说,最好不要简单地将代码转储到问题中,最好只给出函数名称并用最简单的术语解释它们的作用。将来,请尝试限制您发布的代码量。
推荐阅读
- javascript - Kendo Grid ASP.Net 更新错误的行
- android - 您如何获得 Android 中最近的应用程序列表?
- javascript - 如何循环思维图并创建特定对象?使用 Javascript
- python - 给定起点的矩阵中的最大和路径
- scala - 如何将案例对象用作案例类中的字段并转换为 Spark DataSet?
- r - 由于更改了 Web 结构,将 Web 表复制到 ms excel 不再起作用
- python - 尝试从数据框中提取单个值,但改为提取数组
- python - 损失在 Keras ANN 的所有时期都变成“南”(回归)
- .net - 在 DataGridView 中单击一个复选框时如何切换所有选定行中的所有复选框
- android - 我的开关没有转到我的风格颜色