< Prev  |  Home  |  Next >

Adding an Inventory

Just as we have a dictionary called ‘textures’ to map resources to an image, we can also create a dictionary called ‘inventory’ to map resources to the number we have in our inventory:

We could then respond to the user pressing the space key, by finding out what resource the player is standing on, and adding that resource to the inventory. We also need to change the tile the player is standing on to dirt, as the resource has now been picked up:

I’ve added a line to print the inventory, to test it. I’ve ‘picked up’ a few tiles, and we can see them added to the inventory:

Inventory

Let’s add the inventory to the bottom of our game screen. Firstly, let’s make the height of the window a little bigger than the map:

We can then display each resource in our resources list, by using the following code:

In order to draw text, we also need to define a font just before our game loop:

Here’s how the inventory looks:

The game inventory

It’d be nice if we could also do the opposite – pressing a key to place the items in our inventory (if we have any). Let’s use 1 for dirt, 2 for grass, 3 for water and 4 for coal. Add this code to your event checking:

Let’s say the player is stood on grass, and they want to place a dirt there instead. Our program adds the grass to our inventory, and then removes the dirt and places it.

Here’s the game so far:

Challenge

Improve your game by allowing the player to place the other inventory items (if they have any in their inventory). You should then be able to use your inventory to create your own world!

< Prev  |  Home  |  Next >