Python Pickles
Results 1 to 2 of 2

Thread: Python Pickles

  1. #1
    Senior Member IcSilk's Avatar
    Join Date
    Aug 2001
    Posts
    296

    Python Pickles

    I have avoided coming here to AO about this certain topic for a long time. Instead I have joined a forum specifically dedicated to the python language.
    Its a good forum, I like it and have learnt alot from there already, but I like AO better and it always helps to get things from different perspectives.
    I have been having alot of trouble building a highscores list for a game in python. My instructions are to use pickled objects to populate a high score list.
    I have done this ... or thought that I have. Problem is no matter what I do I can only get the first score to print out.
    I've been messing with this for about 3 weeks and really want to move on.
    I have finally decided to come here to ask for some input.

    Here is the full game code:

    Code:
    # Trivia Challenge
    # Trivia game that reads a plain text file
    
    # (added a scoring system to Trivia Challenge)
    # added a pickle file to keep track of high scores
    
    import sys, pickle
    
    def user_name():
        name = input("Hello, what is your name? ")
        #score = 0
        name = name.title()
        #high_scores = {name: score}
        return name
       
    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)
        
        try:
            score = int(next_line(the_file))
            #score = int(score)
        except ValueError:
            score = 0
    
        return category, question, answers, correct, explanation, score
    
    def welcome(title, name):
        """Welcome the player and get his/her name."""
        print("\n\t\tWelcome to Trivia Challenge,", name, "!\n")
        print("\t\tThis is", title, "\n")
    
    def create_name_list(name):
        name_list = [name]
        #if name_list:
            #name_list.append(name)
        
        return name_list
    
    def create_score_list(new_score):
        score_list = [new_score]
        #score_list.append(new_score)
        return score_list
    
    def store_scores(name, new_score):
        f = open("pickledScores.dat", "rb+")
        try:
            y = pickle.load(f)
        except EOFError:
            f.close()
            f = open("pickledScores.dat", "wb")
            name_list = [name]
            pickle.dump(name_list, f)
            print('x')
        else:
            name_list = [name]
            name_list.append(y)
            
            pickle.dump(name_list, f)
            f.close()
        #z= pickle.load(f)
        #y.append(name)
        #z.append(new_score)
        #pickle.dump(y, f)
        #pickle.dump(z, f)
        
    
    def print_scores(score_list):
        f = open("pickledScores.dat", "rb")
        #full_name_list = name_list.append(name_list)
        #full_score_list = score_list.append(score_list)
        #print(full_name_list, full_score_list)
        y = pickle.load(f)
        #name_list_length = len(y)
        #for i in range(name_list_length):
            #print("\t", i + 1, "-", y[i], "\t - \t", score_list[i])
        print(y)
        #print(z)
        f.close()
         
    def main():
        name = user_name()
        trivia_file = open_file("trivia2.txt", "r")
        title = next_line(trivia_file)
        welcome(title, name)
        new_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=" ")
                print("\nYou earned", score, "points.")
                new_score += score
                print("Your new score is:", new_score, "\n\n")
            else:
                print("\nWrong.", end=" ")
                print(explanation)
                print("Your score is still:", new_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", new_score)
     
        if new_score >=90:
            print("\n\nCongratulations", name, "you've made the high score list!!")
            name_list = create_name_list(name)
            score_list = create_score_list(new_score)
            store_scores(name, new_score)
            
            print_scores(score_list)
        else:
            print("\n\nSorry, ", name, "but", new_score, "is not good enough to make the high score list.")
            print("Use the explanations to your wrong answers and try again.")
    
    main()
    input("\n\nPress the enter key to exit.")
    My problems, I believe, lie within these two functions:

    Code:
    def store_scores(name, new_score):
        f = open("pickledScores.dat", "rb+")
        try:
            y = pickle.load(f)
        except EOFError:
            f.close()
            f = open("pickledScores.dat", "wb")
            name_list = [name]
            pickle.dump(name_list, f)
            print('x')
        else:
            name_list = [name]
            name_list.append(y)
            
            pickle.dump(name_list, f)
            f.close()
        #z= pickle.load(f)
        #y.append(name)
        #z.append(new_score)
        #pickle.dump(y, f)
        #pickle.dump(z, f)
        
    
    def print_scores(score_list):
        f = open("pickledScores.dat", "rb")
        #full_name_list = name_list.append(name_list)
        #full_score_list = score_list.append(score_list)
        #print(full_name_list, full_score_list)
        y = pickle.load(f)
        #name_list_length = len(y)
        #for i in range(name_list_length):
            #print("\t", i + 1, "-", y[i], "\t - \t", score_list[i])
        print(y)
        #print(z)
        f.close()
    I just can't figure out where Im going wrong with the pickling and unpickling. I have deleted, commented out, copied, pasted, deleted and experimented with so many different things I've gotten lost in my own thought.

    I want to learn this, I want to get this and I want to move on. What am I not getting?
    BTW, if it matters its python 3.2

    Blessings
    F
    "In most gardens they make the beds too soft - so that the flowers are always asleep" - Tiger Lily

  2. #2
    Senior Member IcSilk's Avatar
    Join Date
    Aug 2001
    Posts
    296
    Hmmm almost 60 views and no replies .... good, I can take all the credit for finally figuring it out myself.
    I really had to get this off of my chest - because it feels soooo F#$% - ing good. Many hours, many posts, much frustration, many times almost giving up - I finally got this high score list to work properly. And it was such a simple thing.... I had a function to create the name list and one to create the score list, then for some stupid reason I re-created each list in the function to store the high score list. I even got to have a bit of fun with nesting try/except/else blocks .. oh joy!!

    heres the finished function product, if anyone cares:

    Code:
    def store_scores(name_list, score_list):
        try:
            f = open("pScores.dat", "rb")
        except IOError:
            f = open("pScores.dat", "wb")
            pickle.dump(name_list, f)
            pickle.dump(score_list, f)
        else:
            try:
                y = pickle.load(f)
                z = pickle.load(f)
            except EOFError:
                f.close()
                f = open("pScores.dat", "wb")
                pickle.dump(name_list, f)
                pickle.dump(score_list, f)
            else:
                f.close
                f = open("pScores.dat", "wb")
                name_list.extend(y)
                score_list.extend(z)
                pickle.dump(name_list, f)
                pickle.dump(score_list, f)
                f.close()
    Im sure there's a way to neaten this up a bit, if anyone has any suggestions on that I'm game. But for right now Im a real happy Python newb

    I even got the formatting to work right in the print function. I have only to sort the list high -> low and make it so it only shows the top 5. I already have in my head how to do this, and its not a complex thing.

    My only concern is that there is alot of opening and closing of files in this function (above). I'm going to experiment with different access modes .... tomorrow. Im enjoying a victory right now :P



    *HICCUP*
    "In most gardens they make the beds too soft - so that the flowers are always asleep" - Tiger Lily

Similar Threads

  1. Python 2.5 Released
    By HTRegz in forum General Computer Discussions
    Replies: 0
    Last Post: September 19th, 2006, 08:28 PM
  2. Developing a Port Scanner in Python
    By HTRegz in forum The Security Tutorials Forum
    Replies: 12
    Last Post: January 28th, 2006, 08:02 PM
  3. Python Introduction
    By HTRegz in forum Other Tutorials Forum
    Replies: 20
    Last Post: September 10th, 2005, 08:28 AM
  4. Beginning Network Programming in Python
    By PacketThirst in forum Other Tutorials Forum
    Replies: 2
    Last Post: August 14th, 2005, 08:16 PM
  5. Basic Python Tutorial for Newbies
    By [pHA]XeNoCiDe in forum AntiOnline's General Chit Chat
    Replies: 11
    Last Post: July 8th, 2002, 08:56 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •