highscores list

Zepo Len no at no.no
Sat Dec 8 15:07:12 EST 2007


> I'm writing a game that uses two functions to check and see if a file  
> called highScoresList.txt exists in the main dir of the game program.   
> If it doesn, it creates one.  That part is working fine.  The problem is  
> arising when it goes to read in the high scores from the file when I  
> play again.
>
> This is the error msg python is giving me
>
> Traceback (most recent call last):
>  File "<pyshell#0>", line 1, in <module>
>    main()
>  File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 330, in main
>    if(hasHighScore(wins) == True):
>  File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 175, in hasHighScore
>    scores[i],names[i] = string.split(line,"\t")
> ValueError: need more than 1 value to unpack
>
>     for line in infile.readlines():
>         scores[i],names[i] = string.split(line,"\t")

The error message is straightforward, you are trying to unpack a 1 value  
tuple to 2 values

The reason it's a one value tuple is that your first line is this:

>     outfile.write ("     High Score                 Name             \n")

Running split('\t') on this will return a tuple of length one (since there  
is no tab in that line)

Your code is also really unpythonic, take a look at this rewrite to see  
what you could have done better:

def getHighScoreList():
     scores = []
     try:
         highscore_file = list(open("highScoresList.txt"))
         for line in highscore_file[2:]:
             score, name = line.split('\t\t\t')
             scores.append((int(score), name.rstrip()))
     except IOError: # no highscore file yet
         pass
     return scores

def hasHighScore(score):
     scores = [s for (s, n) in getHighScoreList()]
     if scores:
         return score > min(scores)
     return True

def setHighScores(newscore, newname):
     max_scores = 3
     scores = getHighScoreList()

     for i, (score, name) in enumerate(scores):
         if newscore > score:
             scores.insert(i, (newscore, newname))
             break
     else:
         scores.append((newscore, newname))

     outfile = open("highScoresList.txt","w")
     outfile.write ("     High Score                 Name             \n")
     outfile.write ("-------------------------------------------------\n")
     for i in range(max_scores):
         try:
             score, name = scores[i]
         except IndexError:
             score, name = 0, ''
         outfile.write("\t%s\t\t\t%s\n" % (score, name))
     outfile.close()

if hasHighScore(wins):
    setHighScores(wins, getName(wins))



More information about the Python-list mailing list