< Prev  |  Home  |  Next >

List Comprehension

So far we have a game map, but it’s very small. If you have a 5 x 5 grid, there are only 25 tiles on the map. If we want a massive map to explore, obviously we’d rather not have to type out hundreds of tiles.

Instead, we can useĀ list comprehension to quickly generate a list. Run your minecraft program, but replace the tilemap with the following:

Your program probably won’t work now, but If you look, you can see that DIRT (the number 0) has been added to the tilemap list, once for each tile in a row. So now that we’ve dynamically created one row, we need to do the same for each column. This gives us the following:

As you can see, we now have lists of lists, and our program now works again:

Tilemap using list comprehension

From the screenshot above, you can see that I’ve changed the values of some of our constants. Do you know which ones? Our world is now only covered in dirt though. To make the map full of all our different resources, we just need to randomly select one each time. We’ve already written a program to randomly select an item from a list when making a poetry generator. All we need to do is create a list of resources, and then select one randomly each time:

You should now see a much more interesting map:

Tilemap using list comprehension

Although I’m quite happy with this map, I just want to make one more change to make it slightly more advanced. I’d really like it if, on our map, dirt was very common, water and grass are less common, and coal is a scarce resource that doesn’t appear on the map much. This will make our game more fun.

ln the ‘Did you win?‘ game, we created a game where a number between 0 and 1 was randomly chosen, and said that if a 1 was chosen, the player had won. This means that the player has a 50% chance of winning. We can do something similar with our game, using a random number to choose which resource to place. Firstly, change the tilemap back to be all dirt to begin with:

We can then loop through our list, and change a resource depending on the number chosen:

What is the chance of a particular tile being coal? or water? You can tinker with these numbers until you have a map that you’re happy with. Here’s what we have so far:

Challenge

Create a new DIAMOND resource, and make it so that it appears very rarely in your map. Very rarely. You’ll need to change the random numbers, including the range of numbers chosen from.

< Prev  |  Home  |  Next >