我目前正在尝试为自己制作的游戏记录高分。想法是记录分数,并针对文件检查匹配的用户名。如果它们匹配并且记录的分数在文件上较低,则创建一个新文件,将复制分数较低的一行以外的所有内容,然后记录当前的用户名和分数。然后删除旧文件,然后将新文件重命名以匹配。
不幸的是,这似乎不起作用。该代码似乎无法复制,意味着我必须放入另一个脚本以确保这样做,然后有时记录不正确的结果(较低),然后从错误的位置读取它们(readfile。[row])。我是使用另一种方法还是进一步追求这种方法更好?
import csv, os, sys
def scorewriter():
replac = 0
writein = 1
string_score = str(score)
with open('highscores.txt','r') as csvfile:
highscoresReader=csv.reader(csvfile)
for row in highscoresReader:
for field in row:
#recording high scores
if field == username and string_score > row[1]:
#MUST get to at least here
with open('highscores_temp.txt','a') as csvfiletemp:
highscoresWriter=csv.writer(csvfiletemp)
for row in highscoresReader:
for field in row:
#something wrong here, doesn't sort properly?
if field == username:
writein = 0
replac=1
highscoresWriter.writerow([username,string_score])
else:
highscoresWriter.writerow([field,row[1]])
elif field != username:
continue
elif field == username and string_score <= row[1]:
writin = 0
continue
if writein == 1:
with open('highscores.txt','a') as csvfile:
highscoresnewWriter = csv.writer(csvfile)
highscoresnewWriter.writerow([username,string_score])
if replac == 1:
csvfile.close()
csvfiletemp.close()
os.remove(pathtofile)
答案 0 :(得分:1)
这似乎过于复杂。最好将所有数据读入dict,然后在掌握了分数与高分的逻辑之后。
import csv
def write_score(hs_file_name, username, score):
high_scores = dict()
with open(hs_file_name) as hsfile:
for row in csv.reader(hsfile):
try:
high_scores[row[0]] = row[1]
except IndexError:
pass
if username not in high_scores:
high_scores[username] = score
elif high_scores[username] < score:
high_scores[username] = score
else:
return False
with open(hs_file_name, mode="w") as hsfile:
writer = csv.writer(hsfile)
for k, v in high_scores.items():
writer.writerow([k, v])
return True
例如这样的事情。您甚至可以让它返回True或False,以便您可以判断这是高分游戏。不必制作临时文件,覆盖旧文件会更容易。