*python code* problem/s with .txt file and tuples + dictionaries -
i writing game, , having trouble coding high scores list.
the high score table consists of .txt file name, score listed in order, each on new line right testing has.
matthew, 13 luke, 6 john, 3
my code record score is:
print "you got it!\nwell done", name,",you guessed in", count, "guesses." save = raw_input("\nwould save 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 code show score is:
def showscores(): infile = open("scores.txt", 'r') scorelist = {} line in infile: line = line.strip() parts = [p.strip() p in line.split(",")] scorelist[parts[0]] = (parts[1]) players = scorelist.keys() players.sort() print "high scores:" person in players: print person, scorelist[person] infile.close()
i don't know how sort right, right sorts according alphabetical order, i'd sort in numerical order smallest biggest, still keep format of name, count.
also every time, try save new high score same name stores it...
in .txt
matthew, 13 luke, 6 john, 3 mark, 8 mark, 1
but shows recent score same name,
in python shell
high scores: john 3 luke 6 mark 1 matthew 13
or shows 1 instance of same item, guess.. know how fix too?
thanks in advance
to fix both sorting , multiple scores single name, want change data structure. here's how write display code:
def showscores(): infile = open("scores.txt", 'r') scorelist = [] line in infile: line = line.strip() score = [p.strip() p in line.split(",")] score[1] = int(score[1]) scorelist.append(tuple(score)) scorelist.sort(key=lambda x: x[1]) print "high scores:" score in scorelist: print score[0], score[1] infile.close()
this uses list of tuples instead of dictionary, tuples contain 2 elements: player's name, followed score.
one note: you'll want make sure name doesn't contain either commas or newlines avoid corrupting scores file.
Comments
Post a Comment