The emergence of a superorganism through intergroup competition