Working version of the algorithm. The game crashes at the end.