EDIT: I just remembered, my bot had the same behaviour at some time. It was because he calculated far enough to see that he'd always lose. The choice then became more or less random, and sometimes hit the wall. To counter that, I put a function after the minimax algorithm that checked wether the asked move was valid, and if it wasn't, choose a random move that's not a wall, random is better than crashing. Later I also corrected the source of the problem, but that's quite specific to my code and will probably be useless for you.