Videogame programming: how to determine when sprites have to move to avoid collision

Hi there,

I've been programming simple games for a while, and now I'm trying to do things a bit more complicated. The point is that, although I manage to define patterns to move sprites and I deal with collisions, I can't find a way to:
-Avoid an enemy sprite collides with a part of the scenario like a mountain (I'd like to change the direction before it gets there)
-Avoid a sprite falls down the floor when there's a hole (by going back where it came from).

Any idea about it?

PS: Sorry if this is not the right place to publish this post. Newbie here.