The emergence of cooperative playing routines: optimality and learning