开发者

Python Programming for the absolute beginner Chapter 7 Challenge 2

I've been trying to learn python using this book, however, I seem to be stuck on this challenge.

"2. Improve the Trivia Challenge game so that it maintains a high-scores list in a file. The program should record the player's name and score if the player makes the list. Store the high scores using a pickled object."

I decided to use lists instead of dictionaries because I don't think I can sort the d开发者_JAVA百科ictionary scores. However, to update the dictionary version per your question, when you load the dictionary give it another variable and then add that variable to the original.

so it would go something like this:

first I created a blank list to hold the dictionary.

high_scores = []

then run a separate program to update the scores.

new_score = {score: player}

f = open("high_Scores.txt", "rb")
score_list = high_scores
f.close()
score_list.append(new_score)
score_list = score_list[:10]
f = open("high_scores.txt", "wb")
pickle.dump(score_list, f)
f.close()

this only holds 10 scores and will update the dictionary. I haven't figured out how to sort the scores and from reading I don't think it's possible to do at this point in the book. I was thinking of switching over to lists or something. I haven't really worked on it so I'm not sure at this point. if you figure it out let me know.


I don't want to do it all for you, but here are some hints:

No need for dictionary, dictionaries are unordered. Use a sorted list of 2-tuples: high_scores = [(score1, name1), (score2, name2), ...]. Sort the list in reverse order: high_scores.sort(reverse=True). Use the list append and pop methods to add new entries and remove entries which are no longer in the top ten.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜