开发者

*python code* problem/s with .txt file and tuples + dictionaries

开发者 https://www.devze.com 2023-03-02 00:48 出处:网络
I am writing this game, and having trouble coding my high scores list. The high score table consists of a .txt fi开发者_Python百科le where the Name, Score is listed in that order, each on a new line

I am writing this game, and having trouble coding my high scores list.

The high score table consists of a .txt fi开发者_Python百科le where the Name, Score is listed in that order, each on a new line right now for testing it has.

Matthew, 13
Luke, 6
John, 3

my code to record the score is:

 print "You got it!\nWell done", NAME,",You guessed it in", count, "guesses."
 save = raw_input("\nWould you like to save your score? (Y)es or (N)o: ")
 save = save.upper()
 if save == "Y":
     inFile = open("scores.txt", 'a')
     inFile.write("\n" + NAME + ", " + str(count))
     inFile.close()
     count = -1
 if save == "N":
     count = -1

and my code to show the score is:

def showScores():
    inFile = open("scores.txt", 'r')
    scorelist = {}
    for line in inFile:
        line = line.strip()
        parts = [p.strip() for p in line.split(",")]
        scorelist[parts[0]] = (parts[1])
    players = scorelist.keys()
    players.sort()
    print "High Scores:"
    for person in players:
        print person, scorelist[person]
        inFile.close()

I don't know how to sort it right, right now it sorts according to Alphabetical order, But I'd like to sort it in numerical order from smallest to biggest, but still keep the format of NAME, count.

Also every time, I try to save a new high score with the same Name it stores it...

in .txt

Matthew, 13
Luke, 6
John, 3
Mark, 8
Mark, 1

but only shows the most recent score from the same name,

In python shell

High Scores:
John 3
Luke 6
Mark 1
Matthew 13

Or only shows one instance of the same item, I guess.. does anyone know how to fix that too?

Thanks in advance


To sort by score rather than by name, use the key keyword argument.

players.sort(key=lambda x: int(scorelist[x]))

To answer your second question (I think?), you are using a dictionary to save the scores. So any given name can only store one score at a time.

parts = [p.strip() for p in line.split(",")]
scorelist[parts[0]] = (parts[1])  #second Mark score overwrites first Mark score

If you want to store multiple scores, store a list of scores instead of a single int. (Also, your code will be more readable if you use unpacking.)

name, score = [p.strip() for p in line.split(",")]
if name not in scorelist:
    scorelist[name] = []
scorelist[name].append(score)

Of course if you do it this way, sorting by score becomes more complicated. Since you want to store multiple scores by the same person, you'd be better off saving a list of tuples

def showScores():
    inFile = open("scores.txt", 'r')
    scorelist = []
    for line in inFile:
        line = line.strip()
        namescore = tuple(p.strip() for p in line.split(","))
        scorelist.append(namescore)
    scorelist.sort(key=lambda namescore: int(namescore[1]))
    print "High Scores:"
    for name, score in scorelist:
        print name, score
    inFile.close()


To fix both the sorting and the multiple scores for a single name, you probably want to change your data structure. Here's how I would write the display code:

def showScores():
    inFile = open("scores.txt", 'r')
    scorelist = []
    for line in inFile:
        line = line.strip()
        score = [p.strip() for p in line.split(",")]
        score[1] = int(score[1])
        scorelist.append(tuple(score))
    scorelist.sort(key=lambda x: x[1])
    print "High Scores:"
    for score in scorelist:
        print score[0], score[1]
    inFile.close()

This uses a list of tuples instead of a dictionary, where the tuples contain two elements: the player's name, followed by the score.

One extra note: You'll want to make sure NAME doesn't contain either commas or newlines to avoid corrupting the scores file.

0

精彩评论

暂无评论...
验证码 换一张
取 消