Dark theme

OK, hopefully you're happy the code is alright. Open it up and give you a quick overview of how it works.

Overall the code avoids using a massive number of if-else statements by instead reading in a map file which is a grid of numbers. Each number is used to run a different function and the player's location in the grid is represented by two variables current_x and current_y. To represent the player moving around, we change these variables and then for each move look at the number in the grid and run the appropriate function.

The map grid is held in a two dimensional array. Arrays are variables that can hold more than one data value. In Python it's easier to use a type of variable called a list, but at this level you can think of them as the same as an array in other languages. A one dimensional list might look like this:

map_line = [1,0,0,5,0]

Each position in the list has a position, numbered from zero, and so we'd use it like this:

if (map_line[0] == 6) or (map_line[1] == 3) :

That is, check the values at the first ("[0]") and second ("[1]") positions. I know it seems crazy to start counting at zero for the first position, but trust me, you get used to it.

A two dimensional list is exactly the same, but you can imagine that there are multiple lists, each one kept in a vertical list, like this:

map_data[0] = map_line0
map_data[1] = map_line1
map_data[2] = map_line2
map_data[3] = map_line3

That is...

map_data[0] = [1,0,0,5,0]
map_data[1] = [5,1,0,1,2]
map_data[2] = [1,2,6,6,2]
map_data[3] = [3,4,0,8,0]

You can then use this like:

if (map_line[1][3] == 3) :

Where the first number is the line and the second the position across the line.

Now comes the really clever bit. If we have a current_x and current_y we can do this:

current_x = 1
current_y = 3
if (map_line[current_x][current_y] == 3) :

If we want to move the player down, we can increase current_y by one:

current_y = current_y + 1

If we want to move the player right, we can increase current_x by one:

current_x = current_x + 1

And then to check the new position, we can again use:

if (map_line[current_x][current_y] == 3) :

If it is "3", we can call an appropriate function. So, for example, assuming "3" is a monster:

if (map_line[current_x][current_y] == 3) :
   monster()

There's a few additional bits in the code: for example, we use zeros to be walls in the map that players can't walk through and we use the len() built in function to find the length of lists so the code can read in grids of any size, but otherwise that's pretty much all that is going on in the code other than the code to read in the file.

Have a look through the code, and read the comments and see if you can work out what it does at each stage. We'll then look at how you can change it to add new bits to the game.

[Home > Part 5 > Next]