我对Python很陌生。我想在Python中保持高分,并且只写新球员的名字。我想在一个更大的程序中实现它,但我还不能完全理解这个逻辑。
你如何处理一个比以前更好的老玩家? 你如何处理两个同名的球员有分数?
save_name = raw_input('Enter your name. ').title()
save_score = raw_input('Enter your score. ')
text_file = open("highscores.txt", "a")
text_file.write("\n" + save_name + ' has a score of ' + save_score + "\n")
text_file.close()
print ("\n")
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print (whole_thing)
text_file.close()
答案 0 :(得分:2)
我假设您的目标是阅读高分并仅添加新玩家所做的分数。如果是这样,你要问的问题是:
就我个人而言,我不会在文本文件中执行此操作,而是将其写入字典并pickle
。
import pickle
high_scores = {"Adam Smith": 65536, "John Doe": 10000}
with open("highscores.pkl","wb") as out:
pickle.dump(high_scores, out)
然后当你必须写一个新的分数时:
import collections
Score = collections.namedtuple("Score", ["name","score"]) # just to make things easy
new_score = Score("Joe Schmoe",12000)
with open("highscores.pkl","rb") as in_:
high_scores = pickle.load(in_)
if new_scores.name not in high_scores:
high_scores[new_scores.name] = new_scores.score
with open("highscores.pkl","wb") as out:
pickle.dump(high_scores, out)
这在显示高分时也会有所帮助,因为您可以执行以下操作:
print("{{TITLE:^{PAGE_WIDTH}}}".format(PAGE_WIDTH=80).format(TITLE="HIGH SCORES"))
print("-" * 80)
for name,score in high_scores.items():
print("{{name:>{col_width}}} | {{score:<{col_width}}}".format(col_width=(80-3)//2).format(name=name, score=score))
此位的格式对于您的用例来说有点过分,但如果您需要在较小的屏幕上显示(每页较少的列数),您以后会感谢我!将所有80
替换为常量,并将每页的列放在常量中,例如MAX_WIDTH
。容易腻。
答案 1 :(得分:1)
首先,text_file.readlines(save_name)
会抛出TypeError
,因为save_name
不是整数。见the readlines documentation。其次,由于您没有将变量赋值给readlines
的返回值,因此该行不会执行任何操作。我不完全确定你在这里想要实现的目标。这部分代码工作正常:
save_name = raw_input('Enter your name. ').title()
save_score = raw_input('Enter your score. ')
text_file = open("highscores.txt", "a")
text_file.write("\n" + save_name + ' has a score of ' + save_score + "\n")
text_file.close()
它将正确写入highscores.txt
文件。
如果你想打印highscores文件的内容,你的代码的最后一部分就是这么做。
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print (whole_thing)
text_file.close()
这两个引用块之间的部分可能已经过时和/或我们需要更好地规范您要实现的目标。
答案 2 :(得分:1)
使用您的代码我做了一些更改,首先检查高分,只有在用户击败最后得分时才添加新分数:
save_name = raw_input('Enter your name. ').title()
save_score = raw_input('Enter your score. ')
last_high_score = 0
#look for highscore
try:
text_file = open("highscores.txt", "r")
for line in text_file.readlines():
#you can use regular expressions here to simplify the lookup
#get the las part of the score assuming the pattern:
#"text[ has a score of] score"
line_parts = line.split(" has a score of ")
if len(line_parts) > 1:
#removing the end \n character
line_parts = line_parts[-1].split("\n")
score = line_parts[0]
#compare the last high score with the newest
if score.isdigit() and int(score) > last_high_score:
last_high_score = int(score)
except Exception, e:
#the first time trows an exception because the high score file does not exist
pass
#check if there is a new high score
if int(save_score) > last_high_score:
text_file = open("highscores.txt", "a")
text_file.write("\n"+save_name+' has a score of '+save_score+"\n")
text_file.close()
print ("\n")
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print (whole_thing)
text_file.close()
答案 3 :(得分:1)
ave_name = raw_input('Enter your name. ').title()
save_score = raw_input('Enter your score. ')
last_high_score = 0
#look for highscore
try:
text_file = open("highscores.txt", "r")
for line in text_file.readlines():
#you can use regular expressions here to simplify the lookup
#get the las part of the score assuming the pattern:
#"text[ has a score of] score"
line_parts = line.split(" has a score of ")
if len(line_parts) > 1:
#removing the end \n character
line_parts = line_parts[-1].split("\n")
score = line_parts[0]
#compare the last high score with the newest
if score.isdigit() and int(score) > last_high_score:
last_high_score = int(score)
except Exception, e:
#the first time trows an exception because the high score file
pass
#unban user14762509 moderator fags
#check if there is a new high score
if int(save_score) > last_high_score:
text_file = open("highscores.txt", "a")
text_file.write("\n"+save_name+' has a score of '+save_score+"\n")
text_file.close()
print ("\n")
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print (whole_thing)
text_file.close()
答案 4 :(得分:0)
如果你只想写用户的名字,而不是他们的高分,你不能只改变这个:
text_file.write(“\ n”+ save_name +'得分为'+ save_score +“\ n”)
对此:
text_file.write(“\ n”+ save_name +“\ n”)
答案 5 :(得分:0)
我不确定这有帮助吗
import time
import operator
startTime=time.time()
x=input('testonly')
endTime=time.time()
userscore=int(endTime-startTime)
scorelist=[]
beathighscore=False
scorefile=open('score.txt','r')
score=scorefile.readlines()
scorefile.close
for line in score:
scorelist.append(line.strip())
if len(score)!=0:
for item in scorelist:
oldscore=((item[0])[1])
oldscore=int(oldscore)
else:
oldscore=float('inf')
if userscore<oldscore:
print("you beat the highscore")
username=input("pls enter ur name")
newscore=(username,userscore)
scorelist.append(newscore)
with open('score.txt',"w") as writescore:
for item in scorelist:
writescore.write(''.join(str(item))+'\n')
writescore.close