python - python:记录分数/用户并显示前10名
问题描述
作为工作练习的一部分,我正在 python 3.6.3 中进行琐事练习。我让整个脚本成功运行并在最后正确触发响应,同时正确计算分数。它开始像这样:
#!python3.6
## greet user, take name, explain rules ##
print ('HELLO! WELCOME TO MY MOVIE TRIVIA QUIZ. \n')
name = input('WHAT IS YOUR NAME?')
print ('\n WELCOME TO THE THUNDERDOME ' + name + '! SHALL WE PLAY A GAME? \n')
print ('I WILL ASK YOU 10 MOVIE TRIVIA QUESTIONS AND YOU SHALL HAVE 3 CHOICES FOR ANSWERS.\n \n PLEASE ANSWER IN A ABC FORMAT.\n \n CHOOSE WISELY, FOR YOU SHALL BE JUDGED\n')
print ('IMPORTANT DISCLAIMER FOR MORTALS : PLEASE KEEP YOUR CAPS LOCK ON')
print ('\n-----------------------------------------------------------\n')
##set the score at 0##
score = 0
score = int(score)
这会重复 10 个以以下结尾的问题:`#### 带有 if/elif 参数的最终分数。百分比阈值已设置,因此我可以添加更多问题,并且我正在研究如何设置某种记录分数功能或与用户一起获得最高分板。
####
print ('Prepare to be judged: ' + str(score) + ' out of 10')
percentage = (score/10)*100
print ('The verdict is:', percentage)
if percentage < 20.0:
print ('I Dont normally judge people, but you need to see more movies and have no culture.')
elif percentage >=20.1 and percentage <=40.0:
print ('Nice, there is some hope for you.')
elif percentage >=40.1 and percentage <=60.0:
print ('Ohhhh, you fancy yourself a trivia buff? step correct next time.')
elif percentage >=60.1 and percentage <=80.0:
print ('Color me impressed! You are getting closer.')
elif percentage >=80.1 and percentage <=99.9:
print ('You are gonna break the game, you are on fire!.')
if percentage ==100.0:
print ('I HAVE VIEWED UPON YOUR MIND AND DEEMED THAT YOU ARE WORTHY OF GODHOOD')
print ('\n-----------------------------------------------------------\n')
我想做的是记录分数/用户并在最后显示前 10 名并使其保持不变。我很难找到类似的好源示例,因此我将不胜感激。
解决方案
我建议在用户完成测验后,将他们的结果附加到这样的文件中:
# Writing high scores to file
file = open('highscores.txt','a')
name='foo';score=78
file.write(name + " " + str(score) + "\n")
name='bobby';score=56
file.write(name + " " + str(score) + "\n")
file.close()
然后读取该文件,按分数排序,并打印结果:
# Reading/Printing the output
file = open('highscores.txt').readlines()
scores_tuples = []
for line in file:
name, score = line.split()[0], float(line.split()[1])
scores_tuples.append((name,score))
scores_tuples.sort(key=lambda t: t[1], reverse=True)
print("HIGHSCORES\n")
for i, (name, score) in enumerate(scores_tuples[:10]):
print("{}. Score:{} - Player:{}".format(i+1, score, name))
HIGHSCORES
1. Score:99.0 - Player:joe
2. Score:78.0 - Player:foo
3. Score:56.0 - Player:bobby
推荐阅读
- android - 为什么同一个pt在不同设备下显示不同大小
- java - 如何使用 jnetpcap 读取特定端口中的 rtp 流
- php - 如何使用 ajax 从 PHP 循环逐步更新 div?
- c# - 如何使用c#从gridview映射两个不同的值
- android - 如何将 FirebaseVisionImage 转换为位图
- c# - 如何在没有类对象的情况下反序列化它?
- javascript - 有时当我按下按钮时它工作有时它不起作用
- javascript - 这个数字排序器有点麻烦
- android - 如何从 android listview 中删除多个选定项目并将其从适配器中删除?
- nlp - 文本分类 - 你能做什么与你的能力是什么?