Learning to Perceive and Act by Trial and Error