How to Create a Game Map with Pygame on Your Raspberry Pi
To really get going with Pygame, you need to use a list to store a map on your Raspberry Pi. A map is two-dimensional, so you’ll use a nested list, a list in which each list item is also a list. In other words, you need to make a list of rows, and each list item will itself be a list containing the information for each column in that row.
It’s easier to understand if you look at an example, so this is how you create your map list:
map=[ #-----0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9-- [0,0,0,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0], [0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0], [0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0], [0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,0], [0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,2,2,2,2,2,2,2,2,0,0,0,0,0,0], [0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0], [0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0], [0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0], [0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0], [0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0], [0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0], [0,0,0,0,0,0,2,2,2,2,2,2,2,2,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], ]
The first line in the list is a comment to number the columns so you can more easily navigate the map. The map list starts and ends with a square bracket. Notice how each list item (or row) is surrounded by square brackets too because it’s also a list.
If you squint, you might be able to make out the shape of a raspberry in there. A 1 represents a green brick (for the leaves at the top), and a 2 represents a red brick (for the juicy berry). A 0 represents no brick.
To create your own level designs, just edit this list. Keep the bottom few rows almost empty; otherwise, the game gets too hard. The bottom line must always be empty because that’s where the bat lives.
The size of the map is 20 rows of 20 columns. The index of each list starts at zero, so when you look up a location in the map, you have to subtract 1 from the X and Y coordinate you want. To find out what’s in the second row and the fifth column (Y=2, X=5), use
Note that you reference the Y coordinate first (the row number), and then the X coordinate (the column in that row).
Run the program to set up the map and use the shell to try printing different values from the map. It’s a good way to familiarize yourself with how it works.