Random Cave Generator using Pygame

Based on this blog post I’ve written a small game that lets you explore a dynamically generated cave.

Use the WASD keys to move around.

dynamic cave using pygame

Game screenshot

You’ll need to get pygame to run the following python script:

import pygame 
from collections import defaultdict

levelmap = defaultdict(dict)

class Player(pygame.sprite.Sprite):
	def __init__(self, level):
		self.image = pygame.Surface((10,10))
		self.rect = self.image.get_rect()
		self.x, self.y = 0,0

	def update(self, world):
		spd = 2
		keys = world.keys
		if keys[pygame.K_a]:self.x+=spd
		if keys[pygame.K_d]:self.x-=spd
		if keys[pygame.K_w]:self.y+=spd
		if keys[pygame.K_s]:self.y-=spd
		self.rect.x, self.rect.y = world.position_transform(self)

def renderlevel(noiseimage, levelmap, screen, camerax, cameray):
	mapsize = 10
	for w in range(-1, screen.get_width() / mapsize):
		for h in range(-1, screen.get_height() / mapsize):
			x = int(w - camerax/mapsize)
			y = int(h - cameray/mapsize)
			if x in levelmap:
				if y in levelmap[x]:
					if levelmap[x][y] == 0:
					realx = x* mapsize + camerax
					realy = y* mapsize + cameray

class World():
	seed = 7
	def __init__(self, screen):
		self.player = Player(levelmap)
		self.sprites = pygame.sprite.LayeredUpdates()
		self.camerax = 0
		self.cameray = 0
		self.keys = 0
		self.screen = screen

		# random noise 
		size = 100
		for i in range(size):
			for j in range(size):
				levelmap[i][j] = 0;
				if self.seededRandom(2, 0) > 1:
					levelmap[i][j] = self.seededRandom(2, 0);
		# generate caves
		smoothness = 6
		for i in range(smoothness):
			global levelmap
			new_map = defaultdict(dict)
			for x in range(size):
				for y in range(size):
					x_range = {'low': max(0, x - 1), 'high': min(size - 1, x + 1)}
					y_range = {'low': max(0, y - 1), 'high': min(size - 1, y + 1)}
					wall_count = 0
					for a in range(x_range['low'], x_range['high']+1):
						for b in range(y_range['low'], y_range['high']+1):
							if ((a == x) and (b == y)):
							wall_count += 1 - levelmap[a][b]
					if (((levelmap[x][y] == 0) and (wall_count >= 4)) or \
						((levelmap[x][y] == 1) and (wall_count >= 5)) or \
						((x == 0) or (y == 0) or (x == size - 1) or (y == size - 1))):
						new_map[x][y] = 0
						new_map[x][y] = 1
			levelmap = new_map;

	def position_transform(self, obj):
		return -(obj.x - self.camerax), -(obj.y - self.cameray)

	def update_camera(self):
		self.camerax = self.player.x + self.screen.get_width()/2
		self.cameray = self.player.y + self.screen.get_height()/2

	def seededRandom  (self, maxa, mina):
		maxa = maxa or 1
		mina = mina or 0

		World.seed = (World.seed * 9301 + 49297) % 233280
		rnd = World.seed / 233280.0

		return mina + rnd * (maxa - mina)

def main():
	screen = pygame.display.set_mode((600, 480))
	clock = pygame.time.Clock()
	world = World(screen)

	while 1:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
		renderlevel(screen, levelmap, screen, world.camerax, world.cameray)

if __name__ =='__main__': main()

Perlin like noise with python and pygame

The below code will generate a Perlin like noise for use in graphics applications.

It’s handy for say generating a dynamic cave, or a set of islands.

Perlin noise

Perlin noise

import pygame 
import math

def findnoise2(x,y):
	n = int(x) + int(y) * 57
	allf = 0xFFFFFFFF
	an = (n << 13) & allf
	n = (an ^ n) & allf
	nn = (n*(n*n*60493+19990303)+1376312589)&0x7fffffff
	return 1.0-(float(nn)/1073741824.0);

def interpolate( a, b, x):
	ft = float(x * 3.1415927)
	f = float((1.0-math.cos(ft))* 0.5)
	return a*(1.0-f)+b*f;

def noise(x,y):
    floorx = float(int(x))
    floory = float(int(y))
    return interpolate(int1,int2,y-floory) 

def main():
	screen = pygame.display.set_mode((600, 480))
	clock = pygame.time.Clock()
	noiseimage = pygame.Surface(screen.get_size())
	scale1 = 2.0
	scale2 = 4.0
	scale3 = 8.0
	for w in range(0, noiseimage.get_width()):
		for h in range(0, noiseimage.get_height()):
			i = int((noise(w/scale1,h/scale1)+1.0) * 42)
			i += int((noise(w/scale2,h/scale2)+1.0) * 42)
			i += int((noise(w/scale3,h/scale3)+1.0) * 42)
	screen.blit(noiseimage, (0,0))
	while 1:
	        for event in pygame.event.get():
	            if event.type == pygame.QUIT:
        screen.blit(noiseimage, (0,0))

if __name__ =='__main__': main()

Build a quadcopter (Part 3) – Preparing the quadcopter

Preparing the Quadcopter

Welcome back to this third installment on how to build a quadcopter. If you haven’t already check out part 1 (the parts) and part 2 (the build) to get up to speed and then read on to start preparing the quadcopter for it’s first flight.

KK2.0 Motor Layout

The first thing we want to do is tell the flight controller what our quadcopter layout looks like so that when it comes to receiving commands it knows exactly what to do and where to do it.

This is easy enough to do. Firstly Plug the battery harness into the battery and wait for the KK2.0 to fire up and follow these steps:

  1. Press button 4 (below the word ‘Menu’)
  2. Press button 3 (down) until you reach ‘Load motor layout’
  3. Press button 4 (enter)
  4. Press button 3 (down) until you reach Quadcopter – X
  5. Hit button 4 (change)

Just like that! You can then either go back (press button 1 over and over until you get back to the start) or press button 3 to scroll through each individual motor on the X layout. If you scroll through the motors you should take note that it shows you an arrow telling you which way the motor should spin (CW or CCW). This is important as this is what we’re going to cover next.

Preparing the quadcopter - Motor layout

Preparing the quadcopter – Motor layout

Motor Rotation

Now basically unless your motors spin the correct way (in line with the motor layout from above) you’re going to have a hard time flying. By hard time I mean the quadcopter will most likely flip before it gets off the ground and cause a bit of damage to itself. In other words this is also quite an important step.

If we follow what we saw in the previous step then motors 1&3 spin are going to spin CW and 2&4 will spin CCW. Check out the image below it you’re not sure:

Preparing the quadcopter - Motor rotation

Preparing the quadcopter – Motor rotation

The only way to find out if your motors are spinning in the correct direction is to fire it up and apply a little bit of throttle. So go ahead and turn on your radio, plug the battery into the harness and check each motor in turn.

By referencing the image above double check to make sure each motor is spinning in the right direction. If you find they aren’t, then all you need to do is switch 2 of the wires connecting from the motors to the ESCs (ie take the yellow and black and switch them). If you don’t know which wires I’m talking about, then these:

Preparing the quadcopter - Motor wiring

Preparing the quadcopter – Motor wiring

Again double check they’re spinning in the correct direction (rinse and repeat the above step for the other motors if needed) and then move onward!

Receiver Test

There are two reasons we need to do this. One, we need to zero out these numbers in order to make sure the quadcopter doesn’t decide to fly off on it’s own and two, we want to check to see if the radio inputs are going in the right direction (ie pushing forward actually makes the quad go forward). If you had trouble with the receiver in the previous post (ie trying to arm it by going to the bottom right didn’t work) then this is where we will hopefully fix those issues.

Firstly, switch on your radio and plug the battery into the harness to power it all up. On the KK2.0 do the following:

  1. Press the menu button (button 4)
  2. Press down and enter into ‘Receiver Test’
  3. You should come across the following:
Preparing the quadcopter - Receiver test

Preparing the quadcopter – Receiver test

This shows all the different channels (throttle, aileron, elevator, rudder, and aux) of your receiver. If you go ahead and move the sticks on your radio you will see the numbers next to the channels increase and decrease as you do so (this is a good sign).

We’re going to check all the inputs one-by-one now.

We’ll start off with the throttle first. So, on the radio move the throttle stick to idle. If you look at the KK2.0 board and the throttle input it showing both ’0′ and ‘idle’ then this is correct. If you push the throttle up you’ll see the number increase. If this isn’t right then you need to reverse the input on your radio.

Next check the rudder. On the left stick (same stick as the throttle) move it from side to side. When you move it left it should give you a negative number and ‘left’ and vise verse for right. Again, if it isn’t then you’ll need to reverse it.

Rinse and repeat this for the aileron and elevator.

The next step is to zero out all the numbers. Firstly, set the throttle to idle and center and center the right stick both vertically and horizontally. Then, using the trim and subtrim options on your radio adjust the throttle, rudder, aileron, and elevator until they are all displaying 0 on the KK2.0 board.

Sensor Calibration

The next step is to calibrate the ACC sensors. The reason we do this is to make sure the quadcopter knows exactly what is level and what is not (fairly important when it comes to self-levelling).

Firstly making sure your quadcopter is sitting on a flat surface and is level (a table or counter-top is ideal) and then:

  1. Press menu on the KK2.0 board
  2. Press down and enter into ‘ACC Calibration’
  3. It will tell you to put the quad on a flat surface. Press button 4 to continue

It will now count down 5 seconds before calibrating. Once done you should see the all OK on the X,Y, and Z sensors:

Preparing the quadcopter - Sensor test

Preparing the quadcopter – Sensor test

ESC Calibration

One of the small tweaks you need to do is the ESC calibration. You may find that when you fire up the quadcopter and apply a little throttle the motors will start at different times. Basically we just need to calibrate them in order for all 4 to start at the same time. This can get a little bit fiddly so it may take a couple of times to complete

  1. Turn on your radio and apply full throttle
  2. Press and hold the 1st and 4th button on the KK2.0
  3. Plug in the battery while still holding the buttons
  4. Wait for 2 short beeps from all your ESCs
  5. Move the throttle to idle
  6. Then you should hear 1 short beep (you can take your fingers off the buttons now)

Now fire up the motors and you will find they all start at the same time.

Balancing and Attaching Props

Balancing the props isn’t extremely necessary, but having said that it is quite important. Having balanced props generally means a smoother flight with less vibrations. This will be very helpful for those of you who want to continue on to uses cameras and FPV on your quadcopters. It can also mean that screws are less likely to vibrate themselves loose, so after all that it probably is quite a good idea to do this.

If you got the cheap and easy balancer from part 1 then really all you need to do is screw the prop into it and then balance it between two objects the same height (I use tissue boxes). If the prop falls to one side then all you need to do is either add tape to the lighter side or using high grit sandpaper, sand the heavier side.

Once you’ve found the sweet spot (the prop will sit level in the balancer) then you’re done. Do the other props and you’re set to go.

Once the props are balanced it’s time to attach them. Now you need to be careful you attach the right props to the right motor. When you bought props you got a set of CW and CCW props. So make sure that you attach the CW props to the motors spinning CW and vise versa for CCW.

Preparing the quadcopter - Attached Props

Preparing the quadcopter – Attached Props

Test Flight

Now this is it. Time to fly this bad boy. More than likely it will be horribly out of tune so it will be fairly hard to fly. Feel free to skip this flight and move on to part 4 (tuning the KK2.) in order to ensure a more stable flight. However if you’re feeling up to it:

  1. Charge up the battery
  2. Take the quadcopter outside (in a large enough area to fly. I suggest a park or football field)
  3. Turn on the radio
  4. Plug the battery into the harness
  5. Step away a few meters and arm the quadcopter
  6. Apply enough throttle to get off the ground
  7. Practice flying and have fun!

Once you’ve tried it out I suggest reading part 4 in order to tune and upgrade the KK2.0

Feel free to comment or you can hit me up on twitter @JAGracie

Build a quadcopter (Part 2) – The build

So if you managed to order all the correct parts (as noted in build a quadcopter part 1) and also managed to sit around waiting for them to arrive, we can now move on and build a quadcopter.


The first thing I suggest you do is put the frame together. It’s relatively straight forward and comes with a basic set of instructions. For now I’d keep the landing feet off as you’ll need to get access to the underneath in order to attach the motors. The end result should look something like this:

NB: Actually it shouldn’t. As you can see I’ve put the top layer on sideways. It probably isn’t a big deal but I have corrected this in the later steps.

Build a quadcopter - Frame

The frame assembled

Electronic Speed Controllers (soldering if applicable)

If you did happen to get the ESCs that require the 3.5mm connectors to be soldered then now is the time to get that out the way. It’s quite simple to do, all you need is to apply some solder into the connector and then place the wire inside (sorry I don’t have any images of this step but check out this video).

Remember the end with 2 wires needs male connectors (you place these into the battery harness) and the opposite end with 3 wires needs female connectors (the motor plugs into these).

Once done you should have them looking like this:

Build a quadcopter ESC

3.5mm connectors soldered to the ESC


Now’s the time to attach the motors to the frame. This really is straight forward. Line the motor up on the black mount and screw in the motor screws. I usually align them up so that the wires are facing forward. Once you’ve done this you can go ahead and attach the feet to the frame. Again the finished product will look like this:

build a quadcopter - motors

Motors attached to the frame

NB: Don’t attach the props just yet. Better that they’re left off while we test everything.

Attach ESCs

Next step is to attach the ESCs on to the arms of the frame. The easiest and simplest solution is to just zip-tie them to the arm. That easy. Once you’ve attached them to the frame you can go ahead and plug the motors in. Right now it doesn’t matter which wire goes in which socket (we’ll fix these later if we needed). Just like this:

build a quadcopter- ESCs

ESCs attached to frame

Flight Controller

I cheat with this step and use the foam packaging that comes with the KK2.0 and just stick it to the frame. It keeps the controller snug in the foam box while also protecting it from any bumps it may take. You don’t have to do this and you could find another way if it’s easier for you. As for the orientation of the controller, the 4 buttons below the LCD screen is considered the bottom (ie it’ll fly backwards in that direction). So, when placing the flight controller you want to make sure it is facing the way you want it.

From here you can run the wires from the ESCs up to the flight controller and connect them. You connect them to the right of the LCD with the black wire on the outside. Going from the top down, connect motor 1, motor 2, motor 3, and motor 4. The motor layout is as follows (see the picture above for a visual aid):

  • Motor 1/Pin 1 – Top left motor on the frame (remember the orientation of the flight controller)
  • Motor 2/Pin 2 – Top right motor
  • Motor 3/Pin 3 – Bottom right motor
  • Motor 4/Pin 4 – Bottom left motor
build a quadcopter - flight controller

Flight Controller attached to the Quadcopter

build a quadcopter - ESCs

ESC connections on the Flight Controller


Now it’s time to hook up the radio receiver to the flight controller. Get started by putting the male-male servo leads into channels 1-4 on the receiver (brown colour on the bottom). If you want to use Aux for auto self-level them connect another to channel 5. From there you can then connect the leads to the flight controller on the connections to the left of the LCD. From the top connect them to:

  • Alieron (Pin 1) – Channel 1
  • Elevator (Pin 2) – Channel 2
  • Throttle (Pin 3) – Channel 3
  • Rudder (Pin 4) – Channel 4
  • Aux (Pin 5) – Channel 5

Check out the photo below (sorry for poor quality) if you’re having trouble or check out the KK2.0 PDF. Finally find a place to attach the receiver to the frame and you’re almost done.

build a quadcopter - radio receiver

Radio Receiver attached to the frame and flight controller

Build a quadcopter - receiver

Receiver attached to the KK2.0 Flight Controller

Battery and Harness

This is the final step (yay!). Grab the harness and connect each ESC in turn. Make sure you plug the black cables into the other black cables and vise versa with the red. Once you’ve got this nice and tidy you can grab the battery strap and attach the battery to the bottom of the frame.

build a quadcopter - battery

Harness and battery attached to the frame and ESCs

NB: Don’t connect the battery and the harness just yet.

First you want to make sure that you aren’t shorting anything out. To do this grab either some heat-shrink (or in my case tape) and cover each individual connection on the motors and ESCs. This is good practice and will avoid any potential issues in the long run. Once you’ve done that I like to zip-tie any loose cables to the frame to make it look nice and tidy.

Fire it up!

Now switch on your radio (Turnigy 9x in my case) and set the throttle (left stick if you got the mode 2 version) to idle (push stick down). Now connect the battery harness to the battery. the KK2.0 will beep several times and then display the word ‘Safe’ on the LCD screen.

Move your throttle to the bottom and then bottom/right to arm it. You’ll now see the word ‘Armed’ appear on the controller. If you give it a little bit of throttle the motors will start to spin.

NB: If this throttle movement doesn’t work, then it may be that the channels on your radio need to be reversed. Try going to the bottom->bottom/left or top->top/right or top->top/left. If it does work when you move it to the top then it means idle is at the top and full throttle is at the bottom. Don’t panic we’ll look at changing this in the next part.

If you got this far and everything is working then congratulations, you’ve successfully built a quadcopter. Don’t get too excited though, if you took it outside now and tried to fly it you’re probably going to have a bad time.

In the part 3 we’re going to look at setting up the KK2.0 controller board to work as a quadcopter, making sure the radio has all channels working in the right order, and finally tuning it so it flies well.

Feel free to comment or you can hit me up on twitter @JAGracie

Build a quadcopter (Part 1) – The parts

It has been a while since my last post and I’m going to step away from Web development for this next series and teach you all how to build a quadcopter.

Build a quadcopter

The final product!

This is something that has interested me for a while now and I decided to jump right into the deep end and go ahead and buy some parts to build a quadcopter. Now, this probably isn’t the idea for a lot of people – especially those who have never flown RC before – and in most cases it is recommended to go out and buy a RTF (ready to fly) mini-quad such as the Syma X1. This will allow you to get the feel of flying a quad while also allowing you to crash without doing a huge amount of damage. It’s also relatively cheap and the Syma can be picked up for as low as $30 when on special.

However, if you’re like me (having only ever flown a tiny indoor RC helicopter) and just want to get your hands dirty then follow along and I’ll show you exactly what you need to build a quad, how to put it all together, and finally how to tune and fly this bad boy.

Parts needed to build a quadcopter

I’m going to list all the parts needed in order to get the quadcopter off the ground as well as a small description explaining what each part does (the more you know!). I’m going to keep it relatively cheap in order to allow beginners to get involved but you need to be aware that this isn’t the cheapest hobby in the world!

  • Frame – Speaks for itself. This is the piece that holds everything together, giving you a nice structure and platform for the rest of the build.
  • Motors / Props – The motors spin the propellers giving you the thrust needed to lift the quad off the ground.
  • Electronic Speed Controller (ESC) – Connects the motors to the battery converting DC power to AC. It also changes the speed of the motors by varying the current and timing.
  • Flight Controller – This is considered the brains of the quadcopter. This keeps the quad steady in the air as well as translating the commands coming from the receiver into movement.
  • Battery – This also speaks for itself. Provides power to the ESCs which in turn provides power to the motors and controller.
  • Radio / Receiver – This is what the pilot uses to fly the quad while the receiver sends the pilots commands to the controller.

Which parts to buy

This is probably the most intimidating part of building your first quad (not do dissimilar to building a PC) and the questions/posts/threads you see most are more often than not around compatibility/confirmation/queries of a parts list.

I’m going to help you out here and give you a basic list of parts (as well as a few much needed miscellaneous accessories) in order to get you off the ground faster. All parts will link to HobbyKing which in my personal opinion is easily the #1 supplier in the world. They also ship worldwide so it makes it simpler also.

Main Parts


This is a nice solid frame that is still reasonably light. You can also buy spare arms in case one snaps in a crash and you can also buy addons in order to attach a camera.


Again these motors are solid and are fairly cheap, so good for starting out. With the props you can see I have 2 sets of both green and black, this is mainly so you can put the green on the front and not get confused by the orientation of the quad (you’ll thank me later). Also I suggest grabbing 2 lots of each so that you have spare. You will break some, so be prepared.


These ESCs can be flashed with the popular SimonK firmware, so as well as being fairly cheap they are also practical. You’ll need the breakout cable in order to connect the ESCs to the battery which also means you’ll need the 3.5mm connectors in order to connect the ESCs to the breakout cable. This requires soldering so if this doesn’t sound like you, there are a few alternatives. Namely the Turnigy Multistar 30 Amp Multi-rotor Brushless ESC 2-4S which don’t require soldering. These are more often than not on back order, so be prepared to wait around a while.

Flight Controller 

This is probably the easiest flight controller to use for most beginners, but it is also advanced enough to allow you to tune the quadcopter and have quite a lot of control.


This is a decent sized battery (albeit a bit heavier) which will allow for some decent flight times. I get a good 10-15min flying around. Even more if I’m being gentle.

Radio / Receiver 

This is the most expensive part but it is very much worth it. Probably the most popular Radio going around today it gives you a lot of breathing room to later use the unused channels for any addons. If this seems slightly outside of your price range then you could go with the Hobby King 2.4Ghz 4Ch Tx & Rx V2 (Mode 2). The extra servo leads are required to connect the transmitter to the KK2.0 board.

Misc Parts

Low Voltage Alarm

This is something that is recommended by most people. The low voltage alarm will sound quite a loud noise when the battery is running low. This will save you from probable disaster (read: crash) and will also help you maintain the life of the battery.

Battery Strap 

How else will you attach the battery to the frame

Prop Balancer 

Having balanced props will mean having a smoother flight. Less vibrations means less chance of stuff coming loose or being broken. Quite important to have. Put the propeller in here and if it falls to one side, either just sand the heavy side down or attach tape to the light side to even it up.

Power Supply / Balancer

Needed to charge the battery.

All up this comes to just over $250USD (excl shipping), so it isn’t all that expensive. You could save a bit of money getting the slimmed down radio, but again if you’re serious about building a quadcopter then you’ll more than likely want/need the Turnigy 9x.

This should give you a general idea on the parts needed to build a quadcopter. Next up in part 2 we’ll look at putting all these parts together. Stay tuned!

Feel free to comment or you can hit me up on twitter @JAGracie