Snap rotation to nearest 90 degrees

Hi,
I am learning Blender Python. I have a cube which I have animated using logic blocks in Blender Game Engine. I can rotate the cube get the x, y an z rotations. However when I release the key I want the cube to rotate - > 45 degrees, forward or < 45 degrees backward - to the nearest 90 degrees.

Can any body point me to a useful tutorial or give me any directions?

Thanks,

ian

The basic formula is:

(angle + 45) // 45 * 90

Input -> Output:

0 -> 0
44 -> 0
45 -> 90
90 -> 90
134 -> 90
135 -> 180

314 -> 270
315 -> 360
360 -> 360

You may have to convert degrees to radians if the input angle is given in radians.

Thanks, coDEmanX. I had a look at how to do it today and came up with something similar to what you have just shown me! Will look at refining what I had!

Thanks again.
Ian