HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Saving high scores in a pickle database

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
picklehighdatabasescoressaving

Problem

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()

Solution


  • Use of global should generally be avoided. You could create a class to hold the dictionary and the three functions would become methods.



  • Don't repeat yourself: use a variable for the file name so you don't have to change it in three places if it needs to change.



  • The save_score function assigns new_score = (name, score) for no reason at all. Using the two variables directly in the code that follows would improve readability.

Context

StackExchange Code Review Q#54117, answer score: 13

Revisions (0)

No revisions yet.