How do I use the compositor to output colour based on the depth of objects?
and another, more tunable.


the Z-buffer isn't really an image but a grid of distance values mapped from camera clipping start, and end (these settings are found in the Camera Object properties tab).

Use the limits tickbox to visualize the clipping start and clipping end range, (also called near and far clipping planes). Generally keep all your geometry in that range and you will be using the Z-Buffer like a boss.

PS: instead of the Map Range node, you can use the Normalize node and you won't have to set the range values, it will find the lowest/highest values in the Z-buffer and map them to 0...1 range