Tidy up the collision detection code.
Implemented a pseudo-random generator.