Rewrite handleTurn function, defining several inner functions which allow the logic of handleTurn to be written more clearly