Hey everyone, I need help with a Python issue. This is what I have so far:

scores = []

choice = None
while choice != "0":

    print \
    """
    High Scores Keeper
    
    0 - Quit
    1 - List Scores
    2 - Add a Score
    """
    
    choice = raw_input("Choice: ")
    print

    
    if choice == "0":
        print "Good-bye."

   
    elif choice == "1":
        print "High Scores\n"
        print "NAME\tSCORE" 
        for entry in scores:
            score, name = entry    
            print name, "\t", score

    
    elif choice == "2":
        name = raw_input("What is the player's name?: ")
        score = int(raw_input("What score did the player get?: "))
        entry = (score, name)
        scores.append(entry)
        scores.sort()
        scores.reverse()        
        scores = scores[:5]     
    else:
        print "Sorry, but", choice, "isn't a valid choice."
  
raw_input("\n\nPress the enter key to exit.")

I need to set it up so that when the program loads and saves the high scores on the program by using a text file. For example, when the user first launches the program, it should try and load the scores from the text file. I need to also set it so if it doesn't exist, the program should use exception handling to avoid the program ending, along with stating that the file could not be loaded.

Also, when the program gets closed down when the user is finished, I need it to write the high scores onto the text file. I need it to also have exception handling just like mentioned above.

Can someone please help me?

You could have a code structure like this

scores_file = "scores.txt"

def load_scores(filename):
    try:
        return eval(open(scores_file).read())
    except OSError:
        return []

def store_scores(filename, scores):
    out = open(filename, "w")
    out.write(repr(scores))
    out.close()


def main():
    try:
        high_scores = load_scores(scores_file)
        user_session(high_scores)
    finally:
        store_scores(scores_file, high_scores)

def user_session(scores):
    choice = None
    while choice != "0":
        ... # PUT YOUR PREVIOUS CODE HERE

if __name__ == "__main__":
    main()

Edited 6 Years Ago by Gribouillis: n/a

I tried that and it didn't work.

"It doesn't work" does not exist. If it doesn't work, there is an exception traceback or something that tells us what happened. What does python say ?

I changed a few things in load_scores() and main(). See if it works better

def load_scores(filename):
    try:
        return eval(open(scores_file).read())
    except (OSError, IOError):
        return []

def main():
    high_scores = load_scores(scores_file)
    try:
        user_session(high_scores)
    finally:
        store_scores(scores_file, high_scores)

This is what I have:

scores_file = "scores.txt"


scores = []

def load_scores(filename):
    try:
        return eval(open(scores_file).read())
    except OSError:
        return []

def store_scores(filename, scores):
    out = open(filename, "w")
    out.write(repr(scores))
    out.close()


def main():
    try:
        high_scores = load_scores(scores_file)
        user_session(high_scores)
    finally:
        store_scores(scores_file, high_scores)

def user_session(scores):
    choice = None
while choice != "0":
 if __name__ == "__main__":
    main()

 text_file = open("scores.txt", "r+")

 print \
    """
    High Scores Keeper
    
    0 - Quit
    1 - List Scores
    2 - Add a Score
    """
    
 choice = raw_input("Choice: ")
 print

    
 if choice == "0":
        print "Good-Bye"
        text_file.write (str(entry))
        text_file.close()
   
 elif choice == "1":
        print "High Scores\n"
        print "NAME\tSCORE" 
        for entry in scores:
            text_file = open("scores.txt", "r")
            whole_thing = text_file.read()
            print whole_thing
            text_file.close()

    
 elif choice == "2":
        text_file = open("scores.txt", "w")
        name = raw_input("What is the player's name?: ")
        score = int(raw_input("What score did the player get?: "))
        entry = (name, score)
        scores.append(entry)
        scores.sort()
        scores.reverse()        
        scores = scores[:5]    

 else:
        print "Sorry, but", choice, "isn't a valid choice."
  
raw_input("\n\nPress the enter key to exit.")

It runs, but then when I try to run it again, it just says "Press the enter key to exit". Also, shouldn't it be IOError instead of an OSError?

User interface suggestion. I did one high score list.

I did it without yet saving to file. That is however trivial as info is kept as fixed length strings, no need eval, repr or \t. So one "\n".join(scores) to file is enough.

I would suggest this style of interaction with user instead of your menu.

(See attached screen capture)

I mean take info until user wants to stop. After entering info show automatically the new high score list (show allways as part of main menu)

Edited 6 Years Ago by pyTony: n/a

Attachments HighscoreUI.gif 22.22 KB

I modified your code. It seems to work now

scores_file = "scores.txt"

def load_scores(filename):
    try:
        return eval(open(scores_file).read())
    except (OSError, IOError):
        return []

def store_scores(filename, scores):
    out = open(filename, "w")
    out.write(repr(scores))
    out.close()


def main():
    high_scores = load_scores(scores_file)
    try:
        user_session(high_scores)
    finally:
        store_scores(scores_file, high_scores)

def main():
    try:
        high_scores = load_scores(scores_file)
        user_session(high_scores)
    finally:
        store_scores(scores_file, high_scores)

def user_session(scores):
    choice = None
    while choice != "0":

        print \
    """
    High Scores Keeper
    
    0 - Quit
    1 - List Scores
    2 - Add a Score
    """
    
        choice = raw_input("Choice: ")
        print

        if choice == "0":
            print "Good-Bye"

        elif choice == "1":
            print "High Scores\n"
            print "NAME\tSCORE" 
            for entry in scores:
                print entry

    
        elif choice == "2":
            name = raw_input("What is the player's name?: ")
            score = int(raw_input("What score did the player get?: "))
            entry = (name, score)
            scores.append(entry)
            scores.sort()
            scores.reverse()        
            scores = scores[:5]    

        else:
            print "Sorry, but", choice, "isn't a valid choice."
  
    raw_input("\n\nPress the enter key to exit.")
    return

if __name__ == "__main__":
    main()

Edited 6 Years Ago by Gribouillis: n/a

Sweet. How do I go about adding exception handling to it? Also, is there an alternative to this by using pickles?

Sweet. How do I go about adding exception handling to it? Also, is there an alternative to this by using pickles?

Exception is already handled in the main() function if you look carefully. And yes, you could use pickle to store the high scores, but it's not necessarily better than a text file because your high scores don't contain complex data with cross references.

def save_scores(scores):
    try:
        open('hightscores.txt','w').write('\n'.join(scores))
        return 0 ## by convention 0 is no error
    except:
        print 'Problem saving the highscores!'
        print 'Check there is enough space in the directory of the program.'
        return(-1)

scores = []
## keep all info as string, but everything must be stored as fixed length
style="%10s%20s"  ## fixed length fields text, sorting by first info

choice = None
while choice != "0":
    print "*** High Scores ***\n"
    print style % ("Name","SCORE" )
    print '\n'.join(scores)

    print \
    """
    High Scores Keeper
    
    0 - Quit
    1 - Enter Scores
    2 - Save Scores
    """
    
    choice = raw_input("Choice: ")
    print

    
    if choice == "0":
        print "Good-bye."

   
    elif choice == "1":
        print "Leave name empty to finish entering info"
        name="Name"
        while name:
            name = raw_input("\nWhat is the player's name?: ")
            if name:
                score = "*"
                
                ## until we get all numbers string (integer scores)
                while score and not all((x.isdigit() for x in score)):
                    score = raw_input("What score did the player get?: ").strip()
                    
                scores.append(style %(score,name)) ## storing as fixed length strings
                scores.sort(reverse=True)
                scores = scores[:5]
    elif choice == '2':
        if save_scores(scores): print "Saving not functioning"
    else:
        print "Sorry, but", choice, "isn't a valid choice."
    print
>>> 

*** High Scores ***

      Name               SCORE


    High Scores Keeper
    
    0 - Quit
    1 - Enter Scores
    2 - Save Scores
    
Choice: 1

Leave name empty to finish entering info

What is the player's name?: afalsdfklö
What score did the player get?: 23412

What is the player's name?: da
What score did the player get?: 443

What is the player's name?: afsf
What score did the player get?: a4352
What score did the player get?: 534

What is the player's name?: dfafa
What score did the player get?: 4245

What is the player's name?: dasd
What score did the player get?: 45125

What is the player's name?: 

*** High Scores ***

      Name               SCORE
     45125                dasd
     23412          afalsdfklö
      4245               dfafa
       534                afsf
       443                  da

    High Scores Keeper
    
    0 - Quit
    1 - Enter Scores
    2 - Save Scores
    
Choice: 1

Leave name empty to finish entering info

What is the player's name?: awerwe
What score did the player get?: 345

What is the player's name?: ljkkls
What score did the player get?: 3211

What is the player's name?: 

*** High Scores ***

      Name               SCORE
     45125                dasd
     23412          afalsdfklö
      4245               dfafa
      3211              ljkkls
       534                afsf

    High Scores Keeper
    
    0 - Quit
    1 - Enter Scores
    2 - Save Scores
    
Choice: 0

Good-bye.


>>>

Edited 6 Years Ago by pyTony: String based highscores

This question has already been answered. Start a new discussion instead.