protected function buildTeams($players)
    {
        $teams = [];
        $teamsByIndex = [];
        foreach ($players as $player) {
            /**
             * Team = 0 can mean two things: either this player has no team,
             * i.e. is in a team on their own, or this player is cooping with
             * another player who _is_ part of a team.
             */
            if ($player->team == 0) {
                $found = false;
                foreach ($teams as $team) {
                    if ($team->index() != $player->team) {
                        continue;
                    }
                    foreach ($team->players() as $coopPlayer) {
                        if ($coopPlayer->index == $player->index) {
                            $team->addPlayer($player);
                            $found = true;
                            break;
                        }
                    }
                }
                // Not a cooping player, so add them to their own team.
                if (!$found) {
                    $team = new Team();
                    $team->addPlayer($player);
                    $teams[] = $team;
                    $teamsByIndex[$player->team] = $team;
                }
            } else {
                if (array_key_exists($player->team, $teamsByIndex)) {
                    $teamsByIndex[$player->team]->addPlayer($player);
                } else {
                    $team = new Team();
                    $team ->addPlayer($player);
                    $teams[] = $team;
                    $teamsByIndex[$player->team] = $team;
                }
            }
        }

        return $teams;
    }