1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-01-26 03:52:01 +02:00

Merge pull request #2372 from vcmi/fix_rmg_teams

Fix teams on random maps
This commit is contained in:
Ivan Savenko 2023-11-07 22:45:51 +02:00 committed by GitHub
commit 083e75e80e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 590 additions and 217 deletions

View File

@ -2,7 +2,7 @@
"Coldshadow's Fantasy": "Coldshadow's Fantasy":
{ {
"minSize" : "xl+u", "maxSize" : "g+u", "minSize" : "xl+u", "maxSize" : "g+u",
"players" : "4-8", "cpu" : "3-6", "players" : "4-8", "humans" : "3-6",
"zones": "zones":
{ {
"1": "1":

View File

@ -5117,7 +5117,7 @@
"Midnight Mix 34" : "Midnight Mix 34" :
{ {
"minSize" : "l", "maxSize" : "xl+u", "minSize" : "l", "maxSize" : "xl+u",
"players" : "6", "cpu" : "2", "players" : "6", "humans" : "2",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"Meeting in Muzgob" : "Meeting in Muzgob" :
{ {
"minSize" : "l", "maxSize" : "xl+u", "minSize" : "l", "maxSize" : "xl+u",
"players" : "2-6", "cpu" : "2", "players" : "2-6", "humans" : "2",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"Newcomers" : "Newcomers" :
{ {
"minSize" : "m+u", "maxSize" : "xl+u", "minSize" : "m+u", "maxSize" : "xl+u",
"players" : "2-3", "cpu" : "1", "players" : "2-3", "humans" : "1",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"South of Hell" : "South of Hell" :
{ {
"minSize" : "m+u", "maxSize" : "l+u", "minSize" : "m+u", "maxSize" : "l+u",
"players" : "2", "cpu" : "1", "players" : "2", "humans" : "1",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"Worlds at War" : "Worlds at War" :
{ {
"minSize" : "m+u", "maxSize" : "xl+u", "minSize" : "m+u", "maxSize" : "xl+u",
"players" : "2", "cpu" : "3", "players" : "2", "humans" : "3",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"Gauntlet" : "Gauntlet" :
{ {
"minSize" : "m+u", "maxSize" : "xl+u", "minSize" : "m+u", "maxSize" : "xl+u",
"players" : "1", "cpu" : "5", "players" : "1", "humans" : "5",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"2SM0k" : "2SM0k" :
{ {
"minSize" : "s", "maxSize" : "m+u", "minSize" : "s", "maxSize" : "m+u",
"players" : "2", "cpu" : "6", "players" : "2", "humans" : "1-2",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,8 @@
"2SM2i(2)" : "2SM2i(2)" :
{ {
"minSize" : "s", "maxSize" : "m+u", "minSize" : "s", "maxSize" : "m+u",
"players" : "2-4", "players" : "2",
"humans": "1-2",
"zones" : "zones" :
{ {
"1" : "1" :
@ -32,7 +33,7 @@
}, },
"3" : "3" :
{ {
"type" : "playerStart", "type" : "treasure",
"size" : 11, "size" : 11,
"monsters" : "normal", "monsters" : "normal",
"minesLikeZone" : 1, "minesLikeZone" : 1,
@ -54,7 +55,7 @@
}, },
"5" : "5" :
{ {
"type" : "playerStart", "type" : "treasure",
"size" : 11, "size" : 11,
"monsters" : "normal", "monsters" : "normal",
"neutralTowns" : { "towns" : 1 }, "neutralTowns" : { "towns" : 1 },

View File

@ -2,7 +2,7 @@
"3SB0b" : "3SB0b" :
{ {
"minSize" : "s", "maxSize" : "m+u", "minSize" : "s", "maxSize" : "m+u",
"players" : "2", "cpu" : "1", "players" : "2", "humans" : "1",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"3SB0c" : "3SB0c" :
{ {
"minSize" : "s+u", "maxSize" : "m+u", "minSize" : "s+u", "maxSize" : "m+u",
"players" : "2", "cpu" : "1", "players" : "2", "humans" : "1",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"5SB0a" : "5SB0a" :
{ {
"minSize" : "s", "maxSize" : "m+u", "minSize" : "s", "maxSize" : "m+u",
"players" : "2-3", "cpu" : "2", "players" : "2-3", "humans" : "2",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"5SB0b" : "5SB0b" :
{ {
"minSize" : "s", "maxSize" : "m+u", "minSize" : "s", "maxSize" : "m+u",
"players" : "2-3", "cpu" : "2", "players" : "2-3", "humans" : "2",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"7SB0b" : "7SB0b" :
{ {
"minSize" : "s", "maxSize" : "l", "minSize" : "s", "maxSize" : "l",
"players" : "2-6", "cpu" : "1", "players" : "2-6", "humans" : "1",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -2,7 +2,7 @@
"7SB0c" : "7SB0c" :
{ {
"minSize" : "s+u", "maxSize" : "l", "minSize" : "s+u", "maxSize" : "l",
"players" : "2-6", "cpu" : "1", "players" : "2-7", "humans" : "2-6",
"zones" : "zones" :
{ {
"1" : "1" :

View File

@ -65,7 +65,7 @@ RandomMapTab::RandomMapTab():
addCallback("setPlayersCount", [&](int btnId) addCallback("setPlayersCount", [&](int btnId)
{ {
mapGenOptions->setPlayerCount(btnId); mapGenOptions->setHumanOrCpuPlayerCount(btnId);
setMapGenOptions(mapGenOptions); setMapGenOptions(mapGenOptions);
updateMapInfoByHost(); updateMapInfoByHost();
}); });
@ -183,55 +183,38 @@ void RandomMapTab::updateMapInfoByHost()
mapInfo->mapHeader->twoLevel = mapGenOptions->getHasTwoLevels(); mapInfo->mapHeader->twoLevel = mapGenOptions->getHasTwoLevels();
// Generate player information // Generate player information
int playersToGen = PlayerColor::PLAYER_LIMIT_I; int playersToGen = mapGenOptions->getMaxPlayersCount();
if(mapGenOptions->getPlayerCount() != CMapGenOptions::RANDOM_SIZE)
{
if(mapGenOptions->getCompOnlyPlayerCount() != CMapGenOptions::RANDOM_SIZE)
playersToGen = mapGenOptions->getPlayerCount() + mapGenOptions->getCompOnlyPlayerCount();
else
playersToGen = mapGenOptions->getPlayerCount();
}
mapInfo->mapHeader->howManyTeams = playersToGen; mapInfo->mapHeader->howManyTeams = playersToGen;
std::set<TeamID> occupiedTeams; //TODO: Assign all human-controlled colors in first place
for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i) for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
{ {
mapInfo->mapHeader->players[i].canComputerPlay = false; mapInfo->mapHeader->players[i].canComputerPlay = false;
mapInfo->mapHeader->players[i].canHumanPlay = false; mapInfo->mapHeader->players[i].canHumanPlay = false;
} }
for(int i = 0; i < playersToGen; ++i) std::vector<PlayerColor> availableColors;
for (ui8 color = 0; color < PlayerColor::PLAYER_LIMIT_I; color++)
{ {
PlayerInfo player; availableColors.push_back(PlayerColor(color));
player.isFactionRandom = true;
player.canComputerPlay = true;
if(mapGenOptions->getCompOnlyPlayerCount() != CMapGenOptions::RANDOM_SIZE && i >= mapGenOptions->getPlayerCount())
{
player.canHumanPlay = false;
}
else
{
player.canHumanPlay = true;
}
auto team = mapGenOptions->getPlayersSettings().at(PlayerColor(i)).getTeam();
player.team = team;
occupiedTeams.insert(team);
player.hasMainTown = true;
player.generateHeroAtMainTown = true;
mapInfo->mapHeader->players[i] = player;
} }
for(auto & player : mapInfo->mapHeader->players)
//First restore known players
for (auto& player : mapGenOptions->getPlayersSettings())
{ {
for(int i = 0; player.team == TeamID::NO_TEAM; ++i) PlayerInfo playerInfo;
{ playerInfo.isFactionRandom = (player.second.getStartingTown() == FactionID::RANDOM);
TeamID team(i); playerInfo.canComputerPlay = (player.second.getPlayerType() != EPlayerType::HUMAN);
if(!occupiedTeams.count(team)) playerInfo.canHumanPlay = (player.second.getPlayerType() != EPlayerType::COMP_ONLY);
{
player.team = team; auto team = player.second.getTeam();
occupiedTeams.insert(team); playerInfo.team = team;
} playerInfo.hasMainTown = true;
} playerInfo.generateHeroAtMainTown = true;
mapInfo->mapHeader->players[player.first] = playerInfo;
vstd::erase(availableColors, player.first);
} }
mapInfoChanged(mapInfo, mapGenOptions); mapInfoChanged(mapInfo, mapGenOptions);
@ -241,47 +224,72 @@ void RandomMapTab::setMapGenOptions(std::shared_ptr<CMapGenOptions> opts)
{ {
mapGenOptions = opts; mapGenOptions = opts;
//prepare allowed options //Prepare allowed options - add all, then erase the ones above the limit
for(int i = 0; i <= PlayerColor::PLAYER_LIMIT_I; ++i) for(int i = 0; i <= PlayerColor::PLAYER_LIMIT_I; ++i)
{ {
playerCountAllowed.insert(i); playerCountAllowed.insert(i);
compCountAllowed.insert(i); compCountAllowed.insert(i);
playerTeamsAllowed.insert(i); if (i >= 2)
compTeamsAllowed.insert(i); {
playerTeamsAllowed.insert(i);
}
if (i >= 1)
{
compTeamsAllowed.insert(i);
}
} }
std::set<int> humanCountAllowed;
auto * tmpl = mapGenOptions->getMapTemplate(); auto * tmpl = mapGenOptions->getMapTemplate();
if(tmpl) if(tmpl)
{ {
playerCountAllowed = tmpl->getPlayers().getNumbers(); playerCountAllowed = tmpl->getPlayers().getNumbers();
compCountAllowed = tmpl->getCpuPlayers().getNumbers(); humanCountAllowed = tmpl->getHumanPlayers().getNumbers(); // Unused now?
} }
if(mapGenOptions->getPlayerCount() != CMapGenOptions::RANDOM_SIZE)
si8 playerLimit = opts->getMaxPlayersCount();
si8 humanOrCpuPlayerCount = opts->getHumanOrCpuPlayerCount();
si8 compOnlyPlayersCount = opts->getCompOnlyPlayerCount();
if(humanOrCpuPlayerCount != CMapGenOptions::RANDOM_SIZE)
{ {
vstd::erase_if(compCountAllowed, vstd::erase_if(compCountAllowed, [playerLimit, humanOrCpuPlayerCount](int el)
[opts](int el){ {
return PlayerColor::PLAYER_LIMIT_I - opts->getPlayerCount() < el; return (playerLimit - humanOrCpuPlayerCount) < el;
}); });
vstd::erase_if(playerTeamsAllowed, vstd::erase_if(playerTeamsAllowed, [humanOrCpuPlayerCount](int el)
[opts](int el){ {
return opts->getPlayerCount() <= el; return humanOrCpuPlayerCount <= el;
}); });
if(!playerTeamsAllowed.count(opts->getTeamCount()))
opts->setTeamCount(CMapGenOptions::RANDOM_SIZE);
} }
if(mapGenOptions->getCompOnlyPlayerCount() != CMapGenOptions::RANDOM_SIZE) else // Random
{ {
vstd::erase_if(playerCountAllowed, vstd::erase_if(compCountAllowed, [playerLimit](int el)
[opts](int el){ {
return PlayerColor::PLAYER_LIMIT_I - opts->getCompOnlyPlayerCount() < el; return (playerLimit - 1) < el; // Must leave at least 1 human player
}); });
vstd::erase_if(compTeamsAllowed, vstd::erase_if(playerTeamsAllowed, [playerLimit](int el)
[opts](int el){ {
return opts->getCompOnlyPlayerCount() <= el; return playerLimit <= el;
});
}
if(!playerTeamsAllowed.count(opts->getTeamCount()))
{
opts->setTeamCount(CMapGenOptions::RANDOM_SIZE);
}
if(compOnlyPlayersCount != CMapGenOptions::RANDOM_SIZE)
{
// This setting doesn't impact total number of players
vstd::erase_if(compTeamsAllowed, [compOnlyPlayersCount](int el)
{
return compOnlyPlayersCount<= el;
}); });
if(!compTeamsAllowed.count(opts->getCompOnlyTeamCount())) if(!compTeamsAllowed.count(opts->getCompOnlyTeamCount()))
{
opts->setCompOnlyTeamCount(CMapGenOptions::RANDOM_SIZE); opts->setCompOnlyTeamCount(CMapGenOptions::RANDOM_SIZE);
}
} }
if(auto w = widget<CToggleGroup>("groupMapSize")) if(auto w = widget<CToggleGroup>("groupMapSize"))
@ -310,7 +318,7 @@ void RandomMapTab::setMapGenOptions(std::shared_ptr<CMapGenOptions> opts)
} }
if(auto w = widget<CToggleGroup>("groupMaxPlayers")) if(auto w = widget<CToggleGroup>("groupMaxPlayers"))
{ {
w->setSelected(opts->getPlayerCount()); w->setSelected(opts->getHumanOrCpuPlayerCount());
deactivateButtonsFrom(*w, playerCountAllowed); deactivateButtonsFrom(*w, playerCountAllowed);
} }
if(auto w = widget<CToggleGroup>("groupMaxTeams")) if(auto w = widget<CToggleGroup>("groupMaxTeams"))
@ -397,6 +405,25 @@ std::vector<int> RandomMapTab::getPossibleMapSizes()
return {CMapHeader::MAP_SIZE_SMALL, CMapHeader::MAP_SIZE_MIDDLE, CMapHeader::MAP_SIZE_LARGE, CMapHeader::MAP_SIZE_XLARGE, CMapHeader::MAP_SIZE_HUGE, CMapHeader::MAP_SIZE_XHUGE, CMapHeader::MAP_SIZE_GIANT}; return {CMapHeader::MAP_SIZE_SMALL, CMapHeader::MAP_SIZE_MIDDLE, CMapHeader::MAP_SIZE_LARGE, CMapHeader::MAP_SIZE_XLARGE, CMapHeader::MAP_SIZE_HUGE, CMapHeader::MAP_SIZE_XHUGE, CMapHeader::MAP_SIZE_GIANT};
} }
void TeamAlignmentsWidget::checkTeamCount()
{
//Do not allow to select one team only
std::set<TeamID> teams;
for (int plId = 0; plId < players.size(); ++plId)
{
teams.insert(TeamID(players[plId]->getSelected()));
}
if (teams.size() < 2)
{
//Do not let player close the window
buttonOk->block(true);
}
else
{
buttonOk->block(false);
}
}
TeamAlignments::TeamAlignments(RandomMapTab & randomMapTab) TeamAlignments::TeamAlignments(RandomMapTab & randomMapTab)
: CWindowObject(BORDERED) : CWindowObject(BORDERED)
{ {
@ -415,10 +442,8 @@ TeamAlignmentsWidget::TeamAlignmentsWidget(RandomMapTab & randomMapTab):
const JsonNode config(JsonPath::builtin("config/widgets/randomMapTeamsWidget.json")); const JsonNode config(JsonPath::builtin("config/widgets/randomMapTeamsWidget.json"));
variables = config["variables"]; variables = config["variables"];
int humanPlayers = randomMapTab.obtainMapGenOptions().getPlayerCount(); //int totalPlayers = randomMapTab.obtainMapGenOptions().getPlayerLimit();
int cpuPlayers = randomMapTab.obtainMapGenOptions().getCompOnlyPlayerCount(); int totalPlayers = randomMapTab.obtainMapGenOptions().getMaxPlayersCount();
int totalPlayers = humanPlayers == CMapGenOptions::RANDOM_SIZE || cpuPlayers == CMapGenOptions::RANDOM_SIZE
? PlayerColor::PLAYER_LIMIT_I : humanPlayers + cpuPlayers;
assert(totalPlayers <= PlayerColor::PLAYER_LIMIT_I); assert(totalPlayers <= PlayerColor::PLAYER_LIMIT_I);
auto settings = randomMapTab.obtainMapGenOptions().getPlayersSettings(); auto settings = randomMapTab.obtainMapGenOptions().getPlayersSettings();
variables["totalPlayers"].Integer() = totalPlayers; variables["totalPlayers"].Integer() = totalPlayers;
@ -458,6 +483,27 @@ TeamAlignmentsWidget::TeamAlignmentsWidget(RandomMapTab & randomMapTab):
OBJ_CONSTRUCTION; OBJ_CONSTRUCTION;
// Window should have X * X columns, where X is max players allowed for current settings
// For random player count, X is 8
if (totalPlayers > settings.size())
{
auto savedPlayers = randomMapTab.obtainMapGenOptions().getSavedPlayersMap();
for (const auto & player : savedPlayers)
{
if (!vstd::contains(settings, player.first))
{
settings[player.first] = player.second;
}
}
}
std::vector<CMapGenOptions::CPlayerSettings> settingsVec;
for (const auto & player : settings)
{
settingsVec.push_back(player.second);
}
for(int plId = 0; plId < totalPlayers; ++plId) for(int plId = 0; plId < totalPlayers; ++plId)
{ {
players.push_back(std::make_shared<CToggleGroup>([&, totalPlayers, plId](int sel) players.push_back(std::make_shared<CToggleGroup>([&, totalPlayers, plId](int sel)
@ -476,10 +522,15 @@ TeamAlignmentsWidget::TeamAlignmentsWidget(RandomMapTab & randomMapTab):
{ {
button->addOverlay(nullptr); button->addOverlay(nullptr);
} }
button->addCallback([this](bool)
{
checkTeamCount();
});
} }
})); }));
OBJ_CONSTRUCTION_TARGETED(players.back().get()); OBJ_CONSTRUCTION_TARGETED(players.back().get());
for(int teamId = 0; teamId < totalPlayers; ++teamId) for(int teamId = 0; teamId < totalPlayers; ++teamId)
{ {
variables["point"]["x"].Integer() = variables["cellOffset"]["x"].Integer() + plId * variables["cellMargin"]["x"].Integer(); variables["point"]["x"].Integer() = variables["cellOffset"]["x"].Integer() + plId * variables["cellMargin"]["x"].Integer();
@ -488,10 +539,17 @@ TeamAlignmentsWidget::TeamAlignmentsWidget(RandomMapTab & randomMapTab):
players.back()->addToggle(teamId, std::dynamic_pointer_cast<CToggleBase>(button)); players.back()->addToggle(teamId, std::dynamic_pointer_cast<CToggleBase>(button));
} }
auto team = settings.at(PlayerColor(plId)).getTeam(); // plId is not neccessarily player color, just an index
auto team = settingsVec.at(plId).getTeam();
if(team == TeamID::NO_TEAM) if(team == TeamID::NO_TEAM)
{
logGlobal->warn("Player %d (id %d) has uninitialized team", settingsVec.at(plId).getColor(), plId);
players.back()->setSelected(plId); players.back()->setSelected(plId);
}
else else
players.back()->setSelected(team.getNum()); players.back()->setSelected(team.getNum());
} }
buttonOk = widget<CButton>("buttonOK");
buttonCancel = widget<CButton>("buttonCancel");
} }

View File

@ -57,6 +57,8 @@ public:
TeamAlignmentsWidget(RandomMapTab & randomMapTab); TeamAlignmentsWidget(RandomMapTab & randomMapTab);
private: private:
void checkTeamCount();
std::shared_ptr<CFilledTexture> background; std::shared_ptr<CFilledTexture> background;
std::shared_ptr<CLabelGroup> labels; std::shared_ptr<CLabelGroup> labels;
std::shared_ptr<CButton> buttonOk, buttonCancel; std::shared_ptr<CButton> buttonOk, buttonCancel;

View File

@ -119,7 +119,7 @@
"description" : "Number of players that will be present on map (human or AI)", "description" : "Number of players that will be present on map (human or AI)",
"type": "string" "type": "string"
}, },
"cpu" : { "humans" : {
"description" : "Optional, number of AI-only players", "description" : "Optional, number of AI-only players",
"type": "string" "type": "string"
}, },

View File

@ -18,8 +18,8 @@
/// Number of players that will be present on map (human or AI) /// Number of players that will be present on map (human or AI)
"players" : "2-4", "players" : "2-4",
/// Optional, number of AI-only players /// Since 1.4.0 - Optional, number of human-only players (as in original templates)
"cpu" : "2", "humans" : "1-4",
///Optional parameter allowing to prohibit some water modes. All modes are allowed if parameter is not specified ///Optional parameter allowing to prohibit some water modes. All modes are allowed if parameter is not specified
"allowedWaterContent" : ["none", "normal", "islands"] "allowedWaterContent" : ["none", "normal", "islands"]

View File

@ -22,10 +22,11 @@ VCMI_LIB_NAMESPACE_BEGIN
CMapGenOptions::CMapGenOptions() CMapGenOptions::CMapGenOptions()
: width(CMapHeader::MAP_SIZE_MIDDLE), height(CMapHeader::MAP_SIZE_MIDDLE), hasTwoLevels(true), : width(CMapHeader::MAP_SIZE_MIDDLE), height(CMapHeader::MAP_SIZE_MIDDLE), hasTwoLevels(true),
playerCount(RANDOM_SIZE), teamCount(RANDOM_SIZE), compOnlyPlayerCount(RANDOM_SIZE), compOnlyTeamCount(RANDOM_SIZE), humanOrCpuPlayerCount(RANDOM_SIZE), teamCount(RANDOM_SIZE), compOnlyPlayerCount(RANDOM_SIZE), compOnlyTeamCount(RANDOM_SIZE),
waterContent(EWaterContent::RANDOM), monsterStrength(EMonsterStrength::RANDOM), mapTemplate(nullptr) waterContent(EWaterContent::RANDOM), monsterStrength(EMonsterStrength::RANDOM), mapTemplate(nullptr),
customizedPlayers(false)
{ {
resetPlayersMap(); initPlayersMap();
setRoadEnabled(RoadId(Road::DIRT_ROAD), true); setRoadEnabled(RoadId(Road::DIRT_ROAD), true);
setRoadEnabled(RoadId(Road::GRAVEL_ROAD), true); setRoadEnabled(RoadId(Road::GRAVEL_ROAD), true);
setRoadEnabled(RoadId(Road::COBBLESTONE_ROAD), true); setRoadEnabled(RoadId(Road::COBBLESTONE_ROAD), true);
@ -63,23 +64,91 @@ void CMapGenOptions::setHasTwoLevels(bool value)
hasTwoLevels = value; hasTwoLevels = value;
} }
si8 CMapGenOptions::getPlayerCount() const si8 CMapGenOptions::getHumanOrCpuPlayerCount() const
{ {
return playerCount; return humanOrCpuPlayerCount;
} }
void CMapGenOptions::setPlayerCount(si8 value) void CMapGenOptions::setHumanOrCpuPlayerCount(si8 value)
{ {
assert((value >= 1 && value <= PlayerColor::PLAYER_LIMIT_I) || value == RANDOM_SIZE); assert((value >= 1 && value <= PlayerColor::PLAYER_LIMIT_I) || value == RANDOM_SIZE);
playerCount = value; humanOrCpuPlayerCount = value;
auto possibleCompPlayersCount = PlayerColor::PLAYER_LIMIT_I - value; // Use template player limit, if any
auto playerLimit = getPlayerLimit();
auto possibleCompPlayersCount = playerLimit - std::max<si8>(0, humanOrCpuPlayerCount);
if (compOnlyPlayerCount > possibleCompPlayersCount) if (compOnlyPlayerCount > possibleCompPlayersCount)
{
setCompOnlyPlayerCount(possibleCompPlayersCount); setCompOnlyPlayerCount(possibleCompPlayersCount);
}
resetPlayersMap(); resetPlayersMap();
} }
si8 CMapGenOptions::getMinPlayersCount(bool withTemplateLimit) const
{
auto totalPlayers = 0;
si8 humans = getHumanOrCpuPlayerCount();
si8 cpus = getCompOnlyPlayerCount();
if (humans == RANDOM_SIZE && cpus == RANDOM_SIZE)
{
totalPlayers = 2;
}
else if (humans == RANDOM_SIZE)
{
totalPlayers = cpus + 1; // Must add at least 1 player
}
else if (cpus == RANDOM_SIZE)
{
totalPlayers = humans;
}
else
{
totalPlayers = humans + cpus;
}
if (withTemplateLimit && mapTemplate)
{
auto playersRange = mapTemplate->getPlayers();
//New template can also impose higher limit than current settings
vstd::amax(totalPlayers, playersRange.minValue());
}
// Can't play without at least 2 players
vstd::amax(totalPlayers, 2);
return totalPlayers;
}
si8 CMapGenOptions::getMaxPlayersCount(bool withTemplateLimit) const
{
// Max number of players possible with current settings
auto totalPlayers = 0;
si8 humans = getHumanOrCpuPlayerCount();
si8 cpus = getCompOnlyPlayerCount();
if (humans == RANDOM_SIZE || cpus == RANDOM_SIZE)
{
totalPlayers = PlayerColor::PLAYER_LIMIT_I;
}
else
{
totalPlayers = humans + cpus;
}
if (withTemplateLimit && mapTemplate)
{
auto playersRange = mapTemplate->getPlayers();
//New template can also impose higher limit than current settings
vstd::amin(totalPlayers, playersRange.maxValue());
}
assert (totalPlayers <= PlayerColor::PLAYER_LIMIT_I);
assert (totalPlayers >= 2);
return totalPlayers;
}
si8 CMapGenOptions::getTeamCount() const si8 CMapGenOptions::getTeamCount() const
{ {
return teamCount; return teamCount;
@ -87,7 +156,7 @@ si8 CMapGenOptions::getTeamCount() const
void CMapGenOptions::setTeamCount(si8 value) void CMapGenOptions::setTeamCount(si8 value)
{ {
assert(getPlayerCount() == RANDOM_SIZE || (value >= 0 && value < getPlayerCount()) || value == RANDOM_SIZE); assert(getHumanOrCpuPlayerCount() == RANDOM_SIZE || (value >= 0 && value < getHumanOrCpuPlayerCount()) || value == RANDOM_SIZE);
teamCount = value; teamCount = value;
} }
@ -96,9 +165,20 @@ si8 CMapGenOptions::getCompOnlyPlayerCount() const
return compOnlyPlayerCount; return compOnlyPlayerCount;
} }
si8 CMapGenOptions::getPlayerLimit() const
{
//How many players could we set with current template, ignoring other settings
si8 playerLimit = PlayerColor::PLAYER_LIMIT_I;
if (auto temp = getMapTemplate())
{
playerLimit = static_cast<si8>(temp->getPlayers().maxValue());
}
return playerLimit;
}
void CMapGenOptions::setCompOnlyPlayerCount(si8 value) void CMapGenOptions::setCompOnlyPlayerCount(si8 value)
{ {
assert(value == RANDOM_SIZE || (getPlayerCount() == RANDOM_SIZE || (value >= 0 && value <= PlayerColor::PLAYER_LIMIT_I - getPlayerCount()))); assert(value == RANDOM_SIZE || (getHumanOrCpuPlayerCount() == RANDOM_SIZE || (value >= 0 && value <= getPlayerLimit() - getHumanOrCpuPlayerCount())));
compOnlyPlayerCount = value; compOnlyPlayerCount = value;
resetPlayersMap(); resetPlayersMap();
@ -135,7 +215,7 @@ void CMapGenOptions::setMonsterStrength(EMonsterStrength::EMonsterStrength value
monsterStrength = value; monsterStrength = value;
} }
void CMapGenOptions::resetPlayersMap() void CMapGenOptions::initPlayersMap()
{ {
std::map<PlayerColor, FactionID> rememberTownTypes; std::map<PlayerColor, FactionID> rememberTownTypes;
@ -151,35 +231,149 @@ void CMapGenOptions::resetPlayersMap()
players.clear(); players.clear();
int realPlayersCnt = playerCount; int realPlayersCnt = getHumanOrCpuPlayerCount();
int realCompOnlyPlayersCnt = (compOnlyPlayerCount == RANDOM_SIZE) ? (PlayerColor::PLAYER_LIMIT_I - realPlayersCnt) : compOnlyPlayerCount;
int totalPlayersLimit = realPlayersCnt + realCompOnlyPlayersCnt;
if (getPlayerCount() == RANDOM_SIZE || compOnlyPlayerCount == RANDOM_SIZE)
totalPlayersLimit = static_cast<int>(PlayerColor::PLAYER_LIMIT_I);
//FIXME: what happens with human players here? // Initialize settings for all color even if not present
for(int color = 0; color < totalPlayersLimit; ++color) for(int color = 0; color < getPlayerLimit(); ++color)
{ {
CPlayerSettings player; CPlayerSettings player;
auto pc = PlayerColor(color); auto pc = PlayerColor(color);
player.setColor(pc); player.setColor(pc);
auto playerType = EPlayerType::AI; auto playerType = EPlayerType::AI;
if (getPlayerCount() != RANDOM_SIZE && color < realPlayersCnt) // Color doesn't have to be continuous. Player colors can later be changed manually
if (getHumanOrCpuPlayerCount() != RANDOM_SIZE && color < realPlayersCnt)
{ {
playerType = EPlayerType::HUMAN; playerType = EPlayerType::HUMAN;
} }
else if((getPlayerCount() != RANDOM_SIZE && color >= realPlayersCnt) else if((getHumanOrCpuPlayerCount() != RANDOM_SIZE && color >= realPlayersCnt)
|| (compOnlyPlayerCount != RANDOM_SIZE && color >= (PlayerColor::PLAYER_LIMIT_I-compOnlyPlayerCount))) || (compOnlyPlayerCount != RANDOM_SIZE && color >= (PlayerColor::PLAYER_LIMIT_I - compOnlyPlayerCount)))
{ {
playerType = EPlayerType::COMP_ONLY; playerType = EPlayerType::COMP_ONLY;
} }
player.setPlayerType(playerType); player.setPlayerType(playerType);
player.setTeam(rememberTeam[pc]);
players[pc] = player;
if (vstd::contains(rememberTownTypes, pc)) players[pc] = player;
players[pc].setStartingTown(rememberTownTypes[pc]);
} }
savePlayersMap();
}
void CMapGenOptions::resetPlayersMap()
{
// Called when number of player changes
// But do not update info about already made selections
savePlayersMap();
int realPlayersCnt = getMaxPlayersCount();
//Trim the number of AI players, then CPU-only players, finally human players
auto eraseLastPlayer = [this](EPlayerType playerType) -> bool
{
for (auto it = players.rbegin(); it != players.rend(); ++it)
{
if (it->second.getPlayerType() == playerType)
{
players.erase(it->first);
return true;
}
}
return false; //Can't earse any player of this type
};
while (players.size() > realPlayersCnt)
{
while (eraseLastPlayer(EPlayerType::AI));
while (eraseLastPlayer(EPlayerType::COMP_ONLY));
while (eraseLastPlayer(EPlayerType::HUMAN));
}
//First colors from the list are assigned to human players, then to CPU players
std::vector<PlayerColor> availableColors;
for (ui8 color = 0; color < PlayerColor::PLAYER_LIMIT_I; color++)
{
availableColors.push_back(PlayerColor(color));
}
auto removeUsedColors = [this, &availableColors](EPlayerType playerType)
{
for (auto& player : players)
{
if (player.second.getPlayerType() == playerType)
{
vstd::erase(availableColors, player.second.getColor());
}
}
};
removeUsedColors(EPlayerType::HUMAN);
removeUsedColors(EPlayerType::COMP_ONLY);
//removeUsedColors(EPlayerType::AI);
//Assign unused colors to remaining AI players
while (players.size() < realPlayersCnt && !availableColors.empty())
{
auto color = availableColors.front();
setPlayerTypeForStandardPlayer(color, EPlayerType::AI);
players[color].setColor(color);
availableColors.erase(availableColors.begin());
if (vstd::contains(savedPlayerSettings, color))
{
setPlayerTeam(color, savedPlayerSettings.at(color).getTeam());
// TODO: setter
players[color].setStartingTown(savedPlayerSettings.at(color).getStartingTown());
}
else
{
logGlobal->warn("Adding settings for player %s", color.encode(color));
// Usually, all players should be initialized in initPlayersMap()
CPlayerSettings settings;
players[color] = settings;
}
}
std::set<TeamID> occupiedTeams;
for(auto & player : players)
{
auto team = player.second.getTeam();
if (team != TeamID::NO_TEAM)
{
occupiedTeams.insert(team);
}
}
// TODO: Handle situation when we remove a player and remaining players belong to only one team
for(auto & player : players)
{
if (player.second.getTeam() == TeamID::NO_TEAM)
{
//Find first unused team
for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
{
TeamID team(i);
if(!occupiedTeams.count(team))
{
player.second.setTeam(team);
occupiedTeams.insert(team);
break;
}
}
}
}
}
void CMapGenOptions::savePlayersMap()
{
//Only save already configured players
for (const auto& player : players)
{
savedPlayerSettings[player.first] = player.second;
}
}
const std::map<PlayerColor, CMapGenOptions::CPlayerSettings> & CMapGenOptions::getSavedPlayersMap() const
{
return savedPlayerSettings;
} }
const std::map<PlayerColor, CMapGenOptions::CPlayerSettings> & CMapGenOptions::getPlayersSettings() const const std::map<PlayerColor, CMapGenOptions::CPlayerSettings> & CMapGenOptions::getPlayersSettings() const
@ -190,16 +384,18 @@ const std::map<PlayerColor, CMapGenOptions::CPlayerSettings> & CMapGenOptions::g
void CMapGenOptions::setStartingTownForPlayer(const PlayerColor & color, FactionID town) void CMapGenOptions::setStartingTownForPlayer(const PlayerColor & color, FactionID town)
{ {
auto it = players.find(color); auto it = players.find(color);
if(it == players.end()) assert(0); assert(it != players.end());
it->second.setStartingTown(town); it->second.setStartingTown(town);
} }
void CMapGenOptions::setPlayerTypeForStandardPlayer(const PlayerColor & color, EPlayerType playerType) void CMapGenOptions::setPlayerTypeForStandardPlayer(const PlayerColor & color, EPlayerType playerType)
{ {
// FIXME: Why actually not set it to COMP_ONLY? Ie. when swapping human to another color?
assert(playerType != EPlayerType::COMP_ONLY); assert(playerType != EPlayerType::COMP_ONLY);
auto it = players.find(color); auto it = players.find(color);
if(it == players.end()) assert(0); assert(it != players.end());
it->second.setPlayerType(playerType); it->second.setPlayerType(playerType);
customizedPlayers = true;
} }
const CRmgTemplate * CMapGenOptions::getMapTemplate() const const CRmgTemplate * CMapGenOptions::getMapTemplate() const
@ -209,6 +405,12 @@ const CRmgTemplate * CMapGenOptions::getMapTemplate() const
void CMapGenOptions::setMapTemplate(const CRmgTemplate * value) void CMapGenOptions::setMapTemplate(const CRmgTemplate * value)
{ {
if (mapTemplate == value)
{
//Does not trigger during deserialization
return;
}
mapTemplate = value; mapTemplate = value;
//validate & adapt options according to template //validate & adapt options according to template
if(mapTemplate) if(mapTemplate)
@ -220,13 +422,21 @@ void CMapGenOptions::setMapTemplate(const CRmgTemplate * value)
setHeight(sizes.first.y); setHeight(sizes.first.y);
setHasTwoLevels(sizes.first.z - 1); setHasTwoLevels(sizes.first.z - 1);
} }
if(!mapTemplate->getPlayers().isInRange(getPlayerCount())) si8 maxPlayerCount = getMaxPlayersCount(false);
setPlayerCount(RANDOM_SIZE); si8 minPlayerCount = getMinPlayersCount(false);
if(!mapTemplate->getCpuPlayers().isInRange(getCompOnlyPlayerCount()))
// Neither setting can fit within the template range
if(!mapTemplate->getPlayers().isInRange(minPlayerCount) &&
!mapTemplate->getPlayers().isInRange(maxPlayerCount))
{
setHumanOrCpuPlayerCount(RANDOM_SIZE);
setCompOnlyPlayerCount(RANDOM_SIZE); setCompOnlyPlayerCount(RANDOM_SIZE);
}
if(!mapTemplate->getWaterContentAllowed().count(getWaterContent())) if(!mapTemplate->getWaterContentAllowed().count(getWaterContent()))
setWaterContent(EWaterContent::RANDOM); setWaterContent(EWaterContent::RANDOM);
resetPlayersMap(); // Update teams and player count
} }
} }
@ -261,15 +471,16 @@ bool CMapGenOptions::isRoadEnabled() const
void CMapGenOptions::setPlayerTeam(const PlayerColor & color, const TeamID & team) void CMapGenOptions::setPlayerTeam(const PlayerColor & color, const TeamID & team)
{ {
auto it = players.find(color); auto it = players.find(color);
if(it == players.end()) assert(0); assert(it != players.end());
it->second.setTeam(team); it->second.setTeam(team);
customizedPlayers = true;
} }
void CMapGenOptions::finalize(CRandomGenerator & rand) void CMapGenOptions::finalize(CRandomGenerator & rand)
{ {
logGlobal->info("RMG map: %dx%d, %s underground", getWidth(), getHeight(), getHasTwoLevels() ? "WITH" : "NO"); logGlobal->info("RMG map: %dx%d, %s underground", getWidth(), getHeight(), getHasTwoLevels() ? "WITH" : "NO");
logGlobal->info("RMG settings: players %d, teams %d, computer players %d, computer teams %d, water %d, monsters %d", logGlobal->info("RMG settings: players %d, teams %d, computer players %d, computer teams %d, water %d, monsters %d",
static_cast<int>(getPlayerCount()), static_cast<int>(getTeamCount()), static_cast<int>(getCompOnlyPlayerCount()), static_cast<int>(getHumanOrCpuPlayerCount()), static_cast<int>(getTeamCount()), static_cast<int>(getCompOnlyPlayerCount()),
static_cast<int>(getCompOnlyTeamCount()), static_cast<int>(getWaterContent()), static_cast<int>(getMonsterStrength())); static_cast<int>(getCompOnlyTeamCount()), static_cast<int>(getWaterContent()), static_cast<int>(getMonsterStrength()));
if(!mapTemplate) if(!mapTemplate)
@ -280,25 +491,44 @@ void CMapGenOptions::finalize(CRandomGenerator & rand)
logGlobal->info("RMG template name: %s", mapTemplate->getName()); logGlobal->info("RMG template name: %s", mapTemplate->getName());
if (getPlayerCount() == RANDOM_SIZE) auto maxPlayers = getMaxPlayersCount();
if (getHumanOrCpuPlayerCount() == RANDOM_SIZE)
{ {
auto possiblePlayers = mapTemplate->getPlayers().getNumbers(); auto possiblePlayers = mapTemplate->getPlayers().getNumbers();
//ignore all non-randomized players, make sure these players will not be missing after roll //ignore all non-randomized players, make sure these players will not be missing after roll
possiblePlayers.erase(possiblePlayers.begin(), possiblePlayers.lower_bound(countHumanPlayers() + countCompOnlyPlayers())); possiblePlayers.erase(possiblePlayers.begin(), possiblePlayers.lower_bound(countHumanPlayers() + countCompOnlyPlayers()));
vstd::erase_if(possiblePlayers, [maxPlayers](int i)
{
return i > maxPlayers;
});
assert(!possiblePlayers.empty()); assert(!possiblePlayers.empty());
setPlayerCount (*RandomGeneratorUtil::nextItem(possiblePlayers, rand)); setHumanOrCpuPlayerCount (*RandomGeneratorUtil::nextItem(possiblePlayers, rand));
updatePlayers(); updatePlayers();
} }
if(teamCount == RANDOM_SIZE) if(teamCount == RANDOM_SIZE)
{ {
teamCount = rand.nextInt(getPlayerCount() - 1); teamCount = rand.nextInt(getHumanOrCpuPlayerCount() - 1);
if (teamCount == 1) if (teamCount == 1)
teamCount = 0; teamCount = 0;
} }
if(compOnlyPlayerCount == RANDOM_SIZE) if(compOnlyPlayerCount == RANDOM_SIZE)
{ {
auto possiblePlayers = mapTemplate->getCpuPlayers().getNumbers(); // Use remaining range
compOnlyPlayerCount = *RandomGeneratorUtil::nextItem(possiblePlayers, rand); auto presentPlayers = getHumanOrCpuPlayerCount();
auto possiblePlayers = mapTemplate->getPlayers().getNumbers();
vstd::erase_if(possiblePlayers, [maxPlayers, presentPlayers](int i)
{
return i > (maxPlayers - presentPlayers);
});
if (possiblePlayers.empty())
{
compOnlyPlayerCount = 0;
}
else
{
compOnlyPlayerCount = *RandomGeneratorUtil::nextItem(possiblePlayers, rand);
}
updateCompOnlyPlayers(); updateCompOnlyPlayers();
} }
if(compOnlyTeamCount == RANDOM_SIZE) if(compOnlyTeamCount == RANDOM_SIZE)
@ -328,11 +558,6 @@ void CMapGenOptions::finalize(CRandomGenerator & rand)
assert (vstd::iswithin(waterContent, EWaterContent::NONE, EWaterContent::ISLANDS)); assert (vstd::iswithin(waterContent, EWaterContent::NONE, EWaterContent::ISLANDS));
assert (vstd::iswithin(monsterStrength, EMonsterStrength::GLOBAL_WEAK, EMonsterStrength::GLOBAL_STRONG)); assert (vstd::iswithin(monsterStrength, EMonsterStrength::GLOBAL_WEAK, EMonsterStrength::GLOBAL_STRONG));
//rectangular maps are the future of gaming
//setHeight(20);
//setWidth(50);
logGlobal->trace("Player config:"); logGlobal->trace("Player config:");
int cpuOnlyPlayers = 0; int cpuOnlyPlayers = 0;
for(const auto & player : players) for(const auto & player : players)
@ -355,19 +580,18 @@ void CMapGenOptions::finalize(CRandomGenerator & rand)
} }
logGlobal->trace("Player %d: %s", player.second.getColor(), playerType); logGlobal->trace("Player %d: %s", player.second.getColor(), playerType);
} }
setCompOnlyPlayerCount(cpuOnlyPlayers); //human players are set automaticlaly (?)
logGlobal->info("Final player config: %d total, %d cpu-only", players.size(), static_cast<int>(getCompOnlyPlayerCount())); logGlobal->info("Final player config: %d total, %d cpu-only", players.size(), static_cast<int>(getCompOnlyPlayerCount()));
} }
void CMapGenOptions::updatePlayers() void CMapGenOptions::updatePlayers()
{ {
// Remove AI players only from the end of the players map if necessary // Remove non-human players only from the end of the players map if necessary
for(auto itrev = players.end(); itrev != players.begin();) for(auto itrev = players.end(); itrev != players.begin();)
{ {
auto it = itrev; auto it = itrev;
--it; --it;
if (players.size() == getPlayerCount()) break; if (players.size() == getHumanOrCpuPlayerCount()) break;
if(it->second.getPlayerType() == EPlayerType::AI) if(it->second.getPlayerType() != EPlayerType::HUMAN)
{ {
players.erase(it); players.erase(it);
} }
@ -385,7 +609,7 @@ void CMapGenOptions::updateCompOnlyPlayers()
{ {
auto it = itrev; auto it = itrev;
--it; --it;
if (players.size() <= getPlayerCount()) break; if (players.size() <= getHumanOrCpuPlayerCount()) break;
if(it->second.getPlayerType() == EPlayerType::COMP_ONLY) if(it->second.getPlayerType() == EPlayerType::COMP_ONLY)
{ {
players.erase(it); players.erase(it);
@ -397,11 +621,11 @@ void CMapGenOptions::updateCompOnlyPlayers()
} }
// Add some comp only players if necessary // Add some comp only players if necessary
int compOnlyPlayersToAdd = static_cast<int>(getPlayerCount() - players.size()); int compOnlyPlayersToAdd = static_cast<int>(getHumanOrCpuPlayerCount() - players.size());
if (compOnlyPlayersToAdd < 0) if (compOnlyPlayersToAdd < 0)
{ {
logGlobal->error("Incorrect number of players to add. Requested players %d, current players %d", playerCount, players.size()); logGlobal->error("Incorrect number of players to add. Requested players %d, current players %d", humanOrCpuPlayerCount, players.size());
assert (compOnlyPlayersToAdd < 0); assert (compOnlyPlayersToAdd < 0);
} }
for(int i = 0; i < compOnlyPlayersToAdd; ++i) for(int i = 0; i < compOnlyPlayersToAdd; ++i)
@ -457,6 +681,11 @@ bool CMapGenOptions::checkOptions() const
} }
} }
bool CMapGenOptions::arePlayersCustomized() const
{
return customizedPlayers;
}
std::vector<const CRmgTemplate *> CMapGenOptions::getPossibleTemplates() const std::vector<const CRmgTemplate *> CMapGenOptions::getPossibleTemplates() const
{ {
int3 tplSize(width, height, (hasTwoLevels ? 2 : 1)); int3 tplSize(width, height, (hasTwoLevels ? 2 : 1));
@ -472,21 +701,38 @@ std::vector<const CRmgTemplate *> CMapGenOptions::getPossibleTemplates() const
if(!tmpl->isWaterContentAllowed(getWaterContent())) if(!tmpl->isWaterContentAllowed(getWaterContent()))
return true; return true;
if(getPlayerCount() != -1) auto humanOrCpuPlayerCount = getHumanOrCpuPlayerCount();
auto compOnlyPlayerCount = getCompOnlyPlayerCount();
// Check if total number of players fall inside given range
if(humanOrCpuPlayerCount != CMapGenOptions::RANDOM_SIZE && compOnlyPlayerCount != CMapGenOptions::RANDOM_SIZE)
{ {
if (!tmpl->getPlayers().isInRange(getPlayerCount())) if (!tmpl->getPlayers().isInRange(humanOrCpuPlayerCount + compOnlyPlayerCount))
return true;
}
else if(humanOrCpuPlayerCount != CMapGenOptions::RANDOM_SIZE)
{
// We can always add any number CPU players, but not subtract
if (!(humanOrCpuPlayerCount <= tmpl->getPlayers().maxValue()))
return true;
}
else if(compOnlyPlayerCount != CMapGenOptions::RANDOM_SIZE)
{
//We must fit at least one more human player, but can add any number
if (!(compOnlyPlayerCount < tmpl->getPlayers().maxValue()))
return true; return true;
} }
else else
{ {
// Human players shouldn't be banned when playing with random player count // Human players shouldn't be banned when playing with random player count
if(humanPlayers > *boost::min_element(tmpl->getPlayers().getNumbers())) if(humanPlayers > tmpl->getPlayers().minValue())
return true; return true;
} }
if(compOnlyPlayerCount != -1) if(compOnlyPlayerCount != CMapGenOptions::RANDOM_SIZE)
{ {
if (!tmpl->getCpuPlayers().isInRange(compOnlyPlayerCount)) if (!tmpl->getHumanPlayers().isInRange(compOnlyPlayerCount))
return true; return true;
} }

View File

@ -85,8 +85,12 @@ public:
/// The count of all (human or computer) players ranging from 1 to PlayerColor::PLAYER_LIMIT or RANDOM_SIZE for random. If you call /// The count of all (human or computer) players ranging from 1 to PlayerColor::PLAYER_LIMIT or RANDOM_SIZE for random. If you call
/// this method, all player settings are reset to default settings. /// this method, all player settings are reset to default settings.
si8 getPlayerCount() const; si8 getHumanOrCpuPlayerCount() const;
void setPlayerCount(si8 value); void setHumanOrCpuPlayerCount(si8 value);
si8 getMinPlayersCount(bool withTemplateLimit = true) const;
si8 getMaxPlayersCount(bool withTemplateLimit = true) const;
si8 getPlayerLimit() const;
/// The count of the teams ranging from 0 to <players count - 1> or RANDOM_SIZE for random. /// The count of the teams ranging from 0 to <players count - 1> or RANDOM_SIZE for random.
si8 getTeamCount() const; si8 getTeamCount() const;
@ -114,6 +118,7 @@ public:
/// The first player colors belong to standard players and the last player colors belong to comp only players. /// The first player colors belong to standard players and the last player colors belong to comp only players.
/// All standard players are by default of type EPlayerType::AI. /// All standard players are by default of type EPlayerType::AI.
const std::map<PlayerColor, CPlayerSettings> & getPlayersSettings() const; const std::map<PlayerColor, CPlayerSettings> & getPlayersSettings() const;
const std::map<PlayerColor, CPlayerSettings> & getSavedPlayersMap() const;
void setStartingTownForPlayer(const PlayerColor & color, FactionID town); void setStartingTownForPlayer(const PlayerColor & color, FactionID town);
/// Sets a player type for a standard player. A standard player is the opposite of a computer only player. The /// Sets a player type for a standard player. A standard player is the opposite of a computer only player. The
/// values which can be chosen for the player type are EPlayerType::AI or EPlayerType::HUMAN. /// values which can be chosen for the player type are EPlayerType::AI or EPlayerType::HUMAN.
@ -136,11 +141,15 @@ public:
/// Returns false if there is no template available which fits to the currently selected options. /// Returns false if there is no template available which fits to the currently selected options.
bool checkOptions() const; bool checkOptions() const;
/// Returns true if player colors or teams were set in game GUI
bool arePlayersCustomized() const;
static const si8 RANDOM_SIZE = -1; static const si8 RANDOM_SIZE = -1;
private: private:
void initPlayersMap();
void resetPlayersMap(); void resetPlayersMap();
void savePlayersMap();
int countHumanPlayers() const; int countHumanPlayers() const;
int countCompOnlyPlayers() const; int countCompOnlyPlayers() const;
PlayerColor getNextPlayerColor() const; PlayerColor getNextPlayerColor() const;
@ -150,11 +159,13 @@ private:
si32 width, height; si32 width, height;
bool hasTwoLevels; bool hasTwoLevels;
si8 playerCount, teamCount, compOnlyPlayerCount, compOnlyTeamCount; si8 humanOrCpuPlayerCount, teamCount, compOnlyPlayerCount, compOnlyTeamCount;
EWaterContent::EWaterContent waterContent; EWaterContent::EWaterContent waterContent;
EMonsterStrength::EMonsterStrength monsterStrength; EMonsterStrength::EMonsterStrength monsterStrength;
std::map<PlayerColor, CPlayerSettings> players; std::map<PlayerColor, CPlayerSettings> players;
std::map<PlayerColor, CPlayerSettings> savedPlayerSettings;
std::set<RoadId> enabledRoads; std::set<RoadId> enabledRoads;
bool customizedPlayers;
const CRmgTemplate * mapTemplate; const CRmgTemplate * mapTemplate;
@ -165,7 +176,7 @@ public:
h & width; h & width;
h & height; h & height;
h & hasTwoLevels; h & hasTwoLevels;
h & playerCount; h & humanOrCpuPlayerCount;
h & teamCount; h & teamCount;
h & compOnlyPlayerCount; h & compOnlyPlayerCount;
h & compOnlyTeamCount; h & compOnlyTeamCount;

View File

@ -104,7 +104,7 @@ void CMapGenerator::initPrisonsRemaining()
if (isAllowed) if (isAllowed)
allowedPrisons++; allowedPrisons++;
} }
allowedPrisons = std::max<int> (0, allowedPrisons - 16 * mapGenOptions.getPlayerCount()); //so at least 16 heroes will be available for every player allowedPrisons = std::max<int> (0, allowedPrisons - 16 * mapGenOptions.getHumanOrCpuPlayerCount()); //so at least 16 heroes will be available for every player
} }
void CMapGenerator::initQuestArtsRemaining() void CMapGenerator::initQuestArtsRemaining()
@ -162,7 +162,7 @@ std::string CMapGenerator::getMapDescription() const
std::stringstream ss; std::stringstream ss;
ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, size %dx%d") + ss << boost::str(boost::format(std::string("Map created by the Random Map Generator.\nTemplate was %s, size %dx%d") +
", levels %d, players %d, computers %d, water %s, monster %s, VCMI map") % mapTemplate->getName() % ", levels %d, players %d, computers %d, water %s, monster %s, VCMI map") % mapTemplate->getName() %
map->width() % map->height() % static_cast<int>(map->levels()) % static_cast<int>(mapGenOptions.getPlayerCount()) % map->width() % map->height() % static_cast<int>(map->levels()) % static_cast<int>(mapGenOptions.getHumanOrCpuPlayerCount()) %
static_cast<int>(mapGenOptions.getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions.getWaterContent()] % static_cast<int>(mapGenOptions.getCompOnlyPlayerCount()) % waterContentStr[mapGenOptions.getWaterContent()] %
monsterStrengthStr[monsterStrengthIndex]); monsterStrengthStr[monsterStrengthIndex]);
@ -185,84 +185,120 @@ std::string CMapGenerator::getMapDescription() const
void CMapGenerator::addPlayerInfo() void CMapGenerator::addPlayerInfo()
{ {
// Calculate which team numbers exist // Teams are already configured in CMapGenOptions. However, it's not the case when it comes to map editor
enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2}; // Used as a kind of a local named array index, so left as enum, not enum class
std::array<std::list<int>, 2> teamNumbers;
std::set<int> teamsTotal; std::set<int> teamsTotal;
int teamOffset = 0; if (mapGenOptions.arePlayersCustomized())
int playerCount = 0;
int teamCount = 0;
for (int i = CPHUMAN; i < AFTER_LAST; ++i)
{ {
if (i == CPHUMAN) // Simply copy existing settings set in GUI
{
playerCount = mapGenOptions.getPlayerCount();
teamCount = mapGenOptions.getTeamCount();
}
else
{
playerCount = mapGenOptions.getCompOnlyPlayerCount();
teamCount = mapGenOptions.getCompOnlyTeamCount();
}
if(playerCount == 0) for (const auto & player : mapGenOptions.getPlayersSettings())
{ {
continue; PlayerInfo playerInfo;
playerInfo.team = player.second.getTeam();
if (player.second.getPlayerType() == EPlayerType::COMP_ONLY)
{
playerInfo.canHumanPlay = false;
}
else
{
playerInfo.canHumanPlay = true;
}
map->getMap(this).players[player.first.getNum()] = playerInfo;
teamsTotal.insert(player.second.getTeam());
} }
int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount); }
int teamCountNorm = teamCount; else
if(teamCountNorm == 0) {
// Assign standard teams (in map editor)
// Calculate which team numbers exist
enum ETeams {CPHUMAN = 0, CPUONLY = 1, AFTER_LAST = 2}; // Used as a kind of a local named array index, so left as enum, not enum class
std::array<std::list<int>, 2> teamNumbers;
int teamOffset = 0;
int playerCount = 0;
int teamCount = 0;
// FIXME: Player can be any color, not just 0
for (int i = CPHUMAN; i < AFTER_LAST; ++i)
{ {
teamCountNorm = playerCount; if (i == CPHUMAN)
} {
for(int j = 0; j < teamCountNorm; ++j) playerCount = mapGenOptions.getHumanOrCpuPlayerCount();
{ teamCount = mapGenOptions.getTeamCount();
for(int k = 0; k < playersPerTeam; ++k) }
else
{
playerCount = mapGenOptions.getCompOnlyPlayerCount();
teamCount = mapGenOptions.getCompOnlyTeamCount();
}
if(playerCount == 0)
{
continue;
}
int playersPerTeam = playerCount / (teamCount == 0 ? playerCount : teamCount);
int teamCountNorm = teamCount;
if(teamCountNorm == 0)
{
teamCountNorm = playerCount;
}
for(int j = 0; j < teamCountNorm; ++j)
{
for(int k = 0; k < playersPerTeam; ++k)
{
teamNumbers[i].push_back(j + teamOffset);
}
}
for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j)
{ {
teamNumbers[i].push_back(j + teamOffset); teamNumbers[i].push_back(j + teamOffset);
} }
teamOffset += teamCountNorm;
} }
for(int j = 0; j < playerCount - teamCountNorm * playersPerTeam; ++j) logGlobal->info("Current player settings size: %d", mapGenOptions.getPlayersSettings().size());
{
teamNumbers[i].push_back(j + teamOffset);
}
teamOffset += teamCountNorm;
}
// Team numbers are assigned randomly to every player // Team numbers are assigned randomly to every player
//TODO: allow customize teams in rmg template //TODO: allow to customize teams in rmg template
for(const auto & pair : mapGenOptions.getPlayersSettings()) for(const auto & pair : mapGenOptions.getPlayersSettings())
{
const auto & pSettings = pair.second;
PlayerInfo player;
player.canComputerPlay = true;
int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
if (j == CPHUMAN)
{ {
player.canHumanPlay = true; const auto & pSettings = pair.second;
} PlayerInfo player;
player.canComputerPlay = true;
if(pSettings.getTeam() != TeamID::NO_TEAM) int j = (pSettings.getPlayerType() == EPlayerType::COMP_ONLY) ? CPUONLY : CPHUMAN;
{ if (j == CPHUMAN)
player.team = pSettings.getTeam();
}
else
{
if (teamNumbers[j].empty())
{ {
logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human")); player.canHumanPlay = true;
assert (teamNumbers[j].size());
} }
auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
player.team = TeamID(*itTeam); if(pSettings.getTeam() != TeamID::NO_TEAM)
teamNumbers[j].erase(itTeam); {
player.team = pSettings.getTeam();
}
else
{
if (teamNumbers[j].empty())
{
logGlobal->error("Not enough places in team for %s player", ((j == CPUONLY) ? "CPU" : "CPU or human"));
assert (teamNumbers[j].size());
}
auto itTeam = RandomGeneratorUtil::nextItem(teamNumbers[j], rand);
player.team = TeamID(*itTeam);
teamNumbers[j].erase(itTeam);
}
teamsTotal.insert(player.team.getNum());
map->getMap(this).players[pSettings.getColor().getNum()] = player;
} }
teamsTotal.insert(player.team.getNum());
map->getMap(this).players[pSettings.getColor().getNum()] = player; logGlobal->info("Current team count: %d", teamsTotal.size());
} }
// FIXME: 0
// Can't find info for player 0 (starting zone)
// Can't find info for player 1 (starting zone)
map->getMap(this).howManyTeams = teamsTotal.size(); map->getMap(this).howManyTeams = teamsTotal.size();
} }

View File

@ -557,9 +557,9 @@ const CRmgTemplate::CPlayerCountRange & CRmgTemplate::getPlayers() const
return players; return players;
} }
const CRmgTemplate::CPlayerCountRange & CRmgTemplate::getCpuPlayers() const const CRmgTemplate::CPlayerCountRange & CRmgTemplate::getHumanPlayers() const
{ {
return cpuPlayers; return humanPlayers;
} }
const CRmgTemplate::Zones & CRmgTemplate::getZones() const const CRmgTemplate::Zones & CRmgTemplate::getZones() const
@ -675,13 +675,23 @@ void CRmgTemplate::CPlayerCountRange::fromString(const std::string & value)
} }
} }
int CRmgTemplate::CPlayerCountRange::maxValue() const
{
return *boost::max_element(getNumbers());
}
int CRmgTemplate::CPlayerCountRange::minValue() const
{
return *boost::min_element(getNumbers());
}
void CRmgTemplate::serializeJson(JsonSerializeFormat & handler) void CRmgTemplate::serializeJson(JsonSerializeFormat & handler)
{ {
handler.serializeString("name", name); handler.serializeString("name", name);
serializeSize(handler, minSize, "minSize"); serializeSize(handler, minSize, "minSize");
serializeSize(handler, maxSize, "maxSize"); serializeSize(handler, maxSize, "maxSize");
serializePlayers(handler, players, "players"); serializePlayers(handler, players, "players");
serializePlayers(handler, cpuPlayers, "cpu"); serializePlayers(handler, humanPlayers, "humans"); // TODO: Rename this parameter
{ {
auto connectionsData = handler.enterArray("connections"); auto connectionsData = handler.enterArray("connections");

View File

@ -231,6 +231,9 @@ public:
std::string toString() const; std::string toString() const;
void fromString(const std::string & value); void fromString(const std::string & value);
int maxValue() const;
int minValue() const;
private: private:
std::vector<std::pair<int, int> > range; std::vector<std::pair<int, int> > range;
}; };
@ -247,7 +250,7 @@ public:
const std::string & getName() const; const std::string & getName() const;
const CPlayerCountRange & getPlayers() const; const CPlayerCountRange & getPlayers() const;
const CPlayerCountRange & getCpuPlayers() const; const CPlayerCountRange & getHumanPlayers() const;
std::pair<int3, int3> getMapSizes() const; std::pair<int3, int3> getMapSizes() const;
const Zones & getZones() const; const Zones & getZones() const;
const std::vector<rmg::ZoneConnection> & getConnectedZoneIds() const; const std::vector<rmg::ZoneConnection> & getConnectedZoneIds() const;
@ -261,7 +264,7 @@ private:
std::string id; std::string id;
std::string name; std::string name;
int3 minSize, maxSize; int3 minSize, maxSize;
CPlayerCountRange players, cpuPlayers; CPlayerCountRange players, humanPlayers;
Zones zones; Zones zones;
std::vector<rmg::ZoneConnection> connectedZoneIds; std::vector<rmg::ZoneConnection> connectedZoneIds;
std::set<EWaterContent::EWaterContent> allowedWaterContent; std::set<EWaterContent::EWaterContent> allowedWaterContent;

View File

@ -444,9 +444,13 @@ void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const
auto playerSettings = map.getMapGenOptions().getPlayersSettings(); auto playerSettings = map.getMapGenOptions().getPlayersSettings();
FactionID faction = FactionID::RANDOM; FactionID faction = FactionID::RANDOM;
if (vstd::contains(playerSettings, player)) if (vstd::contains(playerSettings, player))
{
faction = playerSettings[player].getStartingTown(); faction = playerSettings[player].getStartingTown();
}
else else
logGlobal->error("Can't find info for player %d (starting zone)", player.getNum()); {
logGlobal->trace("Player %d (starting zone %d) does not participate in game", player.getNum(), zone.first);
}
if (faction == FactionID::RANDOM) //TODO: check this after a town has already been randomized if (faction == FactionID::RANDOM) //TODO: check this after a town has already been randomized
zonesToPlace.push_back(zone); zonesToPlace.push_back(zone);

View File

@ -332,7 +332,7 @@ void WindowNewMap::on_humanCombo_activated(int index)
ui->humanCombo->setCurrentIndex(humans); ui->humanCombo->setCurrentIndex(humans);
} }
mapGenOptions.setPlayerCount(humans); mapGenOptions.setHumanOrCpuPlayerCount(humans);
int teams = mapGenOptions.getTeamCount(); int teams = mapGenOptions.getTeamCount();
if(teams > humans - 1) if(teams > humans - 1)
@ -361,8 +361,10 @@ void WindowNewMap::on_humanCombo_activated(int index)
void WindowNewMap::on_cpuCombo_activated(int index) void WindowNewMap::on_cpuCombo_activated(int index)
{ {
int humans = mapGenOptions.getPlayerCount(); int humans = mapGenOptions.getHumanOrCpuPlayerCount();
int cpu = ui->cpuCombo->currentData().toInt(); int cpu = ui->cpuCombo->currentData().toInt();
// FIXME: Use mapGenOption method only to calculate actual number of players for current template
if(cpu > PlayerColor::PLAYER_LIMIT_I - humans) if(cpu > PlayerColor::PLAYER_LIMIT_I - humans)
{ {
cpu = PlayerColor::PLAYER_LIMIT_I - humans; cpu = PlayerColor::PLAYER_LIMIT_I - humans;
@ -455,7 +457,7 @@ void WindowNewMap::on_checkSeed_toggled(bool checked)
void WindowNewMap::on_humanTeamsCombo_activated(int index) void WindowNewMap::on_humanTeamsCombo_activated(int index)
{ {
int humans = mapGenOptions.getPlayerCount(); int humans = mapGenOptions.getHumanOrCpuPlayerCount();
int teams = ui->humanTeamsCombo->currentData().toInt(); int teams = ui->humanTeamsCombo->currentData().toInt();
if(teams >= humans) if(teams >= humans)
{ {

View File

@ -46,7 +46,7 @@ TEST(MapFormat, Random)
CRmgTemplate tmpl; CRmgTemplate tmpl;
std::shared_ptr<ZoneOptionsFake> zoneOptions = std::make_shared<ZoneOptionsFake>(); std::shared_ptr<ZoneOptionsFake> zoneOptions = std::make_shared<ZoneOptionsFake>();
const_cast<CRmgTemplate::CPlayerCountRange &>(tmpl.getCpuPlayers()).addRange(1, 4); const_cast<CRmgTemplate::CPlayerCountRange &>(tmpl.getHumanPlayers()).addRange(1, 4);
const_cast<CRmgTemplate::Zones &>(tmpl.getZones())[0] = zoneOptions; const_cast<CRmgTemplate::Zones &>(tmpl.getZones())[0] = zoneOptions;
zoneOptions->setOwner(1); zoneOptions->setOwner(1);
@ -55,7 +55,7 @@ TEST(MapFormat, Random)
opt.setHeight(CMapHeader::MAP_SIZE_MIDDLE); opt.setHeight(CMapHeader::MAP_SIZE_MIDDLE);
opt.setWidth(CMapHeader::MAP_SIZE_MIDDLE); opt.setWidth(CMapHeader::MAP_SIZE_MIDDLE);
opt.setHasTwoLevels(true); opt.setHasTwoLevels(true);
opt.setPlayerCount(4); opt.setHumanOrCpuPlayerCount(4);
opt.setPlayerTypeForStandardPlayer(PlayerColor(0), EPlayerType::HUMAN); opt.setPlayerTypeForStandardPlayer(PlayerColor(0), EPlayerType::HUMAN);
opt.setPlayerTypeForStandardPlayer(PlayerColor(1), EPlayerType::AI); opt.setPlayerTypeForStandardPlayer(PlayerColor(1), EPlayerType::AI);