Friend and Foe: When to Cooperate, When to Compete, and How to Succeed at Both