I have created a number guessing game that writes and reads scores from a text file. When a section of code was added to sort and right-align the scores from lowest to highest, a problem was encountered.
This is my code:

import random

print "Welcome to the Great CP1200 Guessing Game! \nWritten by ..., March 2010 \nSee if you can get a high score"
userName = raw_input("What is your name: ")

while True:
    print "\nMenu: \n(V)iew High Scores \n(P)lay Game \n(Q)uit"
    userCommand = raw_input(">>>")
    userCommand = userCommand.upper()

    if userCommand == 'Q':
        print "Thankyou for playing."
        break

    elif userCommand == 'V':
        print "High Scores:"
        scoresFile = open("scores1.txt", 'r')
        scores = scoresFile.read()
        scoresFile.close()
        score_name = []
        for line in scores.split('\n'):
            userName, score = line.split(',')
            score = int(score)
            score_name.append((score, userName))
        for score, userName in sorted(score_name):
            print "%-18s %s" % (userName, score)
            
    elif userCommand == 'P':
        smallestNum = 1
        largestNum = 42
        randomNumber = random.randint(smallestNum, largestNum)
        numGuesses =0

        while True:
            numGuesses += 1
            userGuess = input("Please enter a number between %s and %s:" % (smallestNum, largestNum))
            
            if userGuess <smallestNum or userGuess >largestNum:
                print "Invalid guess."
            elif userGuess > randomNumber:
                print "My number is lower"
            elif userGuess < randomNumber:
                print "My number is higher"
            else:
                print "You got it! \nWell done,", userName + ". " "You guessed it in", numGuesses, "guesses. \n"
                saveScore = raw_input("Would you like to save your score? (Y)es or (N)o: ")
                saveScore = saveScore.upper()
                if saveScore == 'N':
                    break
                elif saveScore == 'Y':
                    print "Saving high scores file..."
                    highScore = userName + ", " + str(numGuesses)
                    highScore = str(highScore)
                    scoresFile = open("scores1.txt", 'a')
                    scoresFile.write('\n' + highScore)
                    scoresFile.close()
                    break
            
    else:
        print "Invalid menu choice."

When the program is run, if the scores are viewed before playing, then the name that is user input (userName) is overwritten by the first name thats is saved in the file. However when the game is played first, the user input name is used. I know it is something to do with the code to view the scores, however I cannot figure out what I have done.
Thank you

Recommended Answers

All 5 Replies

Here is your problem.

elif userCommand == 'V':
        print "High Scores:"
        scoresFile = open("scores1.txt", 'r')
        scores = scoresFile.read()
        scoresFile.close()
        score_name = []
        for line in scores.split('\n'):
            userName, score = line.split(',')
            score = int(score)
            score_name.append((score, userName))
        for score, userName in sorted(score_name):
            print "%-18s %s" % (userName, score)

You use the same variable name for the user as you do for the high score person.
Just change it to this

elif userCommand == 'V':
        print "High Scores:"
        scoresFile = open("scores1.txt", 'r')
        scores = scoresFile.read()
        scoresFile.close()
        score_name = []
        for line in scores.split('\n'):
            userScore, score = line.split(',')
            score = int(score)
            score_name.append((score, userScore))
        for score, userScore in sorted(score_name):
            print "%-18s %s" % (userScore, score)

Thank you soo much!

I just had it working but something changed.
This is the code:

elif userCommand == 'V':
        print "High Scores:"
        #open and read the scores text file
        scoresFile = open("scores1.txt", 'r')
        scores = scoresFile.read()
        scoresFile.close()
        #create a list of (score,name)
        score_name = []
        for line in scores.split('\n'):
            userScore, score = line.split(',')
            #convert score to a numeric value
            score = int(score)
            score_name.append((score, userScore))
        #show as a table
        for score, userScore in sorted(score_name):
            print "%-18s %s" % (userScore, score)

I am getting a 'need more than 1 value to unpack error'

That happens when your score file reads an empty line generated by a newline character in the last data line. To prevent this error simply skip any empty line like this ...

for line in scores.split('\n'):
            # skip any empty line
            if not line:
                continue
            userScore, score = line.split(',')
            #convert score to a numeric value
            score = int(score)
            score_name.append((score, userScore))

Thank you so much for all your help. I cannot thank you enough!

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.