Monday, 26 May 2014

Tkinter - Random Backgrounds with Python

Ever tried to design your own game? It can be a tricky process though so I’ll walk you through it using an example. You can either copy the example and modify it to make it more like what you want or try something different. I would recommend following along with these examples first though to see what you can expect.

We’re going to start by creating a 2D game, with a randomly generated background that you have to move your character through to get to the exit. Once that’s done we will add some monsters to chase your character and then the sky’s the limit! Diagrammatically it might look like this:


I’m going to start by creating a randomly generated forest with some rocks and trees (similar to what you might find in old school pokemon games).  First off go find some objects you want to randomly scatter around your map. Remember they should be .gif images!

If you’re looking for some code to use an example try this (yes I used stones and trees because I’m a farm boy)


So you now have a randomly generated background each time you run the programme. The problem is that, well, it kinda sucks. It would be better if we could stop trees and rocks from appearing in the same place wouldn’t it? And if they didn’t disappear off the edge of the map?



Whoa! That got really horrible really quickly didn’t it. If you poke through the code above you might be able to understand what I was doing. I made a list of all the locations I had placed each tree and just checked that the distance between those locations and any new location was greater than the width of the new image I was adding. Unfortunately it’s easy for this sort of structure to get stuck in an infinite loop (as the computer is just randomly guessing each time where to place things). 

 

CHALLENGE #5!

Can you imagine a better way to decide where to place our new trees? Is there a maximum number of trees/rocks we can fit into our window? How might we figure it out? (Hint: this becomes a lot easier if we re-visit this after we’ve learned object orientation)

CHALLENGE #6!

 If we were creating a real level we wouldn’t want things placed randomly. Objects have rules. Imagine trying to create a river through our field. The rule is that from a starting location the river can only be extended into a location that’s next to a bit that’s already river. Can you think about how we might some code to figure this out?



No comments:

Post a Comment