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