When the robot is going to fall the motor starts and moves the robot to the direction it is going to fall, so the motor torque about the center of gravity that is higher than the motor makes the robot balanced.
Step 1: Things you need
small electric motor
(or a motor with gearbox)
some sheets of plastic to make bearings and the robot neck
two battery holders
4 AA batteries
one button cell
one SPDT (single pole double throw) switch with a metal lever
one toggle switch for the on/off switchs
Step 2: Motor, Grears, Shaft, and Wheels
You can also use a motor and gearbox.
It does not matter how you make it.
Step 3: Attach robot neck and head
Then put some glue on one side of battery holders and attach them to the top of the plastic sheet.
Step 4: Making the sensor
Make the nail head hot on a flame and put it on the plastic sheet on the motor in a position that when the robot stands vertically the button cell touches the ground.
Then attach the switch to the robot with glue.
Step 5: Connecting the switch
Then attach the other side of the switch to the motor.
Step 6: Wiring
Note that you must solder the wires in a way that robot moves to the direction that is going to fall.