I need to make a high scores list to a game, for class, and it has to be stored using a pickled object. I can only get it to where it stores and prints one score, and then every time you play it the score gets overwritten. How can I append and sort it.

Here's the code I have so far:

import cPickle, shelve
player_score=[name, score]
high_scores=open("high_scores.dat", "w")
cPickle.dump(player_score, high_scores)
high_scores.close
high_scores=open("high_scores.dat", "r")
player_score=cPickle.load(high_scores)
print Player_score
high_scores.close

Recommended Answers

All 7 Replies

Looks to me like you have to append more names and scores to your player_score list before you use cPickle. The module cPickle just dumps and loads complete objects, it does not append the present object file.

There is no need to import shelve, since you are not using it.

Looks to me like you have to append more names and scores to your player_score list before you use cPickle. The module cPickle just dumps and loads complete objects, it does not append the present object file.

There is no need to import shelve, since you are not using it.

I was able to append the database, and return the first five scores. I just need to sort it, so that the highest scores are the first.

vegaseat, it was my understanding that pickle took an object that acted like a definition(player_score), and dumped it in a database(high_scores).

import cPickle
    player_score=(name, score)
    high_scores=open("high_scores.dat", "a")
    cPickle.dump(player_score, high_scores)
    high_scores.close
    high_scores=open("high_scores.dat", "r")
    try:
        for i in range(5):
            i=cPickle.load(high_scores)
            print i
    except: print "Those are all the scores."
    high_scores.close

am I just appending player_score, or am I appending high_scores with a new and separate player_score each time. If I am appending high_scores with multiple pickled objects, how do I sort high_scores?

Just after I open (high_scores.dat, r), I've tried high_scores.sort(). It comes back 'file' object has no attribute 'sort'.

When I try to sort player_score, I don't get any errors, but it doesn't do anything.

You have to do all your appending and sorting on the list object. Note high_scores is just a file handle to the byte code file "high_scores.dat"

# player scores

import cPickle

def sortTupList_inplace(myList, index):
    """sort a list of tuples by tuple index in-place, high to low, myList will change"""
    myList[:] = [(x[index], x) for x in myList]
    myList.sort()
    myList[:] = reversed([val for (key, val) in myList])  # sore high to low

# make player_score a list of (name, score) tuples
player_score = []
player_score.append(("frank", 88))
player_score.append(("jerry", 68))
player_score.append(("albert", 99))

# test
print "player scores unsorted:"
print player_score  # [('frank', 88), ('jerry', 68), ('albert', 99)]
print

# score is at index 1 in each tuple
sortTupList_inplace(player_score, 1)

print "player scores sorted by score (high to low):"
print player_score  # [('albert', 99), ('frank', 88), ('jerry', 68)]
print

# a different look
print "Player scores:"
for item in player_score:
    print "%-10s%6d" % (item[0], item[1])

print

print "saving object player_score ..."
# high_scores is just a file handle to the byte code file "high_scores.dat"
high_scores = open("high_scores.dat", "w")
cPickle.dump(player_score, high_scores)
high_scores.close

print

print "loading object player_score:"
high_scores = open("high_scores.dat", "r")
player_score = cPickle.load(high_scores)
high_scores.close

# test
print player_score

# if you append more player scores, sort, then save

Thanks vegaseat, but that only allows me to save the scores in a current game, or maybe I'm just missing something:-| . I need to be able to save a score, close out, open a new game, save another score and sort it with the scores from previous games.

Here is the code for the whole game:

def open_file(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except(IOError), e:
        print "Unable to open the file", file_name, "Ending program.\n", e
        raw_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)
    
    points= 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) 
    return category, points, question, answers, correct, explanation
def welcome(title):
    """Welcome the player and get his/her name."""
    print "\t\tWelcome to Trivia Challenge!\n"
    print "\t\t", title, "\n"
        
def main():
    trivia_file = open_file("trivia.txt", "r")
    title = next_line(trivia_file)
    welcome(title)
    score = 0
    
    # get first block
    category, points, question, answers, correct, explanation = next_block(trivia_file)
    name=raw_input("What is your name? ")
    while category:
        # ask a question
        print category
        print question
        for i in range(4):
            print "\t", i + 1, "-", answers[i]
        # get answer
        answer = raw_input("What's your answer?: ")
        # check answer
        if answer == correct:
            print "\nRight!",
            score += int(points)
        else:
            print "\nWrong.",
        print explanation
        print "Score:", score, "\n\n"
        # get next block
        category, points, question, answers, correct, explanation = next_block(trivia_file)
    trivia_file.close()
    print "That was the last question!"
    print "You're final score is:", score
    import cPickle
    player_score=[]
    player_score.append((name, score))
    high_scores=open("high_scores.dat", "a")
    cPickle.dump(player_score, high_scores)
    high_scores.close
    high_scores=open("high_scores.dat", "r")
    try:
        for i in range(5):
            i=cPickle.load(high_scores)
            print i
    except: print "Those are all the scores."
    high_scores.close
  
main()  
raw_input("\n\nPress the enter key to exit.")

And the text file:
An Episode You Can't Refuse
On the Run With a Mammal
3
Let's say you turn state's evidence and need to "get on the lamb." If you wait /too long, what will happen?
You'll end up on the sheep
You'll end up on the cow
You'll end up on the goat
You'll end up on the emu
1
A lamb is just a young sheep.
The Godfather Will Get Down With You Now
2
Let's say you have an audience with the Godfather of Soul. How would it be /smart to address him?
Mr. Richard
Mr. Domino
Mr. Brown
Mr. Checker
3
James Brown is the Godfather of Soul.
That's gonna cost you
4
If you paid the Mob protection money in rupees, what business would you most likely/ be insuring?
Your tulip farm in Holland
Your curry powder factory in India
Your vodka distillery in Russian
Your army knife warehouse in Switzerland
2
The Rupee is the standard monetary unit of India.
Keeping It the Family
3
If your mother's father's sister's son was in "The Family," how are you related /to the mob?
By your first cousin once removed
By your first cousin twice removed
By your second cousin once removed
By your second cousin twice removed
1
Your mother's father's sister is her aunt -- and her son is your /mother's first cousin. Since you and your mother are exactly one generation /apart, her first cousin is your first cousin once removed.
A Maid Man
2
If you were to literally launder your money, but didn't want the green in your /bills to run, what temperature should you use?
Hot
Warm
Tepid
Cold
4
According to my detergent bottle, cold is best for colors that might run.

I haven't had a chance to get through your code in detail. Here is the thought on the high_scores.dat file. You load the previous game's file, and when done append the scores of the present game, sort and save/dump. This way you always have the highest previous scores available. Eventually you might have to limit the file to the ten highest scores or something like that.

You load the previous game's file, and when done append the scores of the present game, sort and save/dump. This way you always have the highest previous scores available.

Please excuse my stupidity, but how do you load the file? I load ("highscores.dat", "a"), but that doesn't seem to do it.

Hi whoru,

You can load pickled data into an object of your choosing by saying:

import cPickle
f = "somefilename.dat"
a = cPickle.load(open(f, "r"))
# Proceed to do things with object a

vegaseat included a comparable set of instructions at the end of his snippet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.