Seeking to improve upon my high score 'module' code. It saves users' high score in a pickle database and if needed prints out the current scores in the database.
import pickle
import os
global high_scores
def setup_scores():
global high_scores
high_scores = {}
if os.path.isfile('highscores.pkl'):
with open("highscores.pkl", "rb") as h:
high_scores = pickle.load(h)
else:
high_scores = {"Adam Smith": 65536, "John Doe": 10000}
def save_score(name, score):
new_score = (name, score)
if new_score[0] in high_scores:
if new_score[1] > high_scores[new_score[0]]:
high_scores[new_score[0]] = new_score[1]
else:
high_scores[new_score[0]] = new_score[1]
with open("highscores.pkl","wb") as out:
pickle.dump(high_scores, out)
def print_scores():
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))
setup_scores()
save_score(raw_input('Name:'), raw_input('Score:')) # inputs only for testing, can use variables instead
print_scores()