# Python - Highscores system



## Will Watts (Jun 18, 2008)

Hello :wave:

I'm learning python at the moment, one of the "challenges" I'm working on is adding a high scores system for an already existing game. It's meant to save the top 5 scores a pickled list in a text file - unfortunately it's only saving the top two scores, and is overwriting where it should be inserting.

High_scores function code:


```
def highscores(name, the_score):
    """Creates, sorts and displays new highscores"""
    high_scores = []
    try:
        f = open("highscores.dat", "rb+")
        high_scores = pickle.load(f)
    except:
        f = open("highscores.dat", "wb+")

    
    
    # Add users score to high_scores
    
    entry = (int(the_score), name)
    high_scores.append(entry)
    high_scores.sort(reverse=True)
    high_scores = high_scores[:5]

    pickle.dump(high_scores, f)

    #display highscores
    print("\n\n\tHIGHSCORES\nNAME\tSCORE")

    for score in high_scores:
        the_score = score[0]
        name = score[1]
        print(name, "\t", the_score)
    f.close()
```
For some reason this isn't working as intended - it will save the first two scores fine and order them, after that it replaces one of them depending on the score.

Full file:


```
# Trivia Challenge
# Trivia game that reads a plain text file

import sys, pickle

def open_file(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except IOError as e:
        print("Unable to open the file", file_name, "Ending program.\n", e)
        input("\n\nPress the enter key to exit.")
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    """Return next line from the trivia file, formatted."""
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line

def next_block(the_file):
    """Return the next block of data from the trivia file."""
    category = next_line(the_file)
    
    question = next_line(the_file)
    
    answers = []
    for i in range(4):
        answers.append(next_line(the_file))
        
    correct = next_line(the_file)
    if correct:
        correct = correct[0]
        
    explanation = next_line(the_file)

    score = next_line(the_file)
    if score:
        score = score[0]

    return category, question, answers, correct, explanation, score

def welcome(title):
    """Welcome the player and get his/her name."""
    print("\t\tWelcome to Trivia Challenge!\n")
    print("\t\t", title, "\n")
    print("\n\nEnter contestant name:")
    name = input()
    return name

def highscores(name, the_score):
    """Creates, sorts and displays new highscores"""
    high_scores = []
    try:
        f = open("highscores.dat", "rb+")
        high_scores = pickle.load(f)
    except:
        f = open("highscores.dat", "wb+")

    
    
    # Add users score to high_scores
    
    entry = (int(the_score), name)
    high_scores.append(entry)
    high_scores.sort(reverse=True)
    high_scores = high_scores[:5]

    pickle.dump(high_scores, f)

    #display highscores
    print("\n\n\tHIGHSCORES\nNAME\tSCORE")

    for score in high_scores:
        the_score = score[0]
        name = score[1]
        print(name, "\t", the_score)
    f.close()
    
 
def main():
    trivia_file = open_file("trivia.txt", "r")
    title = next_line(trivia_file)
    name = welcome(title)
    the_score = 0

    # get first block
    category, question, answers, correct, explanation, score = next_block(trivia_file)
    while category:
        # ask a question
        print(category)
        print(question)
        for i in range(4):
            print("\t", i + 1, "-", answers[i])

        # get answer
        answer = input("What's your answer?: ")

        # check answer
        if answer == correct:
            print("\nRight!", end=" ")
            the_score += int(score)
        else:
            print("\nWrong.", end=" ")
        print(explanation)
        print("Score:", the_score, "\n\n")
        
        
        # get next block
        category, question, answers, correct, explanation, score = next_block(trivia_file)

    trivia_file.close()

    print("That was the last question!")
    print("You're final score is", the_score)

    highscores(name, the_score)
 
main()  
input("\n\nPress the enter key to exit.")
```
I've also attached the trivia questions to make the program run. The only parts of the program I've written myself are the scoring system, and the High_Scores system - the rest is an example/practice program.


----------

