Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

feat(ai): ai types gg in chat and surrenders when the game is hopeless

Olcay Seygandfdb2663e4ef
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eb12324bd..605c7d618 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -276,6 +276,7 @@ found and fixed — EA's own, not port damage.**
- A beaten team stops running once it is out of range. It used to break off a fight at your front door and walk the whole map back to its base at full health, where nothing repaired it, then stand there until a script or the next wave remembered it. Now it falls back just past the reach of the guns it was losing to, waits, and goes straight back in as soon as that fight turns: your units leave or die, or enough of its own arrive. If the fight still looks lost half a minute later, it goes home and joins the next wave. A team only walks home first when your guns cover the whole road. In 32 Hard against Hard matches on Twilight Flame, 2,748 of 2,756 retreats stopped short of home, and the side doing it lost 92 units a match where it had lost 96, for the same number of kills; that difference is inside the noise of 32 matches. Replays recorded before this change play out differently.
- It looks after its veterans. A heroic tank cost the computer no more thought than one off the line, and it fought to the last chevron. Now a unit with a rank pulls out on its own health, whatever its team does: under 35% for a veteran, 45% for an elite, 55% for a heroic. It also leaves a fight its team is losing before the team gives up, the higher the rank the sooner, though never one it is even in. It goes to whatever of its side's buildings can mend it, a tank to its repair point or a soldier to his barracks, and home when there is none. The computer also counts a ranked unit for a quarter more per chevron when it weighs one army against another, yours included, since your chevrons are on show. Over eight Hard matches on Twilight Flame it pulled out 422 ranked units, 28 of them heroic, and 358 of those went to a building that mends them. Both sides lost 1,979 units where the same matches had cost them 2,080, and 3% less in value, with the same economy. Replays recorded before this change play out differently. A unit sent off to be mended now leaves its squad on the way, so the squad's next order no longer drags it back into the fight half-repaired; it joins a new squad once it is fixed or home. Before, a Black Lotus at 67% health was sent to her barracks four times in a row and never arrived, and one unit was pulled out twelve times in a match. Over the same two 2v2 Hard matches on Twilight Flame the most any unit was pulled out fell from 12 and 8 to 5 and 2, and the ones still pulled out twice came back mended in between. It still sent some again every thirty seconds from wherever they stood: a GLA Angry Mob member that its mob kept marching off was ordered to the barracks eight times, and a Scorpion on its way to the Arms Dealer was turned back into the fight at a third of its health, because the computer's fight logic saw a hurt tank standing still in the queue and sent it back to its squad. A unit sent off to be mended now gets no other order until it is fixed or home. Over six Hard against Medium matches between GLA and the USA on Twilight Flame, the thirty-second repeats went from 13 to none, every unit pulled out twice had come back at full health in between, and 78 of the 89 that came back did so at full health. It also stops pulling out a unit that is not hurt because its squad is losing: Colonel Burton was walked off at full health. A losing fight now pulls a ranked unit only once it is below 90%; in the same matches, 25 pulled at 90% or more became none.
- It no longer runs from a fight in its own base. Home was where the retreat went, so when you rushed a Normal or Hard computer early, every defender was outnumbered, read the fight as lost, and was ordered back to the middle of the base it was already standing in, walking and not shooting, again every second and a half. Sixteen rebels and four Scorpions sent into a Hard USA base a minute in went a full minute without losing one. A fight at home is now fought where it is. While the base is being hit the computer also keeps its attack groups at home: nothing it has gathered leaves on a wave, nothing waiting to leave gathers out on the road, and the groups guarding the base are no longer called away to join an attack. What was gathered goes once none of your units it knows of stands in its base, or half a minute after the last hit. And it spends on the fight. A minute in, its opening has gone on buildings: a Hard USA had two soldiers and 8,000 in the bank when that rush arrived. Now a base under attack trains fighters from every factory that has room, each one picked against whatever of yours it has the least answer to yet, so sixteen rebels and four Scorpions get Rangers as well as Missile Defenders. It stops buying income buildings and extra factories until the fight is over, puts a gun up between the middle of its base and your units when it finds the room, and sends what it has at home at you once there is enough of it to matter; a handful sent out by twos only feeds you. Over four matches the USA left 36 of those 64 rebels alive where it had left 49. China and GLA already train at the pace their barracks allow, and came out about where they were. Replays recorded before this change play out differently.
+- It also knows when the match is over. A computer player that had lost used to make you hunt down its last harvester in a corner of the map. Now it types "GG" in the chat, under its own name and in its own colour, and two seconds later surrenders the way you would from the menu: anything it still has goes to a living ally, or is destroyed when it has none. It gives up when it has nothing left that builds and nothing that could put a builder back up, while behind, or when everything it owns plus its bank is worth a small fraction of the strongest enemy's: under 20% on Easy, 12% on Medium and 8% on Hard. That has to hold for 30 seconds on Easy, 45 on Medium and a full minute on Hard, so a lost fight or a base being rebuilt does not count, and it never quits before minute 6, 8 or 10 respectively. Only skirmish and multiplayer computer players do this; a mission's or a generals' challenge opponent fights on as its map tells it to. Replays recorded before this change play out differently.
## Hard fights each unit from where it is strongest
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/Player.h b/GeneralsMD/Code/GameEngine/Include/Common/Player.h
index 651e86466..83859cd59 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/Player.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/Player.h
@@ -748,6 +748,10 @@ public:
/// Destroy all of the teams for this player, causing him to DIE.
void killPlayer(void);
+ /// Give up: hand everything to a living ally when giveToAlly and one exists, then die. A
+ /// human's surrender message and a hopeless skirmish AI both end here.
+ void surrender(Bool giveToAlly);
+
/// Enabled/Disable all objects of type templateTypeToAffect
void setObjectsEnabled(AsciiString templateTypeToAffect, Bool enable);
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h
index 0b0ea870b..bed1a71e0 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AISkirmishPlayer.h
@@ -110,6 +110,7 @@ protected:
void adjustBuildList(BuildListInfo *list);
Int getMyEnemyPlayerIndex(void);
void acquireEnemy(void);
+ void doSurrender(void); ///< say GG and give up once the match is lost beyond recovery
protected:
Int m_curFrontBaseDefense; // First is 0.
@@ -124,6 +125,9 @@ protected:
UnsignedInt m_frameToCheckEnemy;
Player *m_currentEnemy;
+ UnsignedInt m_hopelessSinceFrame; ///< first check of the current hopeless stretch, 0 while there is hope
+ UnsignedInt m_surrenderFrame; ///< GG said; give up on this frame. 0 until then
+
};
#endif // _AI_SKIRMISH_PLAYER_H_
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
index a1becfd8b..4f80cdfbd 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RTS/Player.cpp
@@ -2168,6 +2168,31 @@ void Player::setUnitsShouldHunt(Bool unitsShouldHunt, CommandSourceType source)
}
}
+//=============================================================================
+void Player::surrender(Bool giveToAlly)
+{
+ if (giveToAlly)
+ {
+ for (Int i = 0; i < ThePlayerList->getPlayerCount(); ++i)
+ {
+ Player *otherPlayer = ThePlayerList->getNthPlayer(i);
+ if (otherPlayer == this)
+ continue;
+ if (getRelationship(otherPlayer->getDefaultTeam()) != ALLIES ||
+ otherPlayer->getRelationship(getDefaultTeam()) != ALLIES)
+ continue;
+ if (TheVictoryConditions->hasSinglePlayerBeenDefeated(otherPlayer))
+ continue;
+
+ // a living ally! hooray!
+ otherPlayer->transferAssetsFromThat(this);
+ break;
+ }
+ }
+ // Kills whatever did not transfer (beacons and the like), or everything when nobody took it.
+ killPlayer();
+}
+
//=============================================================================
void Player::killPlayer(void)
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
index d930bbda9..22b7b6d35 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AISkirmishPlayer.cpp
@@ -42,6 +42,9 @@
#include "Common/ThingTemplate.h"
#include "Common/WellKnownKeys.h"
#include "Common/Xfer.h"
+#include "Common/Recorder.h"
+#include "GameClient/InGameUI.h"
+#include "GameLogic/VictoryConditions.h"
#include "GameLogic/GameLogic.h"
#include "GameLogic/Object.h"
#include "GameLogic/AISkirmishPlayer.h"
@@ -82,7 +85,9 @@ m_curLeftFlankRightDefenseAngle(0),
m_curRightFlankLeftDefenseAngle(0),
m_curRightFlankRightDefenseAngle(0),
m_frameToCheckEnemy(0),
-m_currentEnemy(NULL)
+m_currentEnemy(NULL),
+m_hopelessSinceFrame(0),
+m_surrenderFrame(0)
{
m_frameLastBuildingBuilt = TheGameLogic->getFrame();
@@ -1103,6 +1108,120 @@ void AISkirmishPlayer::doTeamBuilding( void )
void AISkirmishPlayer::update( void )
{
AIPlayer::update();
+ doSurrender();
+}
+
+//----------------------------------------------------------------------------------------------------------
+/** What a player is worth on the field: the build cost of everything alive he owns, and how many of
+ * it can put a building up. */
+struct SurrenderTally
+{
+ Int64 value; // an Unlimited bank alone is 10 million, and the check multiplies by 100
+ Int builders;
+};
+
+static void tallyForSurrender( Object *obj, void *userData )
+{
+ if( obj->isEffectivelyDead() )
+ return;
+ SurrenderTally *tally = (SurrenderTally *)userData;
+ tally->value += obj->getTemplate()->friend_getBuildCost();
+ if( obj->isKindOf( KINDOF_DOZER ) )
+ ++tally->builders;
+}
+
+/// The bank counts toward worth, except an Unlimited one: every side holds the same bottomless 10
+/// million there, which would bury the field in the comparison and never let anyone fall behind.
+static Int64 bankForSurrender( Player *player )
+{
+ const Money *money = player->getMoney();
+ return money->isUnlimited() ? 0 : money->countMoney();
+}
+
+//----------------------------------------------------------------------------------------------------------
+/**
+ * Give up the way a person does when the match is gone: say GG, and a moment later surrender, handing
+ * whatever is left to a living ally. Lost means one of two things, held for a while so a dip in a
+ * fight or a base being rebuilt does not count:
+ * - nothing left that builds and nothing that could put a builder back up, while behind on worth;
+ * - worth (build cost of everything alive, plus the bank unless it is Unlimited) a small fraction of the strongest
+ * living enemy's.
+ * Easy gives up soonest, Hard fights longest. Only in skirmish and multiplayer, and their replays:
+ * a mission or Challenge opponent belongs to its script. Every input is logic state, so every
+ * machine and the replay say GG on the same frame; the chat line is a write to the client.
+ */
+void AISkirmishPlayer::doSurrender( void )
+{
+ if( m_player->isPlayerDead() )
+ return;
+
+ const UnsignedInt now = TheGameLogic->getFrame();
+ if( m_surrenderFrame != 0 )
+ {
+ if( now >= m_surrenderFrame )
+ {
+ DEBUG_LOG(( "AI SURRENDER player %d frame %u\n", (Int)m_player->getPlayerIndex(), now ));
+ m_player->surrender( TRUE );
+ }
+ return;
+ }
+
+ // Every five seconds, players a few frames apart.
+ const UnsignedInt CHECK_FRAMES = 5 * LOGICFRAMES_PER_SECOND;
+ if( (now + 7 * (UnsignedInt)m_player->getPlayerIndex()) % CHECK_FRAMES != 0 )
+ return;
+ if( !TheRecorder->isMultiplayer() || !m_player->isPlayableSide() )
+ return;
+
+ // Easy, Medium, Hard.
+ static const Int EARLIEST_MINUTE[ DIFFICULTY_COUNT ] = { 6, 8, 10 }; // never before this
+ static const Int WORTH_PERCENT[ DIFFICULTY_COUNT ] = { 20, 12, 8 }; // of the strongest enemy's
+ static const Int HOLD_SECONDS[ DIFFICULTY_COUNT ] = { 30, 45, 60 }; // lost this long before GG
+ const Int difficulty = getAIDifficulty();
+
+ if( now < (UnsignedInt)( EARLIEST_MINUTE[ difficulty ] * 60 * LOGICFRAMES_PER_SECOND ) )
+ return;
+
+ SurrenderTally mine = { 0, 0 };
+ m_player->iterateObjects( tallyForSurrender, &mine );
+ mine.value += bankForSurrender( m_player );
+
+ Int64 strongestEnemy = 0;
+ for( Int i = 0; i < ThePlayerList->getPlayerCount(); ++i )
+ {
+ Player *other = ThePlayerList->getNthPlayer( i );
+ if( other == m_player || !other->isPlayableSide() || other->isPlayerObserver() )
+ continue;
+ if( m_player->getRelationship( other->getDefaultTeam() ) != ENEMIES )
+ continue;
+ if( TheVictoryConditions->hasSinglePlayerBeenDefeated( other ) )
+ continue;
+ SurrenderTally theirs = { 0, 0 };
+ other->iterateObjects( tallyForSurrender, &theirs );
+ theirs.value += bankForSurrender( other );
+ if( theirs.value > strongestEnemy )
+ strongestEnemy = theirs.value;
+ }
+
+ const Bool cannotRebuild = !m_player->hasAnyBuildFacility() && mine.builders == 0 && mine.value < strongestEnemy;
+ const Bool outweighed = mine.value * 100 < strongestEnemy * WORTH_PERCENT[ difficulty ];
+ if( !cannotRebuild && !outweighed )
+ {
+ m_hopelessSinceFrame = 0;
+ return;
+ }
+ if( m_hopelessSinceFrame == 0 )
+ {
+ m_hopelessSinceFrame = now;
+ return;
+ }
+ if( now - m_hopelessSinceFrame < (UnsignedInt)( HOLD_SECONDS[ difficulty ] * LOGICFRAMES_PER_SECOND ) )
+ return;
+
+ DEBUG_LOG(( "AI GG player %d frame %u worth %lld enemy %lld rebuild %d\n", (Int)m_player->getPlayerIndex(),
+ now, (long long)mine.value, (long long)strongestEnemy, (Int)!cannotRebuild ));
+ TheInGameUI->chatMessage( m_player, UnicodeString( u"GG" ) );
+ m_surrenderFrame = now + 2 * LOGICFRAMES_PER_SECOND;
}
//----------------------------------------------------------------------------------------------------------
@@ -1364,7 +1483,8 @@ void AISkirmishPlayer::xfer( Xfer *xfer )
// version
// 2: the current enemy and the frame to look for one again. Without them a loaded game picked
// its enemy afresh on the first frame and played on differently from the one that was saved.
- XferVersion currentVersion = 2;
+ // 3: the surrender clock.
+ XferVersion currentVersion = 3;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
@@ -1380,6 +1500,12 @@ void AISkirmishPlayer::xfer( Xfer *xfer )
m_currentEnemy = enemyIndex >= 0 ? ThePlayerList->getNthPlayer( enemyIndex ) : NULL;
}
+ if( version >= 3 )
+ {
+ xfer->xferUnsignedInt( &m_hopelessSinceFrame );
+ xfer->xferUnsignedInt( &m_surrenderFrame );
+ }
+
// front base defense
xfer->xferInt( &m_curFrontBaseDefense );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
index b82cff411..0209d4336 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogicDispatch.cpp
@@ -2499,39 +2499,7 @@ void GameLogic::logicMessageDispatcher( GameMessage *msg, AIGroup *orderedGroup
// --------------------------------------------------------------------------------------------
case GameMessage::MSG_SELF_DESTRUCT:
{
- if (msg->getArgument(0)->boolean)
- {
- // transfer control to any living ally
- // i is used after the loop; VC6 for-scope let it escape.
- Int i;
- for (i =0; i<ThePlayerList->getPlayerCount(); ++i)
- {
- if (i != msg->getPlayerIndex())
- {
- Player *otherPlayer = ThePlayerList->getNthPlayer(i);
- if (thisPlayer->getRelationship(otherPlayer->getDefaultTeam()) == ALLIES &&
- otherPlayer->getRelationship(thisPlayer->getDefaultTeam()) == ALLIES)
- {
- if (TheVictoryConditions->hasSinglePlayerBeenDefeated(otherPlayer))
- continue;
-
- // a living ally! hooray!
- otherPlayer->transferAssetsFromThat(thisPlayer);
- thisPlayer->killPlayer(); // just to be safe (and to kill beacons etc that don't transfer)
- break;
- }
- }
- }
- if (i == ThePlayerList->getPlayerCount())
- {
- // didn't find any allies. die, loner!
- thisPlayer->killPlayer();
- }
- }
- else
- {
- thisPlayer->killPlayer();
- }
+ thisPlayer->surrender(msg->getArgument(0)->boolean);
// There is no reason to do any notification here, it now takes place in the victory conditions.
// bonehead.
break;