< Prev  |  Home  |  Next >


Now that we have a map, let’s add a player that can explore the map. We need to create a new PLAYER constant, and also a variable to keep track of the player’s position on the map:

Notice that the x and y coordinates are stored in a list, and not a tuple, as they will change during the game. The first item in the list will be the players x-coordinate, and the second will be the y-coordinate. The ‘.convert_alpha()’ bit at the end of the image means that we can make parts of our player image transparent, and therefore still see the tile under the player. You can add this code somewhere before the main game loop.

In our game loop, we also need to display the player. We do this in the same way that we display a tile:

When drawing the player, notice that we use the player’s current coordinates (stored in ‘playerPos’) but that we have to multiply the position on the map by the size of the tiles. As our tile size is currently set to 20, I’ve created the ‘player.png’ image to the same size. Here’s how our game looks with the player included:

The player on the map

To move our player around the map, we need to be able to respond to events. We already respond to one event in our game, the player wishing to quit:

To see what other events we can respond to, add a statement to print the events as they happen:

If you do things while the program is running, such as moving/clicking the mouse, or pressing keys, you’ll see the following:

Pygame events

The events we’re interested in are the user pressing keys on the keyboard. Specifically, the arrow keys to move the player around. Let’s respond to those key presses, by altering the player’s position:

Add this code to your game loop:

Now, if you ever press the right arrow, the player will move one tile to the right. However, the player keeps moving, even when it reaches the edge of our map. This fix will stop that happening, by only moving the player if it isn’t on the edge of the map:


Make your game respond to up, down and left arrow presses, by moving the player around the map. Make sure that the player doesn’t move off of the screen in any direction.

< Prev  |  Home  |  Next >