Game Development:
Intro to Computer Science

CSC 105
Union College
Fall 2009

Exercises about dictionaries and to practice for the final are on Codelab.

Helpdesk in Olin 102, Sun-Thu 7-9pm.

Keeping track of scores (with dictionaries)


To practice using dictionaries and reading and writing files, you will rewrite the program that reads in a file of high_scores from storing the high scores ina list (of lists) to storing them in a dictionary.

Here is the pygame program to start from: You also need the following image and sound files: red_balloon.gif, green_balloon.gif, pop.wav.

And here is a high score file to start from: hiscores.txt. It looks the same as before.

And here is the version that works with lists:

The "rules" are the similar to before (but slightly different, so read this carefully): Whenever a new game is started the player is asked for his/her name. The high score file is loaded and displayed on the screen while the player is playing (see picture). When the game is over, this player's score is compared to the list of high scores read from a file. If the player already has an entry in the high scores file and his current score is higher than his previous score, the score gets replaced; if the file contains fewer than five high scores, the current score is added to the file; if the player does not yet have an entry in the high scores file and his current score is greater than the smallest score in the file, the entry with the smallest score is deleted and a new entry for the current player is added.

Step 1: Reading in the high score file

Write a function to read in and process the file. This function should take string parameter, which is the name of the file to be read. It should return a dictionary, where player names are used for keys and scores are the values. score.

Hint: Start with an empty dictionary. For example:

scores_dict = {}
Then add entries to that dictionary as you are reading the file:
scores_dict[name] = score

Step 2: Writing the high scores dictionary to a file

Write a function that takes a string (the file name) and a dictionary mapping player names to their scores as parameters and that writes one line to the file for each entry in the dictionary. The format of the file should be like the original format of the high scores file.

Hint: Use

for (key, val) in scores_dict.items()
for key in scores_dict.keys()
to go over the whole dictionary entry by entry.

Step 3: Find the name with the of the smallest score

Write a function that takes a high scores dictionary and returns the key (player name) with the lowest value (score).

Step 4: Integrate everything into the pygame program

For this, you need to

Hint: Use

del scores_dict[name]
to delete an entry from the dictionary.