예제 #1
0
        // cheap hack to respond to enemy shooting us
        void csai_UnitDamagedEvent(int damaged, int attacker, float damage, Float3 dir)
        {
            /*
             * if (!EnemyUnitDefByDeployedId.ContainsKey(attacker))
             * {
             *  EnemyUnitDefByDeployedId.Add(attacker, aicallback.GetUnitDef(attacker));
             * }
             */
            //if (!EnemyStaticPosByDeployedId.ContainsKey(attacker))
            //{
            Float3 enemypos = aicallback.GetUnitPos(attacker);

            if (enemypos != null &&
                Float3Helper.GetSquaredDistance(enemypos, new Float3(0, 0, 0)) > 10 * 10)
            {
                logfile.WriteLine("unitdamaged, attacker " + attacker + " pos " + enemypos);
                if (!EnemyStaticPosByDeployedId.ContainsKey(attacker))
                {
                    EnemyStaticPosByDeployedId.Add(attacker, enemypos);
                }
                else
                {
                    EnemyStaticPosByDeployedId[attacker] = enemypos;
                }
                if (NewStaticEnemyAddedEvent != null)
                {
                    NewStaticEnemyAddedEvent(attacker, enemypos, null);
                }
            }
            else // else we guess...
            {
                if (FriendlyUnitPositionObserver.GetInstance().PosById.ContainsKey(damaged))
                {
                    Float3 ourunitpos = FriendlyUnitPositionObserver.GetInstance().PosById[damaged];
                    if (ourunitpos != null)
                    {
                        Float3 guessvectortotarget = dir * 300.0;
                        logfile.WriteLine("vectortotarget guess: " + guessvectortotarget.ToString());
                        Float3 possiblepos = ourunitpos + guessvectortotarget;

                        if (!EnemyStaticPosByDeployedId.ContainsKey(attacker))
                        {
                            EnemyStaticPosByDeployedId.Add(attacker, possiblepos);
                        }
                        else
                        {
                            EnemyStaticPosByDeployedId[attacker] = possiblepos;
                        }

                        if (NewStaticEnemyAddedEvent != null)
                        {
                            NewStaticEnemyAddedEvent(attacker, possiblepos, null);
                        }
                        logfile.WriteLine("unitdamaged, attacker " + attacker + " our unit pos " + ourunitpos + " dir " + dir.ToString() + " guess: " + possiblepos.ToString());
                    }
                }
            }
            //}
        }
        void CommanderBuild(IUnitDef unitdef)
        {
            Float3   commanderpos = aicallback.GetUnitPos(commanderid);
            IUnitDef corasydef    = buildtable.UnitDefByName["CORGANT".ToLower()] as IUnitDef;
            Float3   buildsite    = aicallback.ClosestBuildSite(corasydef, commanderpos, 1400.0, 2);

            buildsite = aicallback.ClosestBuildSite(unitdef, buildsite, 1400.0, 2);
            CommanderBuildAt(unitdef, buildsite);
        }
예제 #3
0
        bool DoReclaim(int constructorid)
        {
            if (totalticks == 0) // check ticks first, beacuse metal shows as zero at start
            {
                return(false);
            }
            IUnitDef     unitdef      = UnitDefByUnitId[constructorid] as IUnitDef;
            Float3       mypos        = aicallback.GetUnitPos(constructorid);
            MovementMaps movementmaps = MovementMaps.GetInstance();
            int          currentarea  = movementmaps.GetArea(unitdef, mypos);
            //double nearestreclaimdistancesquared = 1000000;
            //Float3 nearestreclaimpos = null;
            double bestmetaldistanceratio = 0;
            int    bestreclaimid          = 0;
            int    metalspace             = (int)(aicallback.GetMetalStorage() - aicallback.GetMetal());

            logfile.WriteLine("available space in metal storage: " + metalspace);
            int[] nearbyfeatures = aicallback.GetFeatures(mypos, maxreclaimradius);
            bool  reclaimfound   = false;

            foreach (int feature in nearbyfeatures)
            {
                IFeatureDef featuredef = aicallback.GetFeatureDef(feature);
                if (featuredef.metal > 0 && featuredef.metal <= metalspace)
                {
                    Float3 thisfeaturepos         = aicallback.GetFeaturePos(feature);
                    double thisdistance           = Math.Sqrt(Float3Helper.GetSquaredDistance(thisfeaturepos, mypos));
                    double thismetaldistanceratio = featuredef.metal / thisdistance;
                    if (thismetaldistanceratio > bestmetaldistanceratio && movementmaps.GetArea(unitdef, thisfeaturepos) == currentarea)
                    {
                        logfile.WriteLine("Potential reclaim, distance = " + thisdistance + " metal = " + featuredef.metal + " ratio = " + thismetaldistanceratio);
                        bestmetaldistanceratio = thismetaldistanceratio;
                        bestreclaimid          = feature;
                        //         nearestreclaimpo
                        reclaimfound = true;
                    }
                }
            }
            if (reclaimfound && (bestmetaldistanceratio > (1.0 / (100 * reclaimradiusperonehundredmetal))))
            {
                Float3 reclaimpos = aicallback.GetFeaturePos(bestreclaimid);
                logfile.WriteLine("Reclaim found, pos " + reclaimpos.ToString());
                if (csai.DebugOn)
                {
                    aicallback.DrawUnit("ARMMEX", reclaimpos, 0.0f, 200, aicallback.GetMyAllyTeam(), true, true);
                }
                aicallback.GiveOrder(constructorid, new Command(Command.CMD_RECLAIM,
                                                                new double[] { reclaimpos.x, reclaimpos.y, reclaimpos.z, 10 }));
            }
            else
            {
                logfile.WriteLine("No reclaim within parameters");
            }
            return(reclaimfound);
        }
예제 #4
0
 void UpdatePoses()
 {
     //  logfile.WriteLine( "FriendlyUnitPositionObserver start UpdatePoses" );
     foreach (object idobject in MobileUnitIds)
     {
         int    id     = (int)idobject;
         Float3 newpos = aicallback.GetUnitPos(id);
         PosById[id] = newpos;
     }
     //   logfile.WriteLine( "FriendlyUnitPositionObserver end UpdatePoses" );
 }
예제 #5
0
        public void EnemyAdded(int id, IUnitDef unitdef)
        {
            Float3 enemypos = aicallback.GetUnitPos(id);

            for (int i = 0; i < 3; i++)
            {
                Float3 randomoffset = new Float3(random.Next(-enemysightedsearchradius, enemysightedsearchradius), 0, random.Next(-enemysightedsearchradius, enemysightedsearchradius));
                if (csai.DebugOn)
                {
                    aicallback.DrawUnit("ARMARAD", enemypos + randomoffset, 0.0f, 500, aicallback.GetMyAllyTeam(), true, true);
                }
                PriorityTargets.Enqueue(enemypos + randomoffset);
            }
        }
예제 #6
0
 // mark squares as used
 // and keep record of where this unit was, and how big, in case it is destroyed
 public void UnitCreated(int id, IUnitDef unitdef)
 {
     if (!buildinginfobyid.Contains(id) && !unitdefhelp.IsMobile(unitdef))
     {
         Float3 pos     = aicallback.GetUnitPos(id);
         int    mapposx = (int)(pos.x / 8);
         int    mapposy = (int)(pos.z / 8);
         //int unitsizex = (int)Math.Ceiling( unitdef.xsize / 8.0 );
         //int unitsizey = (int)Math.Ceiling( unitdef.ysize / 8.0 );
         int unitsizex = unitdef.xsize;
         int unitsizey = unitdef.ysize;
         logfile.WriteLine("Buildmap unitcreated " + unitdef.name + " mappos " + mapposx + " " + mapposy + " unitsize " + unitsizex + " " + unitsizey);
         buildinginfobyid.Add(id, new BuildingInfo(mapposx, mapposy, unitsizex, unitsizey));
         for (int x = 0; x < unitsizex; x++)
         {
             for (int y = 0; y < unitsizey; y++)
             {
                 int thisx = mapposx + x - unitdef.xsize / 2;
                 int thisy = mapposy + y - unitdef.ysize / 2;
                 SquareAvailable[thisx, thisy] = false;
                 //if( csai.DebugOn )
                 //{
                 // logfile.WriteLine( "marking " + thisx + " " + thisy + " as used by " + unitdef.name );
                 //  aicallback.DrawUnit( "ARMMINE1", new Float3( thisx * 8, aicallback.GetElevation( thisx * 8, thisy * 8 ), thisy * 8 ), 0.0f, 400, aicallback.GetMyAllyTeam(), true, true);
                 //}
             }
         }
     }
 }
예제 #7
0
 void ShowEnemies()
 {
     foreach (DictionaryEntry de in EnemyStaticPosByDeployedId)
     {
         Float3 pos = de.Value as Float3;
         aicallback.DrawUnit(BuildTable.ArmGroundScout, pos, 0.0f, 50, aicallback.GetMyAllyTeam(), true, true);
     }
     foreach (DictionaryEntry de in EnemyUnitDefByDeployedId)
     {
         int enemyid = (int)de.Key;
         //IUnitDef unit = de.Value as Float3;
         Float3 pos = aicallback.GetUnitPos(enemyid);
         aicallback.DrawUnit(BuildTable.ArmL1AntiAir, pos, 0.0f, 50, aicallback.GetMyAllyTeam(), true, true);
     }
     //  logfile.WriteLine( "Number enemies: " + EnemyUnitDefByDeployedId.Count );
 }
        UnitInfo[] GetClosestUnits(Hashtable UnitDefListByDeployedId, Float3 targetpos, int numclosestunits)
        {
            UnitInfo[] closestunits = new UnitInfo[numclosestunits];
            double     worsttopfivesquareddistance = 0; // got to get better than this to enter the list
            int        numclosestunitsfound        = 0;

            foreach (DictionaryEntry de in UnitDefListByDeployedId)
            {
                int      deployedid          = (int)de.Key;
                IUnitDef unitdef             = de.Value as IUnitDef;
                Float3   unitpos             = aicallback.GetUnitPos(deployedid);
                double   unitsquareddistance = Float3Helper.GetSquaredDistance(unitpos, targetpos);
                if (numclosestunitsfound < numclosestunits)
                {
                    UnitInfo unitinfo = new UnitInfo(deployedid, unitpos, unitdef, unitsquareddistance);
                    InsertIntoArray(closestunits, unitinfo, numclosestunitsfound);
                    numclosestunitsfound++;
                    worsttopfivesquareddistance = closestunits[numclosestunitsfound - 1].squareddistance;
                }
                else if (unitsquareddistance < worsttopfivesquareddistance)
                {
                    UnitInfo unitinfo = new UnitInfo(deployedid, unitpos, unitdef, unitsquareddistance);
                    InsertIntoArray(closestunits, unitinfo, numclosestunits);
                    worsttopfivesquareddistance = closestunits[numclosestunits - 1].squareddistance;
                }
            }
            return(closestunits);
        }
예제 #9
0
        void BuildSomething(int factoryid)
        {
            double         highestpriority    = 0;
            IUnitRequester requestertosatisfy = null;
            IUnitDef       factorydef         = FactoryUnitDefByDeployedId[factoryid] as IUnitDef;

            foreach (object requesterobject in Requesters)
            {
                IUnitRequester requester             = requesterobject as IUnitRequester;
                double         thisrequesterpriority = requester.DoYouNeedSomeUnits(new Factory(factoryid, factorydef));
                if (thisrequesterpriority > 0 && thisrequesterpriority > highestpriority)
                {
                    requestertosatisfy = requester;
                    highestpriority    = thisrequesterpriority;
                    logfile.WriteLine("Potential requester to use " + requestertosatisfy.ToString() + " priority: " + highestpriority);
                }
            }

            if (requestertosatisfy != null)
            {
                IUnitDef unitdef = requestertosatisfy.WhatUnitDoYouNeed(new Factory(factoryid, factorydef));
                logfile.WriteLine("factorycontroller factory " + factoryid + " going with request from " + requestertosatisfy.ToString() + " for " + unitdef.humanName);
                requestertosatisfy.WeAreBuildingYouA(unitdef);
                Ownership.GetInstance().RegisterBuildingOrder(this, unitdef, aicallback.GetUnitPos(factoryid));
                aicallback.GiveOrder(factoryid, new Command(-unitdef.id));
            }
        }
 void MobileFusionController_AllUnitsLoaded()
 {
     foreach (int mob in mobileunits)
     {
         Float3 targetpos = aicallback.GetUnitPos(UnitController.GetInstance().UnitDefsByName["armmex"][0].id);
         //aicallback.GiveOrder(mob, new Command(Command.CMD_PATROL, targetpos.ToDoubleArray()));
         GiveOrderWrapper.GetInstance().MoveTo(mob, targetpos);
     }
 }
예제 #11
0
 public void UnitAdded(int id, IUnitDef unitdef)
 {
     if (!LastLosRefreshFrameCountByUnitId.Contains(id))
     {
         LastLosRefreshFrameCountByUnitId.Add(id, aicallback.GetCurrentFrame());
         PosAtLastRefreshByUnitId.Add(id, aicallback.GetUnitPos(id));
         UpdateLosForUnit(id, unitdef);
     }
 }
예제 #12
0
 public void UnitAdded(int id, IUnitDef def)
 {
     //logfile.WriteLine( "Unit " + def.humanName + " radarradius: " + def.radarRadius );
     if (def.name.ToLower() == "armrad")
     {
         logfile.WriteLine("RadarController UnitAdded: " + def.humanName + " id: " + id);
         Radars.Add(id, new Radar(aicallback.GetUnitPos(id), def.radarRadius, def));
     }
 }
예제 #13
0
        void UnitCreatedEvent(int deployedunitid, IUnitDef unitdef)
        {
            IAICallback aicallback = CSAI.GetInstance().aicallback;

            if (aicallback.GetCurrentFrame() <= 1)
            {
                if (unitdef.isCommander)
                {
                    startposition = aicallback.GetUnitPos(deployedunitid);
                    //aicallback.get
                }
            }
        }
예제 #14
0
 void DoSomething()
 {
     if (DefsById.Count >= MinTanksForAttack)  // make sure at least have a few units before attacking
     {
         Float3 approximateattackpos = LastAttackPos;
         if (approximateattackpos == null)
         {
             foreach (int id in DefsById.Keys)
             {
                 Float3 thispos = aicallback.GetUnitPos(id);
                 if (thispos != null)
                 {
                     approximateattackpos = thispos;
                 }
             }
             //approximateattackpos = aicallback.GetUnitPos(DefsById.Keys.GetEnumerator().Current);
         }
         logfile.WriteLine("tankcontroller approximateattackpos: " + approximateattackpos);
         Float3 nearestenemypos = enemyselector.ChooseAttackPoint(approximateattackpos);
         if (nearestenemypos != null)
         {
             attackpackcoordinator.SetTarget(nearestenemypos);
             packcoordinatorselector.ActivatePackCoordinator(attackpackcoordinator);
             LastAttackPos = nearestenemypos;
         }
         else
         {
             if (DefsById.Count > MinTanksForSpreadSearch)
             {
                 spreadsearchpackcoordinator.SetTarget(nearestenemypos);
                 packcoordinatorselector.ActivatePackCoordinator(spreadsearchpackcoordinator);
             }
             else
             {
                 if (unitcontroller.UnitDefsByName.ContainsKey("armcom"))
                 {
                     guardpackcoordinator.SetTarget(unitcontroller.UnitDefsByName["armcom"][0].id);
                     packcoordinatorselector.ActivatePackCoordinator(guardpackcoordinator);
                 }
             }
         }
     }
     else
     {
         if (unitcontroller.UnitDefsByName.ContainsKey("armcom"))
         {
             guardpackcoordinator.SetTarget(unitcontroller.UnitDefsByName["armcom"][0].id);
             packcoordinatorselector.ActivatePackCoordinator(guardpackcoordinator);
         }
     }
 }
예제 #15
0
        public void UnitCreated(int unit)
        {
            aicallback.SendTextMsg("Unit created: " + unit, 0);

            IUnitDef unitdef = aicallback.GetUnitDef(unit);

            aicallback.SendTextMsg("Unit created: " + unitdef.name, 0);

            IMoveData movedata = unitdef.movedata;

            if (movedata != null)
            {
                aicallback.SendTextMsg("Max Slope: " + movedata.maxSlope, 0);
            }

            if (unitdef.isCommander)
            {
                int    numbuildoptions    = unitdef.GetNumBuildOptions();
                string buildoptionsstring = "Build options: ";
                for (int i = 0; i < numbuildoptions; i++)
                {
                    buildoptionsstring += unitdef.GetBuildOption(i);
                }
                aicallback.SendTextMsg(buildoptionsstring, 0);

                Float3 commanderpos = aicallback.GetUnitPos(unit);
                aicallback.SendTextMsg("Commanderpos: " + commanderpos.ToString(), 0);

                int numunitdefs = aicallback.GetNumUnitDefs();
                aicallback.SendTextMsg("Num unit defs: " + numunitdefs, 0);

                for (int i = 1; i <= numunitdefs; i++)
                {
                    IUnitDef thisunitdef = aicallback.GetUnitDefByTypeId(i);
                    if (thisunitdef.name == "ARMSOLAR")
                    {
                        aicallback.SendTextMsg("Found solar collector def: " + thisunitdef.id, 0);

                        Float3 nearestbuildpos = aicallback.ClosestBuildSite(thisunitdef, commanderpos, 1400, 2);
                        aicallback.SendTextMsg("Closest build site: " + nearestbuildpos.ToString(), 0);

                        aicallback.DrawUnit("ARMSOLAR", nearestbuildpos, 0,
                                            200, aicallback.GetMyAllyTeam(), true, true);

                        aicallback.GiveOrder(unit, new Command(-thisunitdef.id, nearestbuildpos.ToDoubleArray()));
                    }
                }
            }
        }
예제 #16
0
        void ExploreWith(int unitid)
        {
            bool         destinationfound = false;
            Float3       currentpos       = aicallback.GetUnitPos(unitid);
            MovementMaps movementmaps     = MovementMaps.GetInstance();
            IUnitDef     unitdef          = UnitDefListByDeployedId[unitid] as IUnitDef;
            int          currentarea      = movementmaps.GetArea(unitdef, currentpos);
            LosMap       losmap           = LosMap.GetInstance();

            if (csai.DebugOn)
            {
                logfile.WriteLine("explorewith unit " + unitid + " " + unitdef.humanName + " area: " + currentarea);
            }

            /*
             * int numtriesleft = 30; // just try a few times then give up
             * // maybe there is a better way to do this?
             * while( !destinationfound )
             * {
             *  Float3 destination = GetRandomDestination();
             * // logfile.WriteLine( "SpreadSearchWithSearchGrid attempt " + destination.ToString() );
             *  int mapx = (int)( destination.x / 16 );
             *  int mapy = (int)( destination.z / 16 );
             *  if( ( movementmaps.GetArea( unitdef, destination ) == currentarea &&
             *      losmap.LastSeenFrameCount[ mapx, mapy ] < recentmeansnumframes || numtriesleft <= 0 ) )
             *  {
             *      logfile.WriteLine( "Looks good. Go. " + numtriesleft + " retriesleft" );
             *      if( csai.DebugOn )
             *      {
             *          aicallback.CreateLineFigure( currentpos, destination,10,true,400,0);
             *          aicallback.DrawUnit( "ARMFAV", destination, 0.0f, 400, aicallback.GetMyAllyTeam(), true, true);
             *      }
             *      aicallback.GiveOrder( unitid, new Command( Command.CMD_MOVE, destination.ToDoubleArray() ) );
             *      return;
             *  }
             *  numtriesleft--;
             * }
             */
            // find nearest, area that hasnt had los recently
            //int maxradius = Math.Max( aicallback.GetMapWidth(), aicallback.GetMapHeight() ) / 2;
            //for( int radius =
            Float3 nextpoint = LosMap.GetInstance().GetNearestUnseen(currentpos, unitdef, 6000);

            if (nextpoint == null)
            {
                nextpoint = GetRandomDestination();
            }
            aicallback.GiveOrder(unitid, new Command(Command.CMD_MOVE, nextpoint.ToDoubleArray()));
        }
예제 #17
0
 void csai_UnitCreatedEvent(int deployedunitid, IUnitDef unitdef)
 {
     foreach (Order order in orders)
     {
         if (order.orderedunit.id == unitdef.id)
         {
             Float3 createdunitpos = aicallback.GetUnitPos(deployedunitid);
             if (Float3Helper.GetSquaredDistance(createdunitpos, order.pos) < maxdistanceconsideredsame * maxdistanceconsideredsame)
             {
                 order.unitdeployedid = deployedunitid;
                 order.factorycontroller.UnitCreated(order, deployedunitid);
             }
         }
     }
 }
예제 #18
0
 public void UnitMoveFailed(int unit)
 {
     try
     {
         if (UnitMoveFailedEvent != null)
         {
             UnitMoveFailedEvent(unit);
         }
         if (DebugOn)
         {
             aicallback.DrawUnit("ARMRAD", aicallback.GetUnitPos(unit), 0.0f, 500, aicallback.GetMyAllyTeam(), true, true);
         }
         // note to self: add add map ponits to interface
     }
     catch (Exception e)
     {
         logfile.WriteLine("Exception: " + e.ToString());
         SendTextMsg("Exception: " + e.ToString());
     }
 }
예제 #19
0
 public void UnitAdded(int deployedid, IUnitDef unitdef)
 {
     if (!isMetalMap)
     {
         if (!Extractors.Contains(deployedid) && unitdefhelp.IsMex(unitdef))
         {
             Float3 mexpos = aicallback.GetUnitPos(deployedid);
             logfile.WriteLine("Metal.UnitAdded, pos " + mexpos.ToString());
             Extractors.Add(deployedid, mexpos);
             double squareextractorradius = ExtractorRadius * ExtractorRadius;
             foreach (MetalSpot metalspot in MetalSpots)
             {
                 double thisdistancesquared = Float3Helper.GetSquaredDistance(metalspot.Pos, mexpos);
                 //   logfile.WriteLine( "squareextractorradius: " + squareextractorradius + " thisdistancesquared: " + thisdistancesquared );
                 if (thisdistancesquared <= squareextractorradius)
                 {
                     MetalSpotsUsed.Add(metalspot);
                     logfile.WriteLine("Marking metal spot used: " + metalspot.Pos.ToString());
                 }
             }
         }
     }
 }
예제 #20
0
        // this is going to have to interact with all sorts of stuff in the future
        // for now keep it simple
        // for now we look for nearby buildings, then nearby enemy units with low speed, then anything
        public Float3 ChooseAttackPoint(Float3 ourpos)
        {
            bool   gotbuilding         = false;
            bool   gotknownunit        = false;
            double BestSquaredDistance = 100000000000;

            int      bestid       = 0;
            IUnitDef defforbestid = null;
            Float3   posforbestid = null;

            //   logfile.WriteLine( "EnemySelector: checking mobile... " );
            foreach (KeyValuePair <int, IUnitDef> kvp in enemycontroller.EnemyUnitDefByDeployedId)
            {
                int      thisenemyid = kvp.Key;
                IUnitDef unitdef     = kvp.Value;
                Float3   enemypos    = aicallback.GetUnitPos(thisenemyid);
                //Float3 enemypos = EnemyMap.GetInstance().
                // logfile.WriteLine( "Found building " +
                if (MovementMaps.GetInstance().GetArea(typicalunitdef, enemypos) == startarea)
                {
                    if (Float3Helper.GetSquaredDistance(new Float3(0, 0, 0), enemypos) > 1)
                    {
                        double thissquareddistance = Float3Helper.GetSquaredDistance(ourpos, enemypos);
                        //   logfile.WriteLine( "EnemySelector: Potential enemy at " + enemypos.ToString() + " squareddistance: " + thissquareddistance );
                        if (unitdef != null)
                        {
                            //   logfile.WriteLine( "unitdef not null " + unitdef.humanName + " ismobile: " + unitdefhelp.IsMobile( unitdef ).ToString() );
                            //   logfile.WriteLine( "gotbuilding = " + gotbuilding.ToString() );
                            if (gotbuilding)
                            {
                                if (!unitdefhelp.IsMobile(unitdef))
                                {
                                    if (thissquareddistance < BestSquaredDistance)
                                    {
                                        //  logfile.WriteLine( "best building so far" );
                                        bestid              = thisenemyid;
                                        gotbuilding         = true;
                                        gotknownunit        = true;
                                        posforbestid        = enemypos;
                                        defforbestid        = unitdef;
                                        BestSquaredDistance = thissquareddistance;
                                    }
                                }
                            }
                            else
                            {
                                if (unitdef.speed < maxenemyspeed) // if we already have building we dont care
                                {
                                    if (thissquareddistance < BestSquaredDistance)
                                    {
                                        //    logfile.WriteLine( "best known so far" );
                                        bestid              = thisenemyid;
                                        gotknownunit        = true;
                                        posforbestid        = enemypos;
                                        defforbestid        = unitdef;
                                        BestSquaredDistance = thissquareddistance;
                                    }
                                }
                            }
                        }
                        else // if unitdef unknown
                        {
                            //  logfile.WriteLine( "gotknownunit = " + gotknownunit.ToString() );
                            if (!gotknownunit) // otherwise just ignore unknown units
                            {
                                if (thissquareddistance < BestSquaredDistance)
                                {
                                    //    logfile.WriteLine( "best unknown so far" );
                                    bestid              = thisenemyid;
                                    posforbestid        = enemypos;
                                    defforbestid        = unitdef;
                                    BestSquaredDistance = thissquareddistance;
                                }
                            }
                        }
                    }
                }
            }

            foreach (KeyValuePair <int, Float3> kvp in enemycontroller.EnemyStaticPosByDeployedId)
            {
                //  logfile.WriteLine( "EnemySelector: checking static... " );
                int    thisenemyid         = kvp.Key;
                Float3 enemypos            = kvp.Value;
                double thissquareddistance = Float3Helper.GetSquaredDistance(ourpos, enemypos);
                //  logfile.WriteLine( "EnemySelector: Potential enemy at " + enemypos.ToString() + " squareddistance: " + thissquareddistance );
                if (thissquareddistance < BestSquaredDistance)
                {
                    //   logfile.WriteLine( "EnemySelector: best distance so far" );
                    bestid       = thisenemyid;
                    gotbuilding  = true;
                    gotknownunit = true;
                    posforbestid = enemypos;
                    //defforbestid = unitdef;
                }
            }

            //if( enemycontroller.EnemyStaticPosByDeployedId.Contains( bestid ) )
            // {
            //     enemycontroller.EnemyStaticPosByDeployedId.Remove( bestid );
            // }

            return(posforbestid);
        }
예제 #21
0
        void Reappraise()
        {
            //  logfile.WriteLine("reappraise>>>");
            foreach (KeyValuePair <int, IUnitDef> scoutkvp in ScoutUnitDefsById)
            {
                int    scoutdeployedid = scoutkvp.Key;
                Float3 scoutpos        = aicallback.GetUnitPos(scoutdeployedid);

                Float3 nearestpos          = null;
                double bestsquareddistance = 100000000;
                int    targetid            = 0;
                // need to add index by position for this, to speed things up
                foreach (KeyValuePair <int, IUnitDef> enemykvp in EnemyController.GetInstance().EnemyUnitDefByDeployedId)
                {
                    int      deployedid = enemykvp.Key;
                    IUnitDef unitdef    = enemykvp.Value;
                    if (unitdef != null)
                    {
                        if (IsPriorityTarget(unitdef))
                        {
                            logfile.WriteLine("considering unit " + deployedid + " " + unitdef.name);
                            Float3 thispos             = aicallback.GetUnitPos(deployedid);
                            double thissquareddistance = Float3Helper.GetSquaredDistance(scoutpos, thispos);
                            if (thissquareddistance < bestsquareddistance)
                            {
                                bool nolasertowersnear = true;
                                foreach (KeyValuePair <int, IUnitDef> attackerkvp in EnemyController.GetInstance().EnemyUnitDefByDeployedId)
                                {
                                    int      attackerid      = attackerkvp.Key;
                                    IUnitDef attackerunitdef = attackerkvp.Value;
                                    if (attackerunitdef != null)
                                    {
                                        if (IsLaserTower(attackerunitdef))
                                        {
                                            Float3 attackerpos = aicallback.GetUnitPos(attackerid);
                                            if (Float3Helper.GetSquaredDistance(attackerpos, thispos) < nearbyforenemiesmeans * nearbyforenemiesmeans)
                                            {
                                                nolasertowersnear = false;
                                            }
                                        }
                                    }
                                }
                                if (nolasertowersnear)
                                {
                                    nearestpos          = thispos;
                                    bestsquareddistance = thissquareddistance;
                                    targetid            = deployedid;
                                }
                            }
                        }
                    }
                }
                if (nearestpos != null)
                {
                    GiveOrderWrapper.GetInstance().Attack(scoutdeployedid, targetid);
                    if (!attackingscouts.Contains(scoutdeployedid))
                    {
                        attackingscouts.Add(scoutdeployedid);
                    }
                }
                else
                {
                    if (attackingscouts.Contains(scoutdeployedid))
                    {
                        ExploreWith(scoutdeployedid);
                        attackingscouts.Remove(scoutdeployedid);
                    }
                }
            }
            //     logfile.WriteLine("reappraise<<<");
        }
예제 #22
0
        void csai_UnitIdleEvent(int deployedunitid)
        {
            IUnitDef unitdef = UnitController.GetInstance().UnitDefByDeployedId[deployedunitid];

            if (!unitdef.canBuild)
            {
                //logfile.WriteLine("cantbuild");
                return;
            }
            logfile.WriteLine("unitidleevent " + deployedunitid + " " + unitdef.name + " " + unitdef.humanName);
            if (ActiveConstructors.Contains(deployedunitid))
            {
                ActiveConstructors.Remove(deployedunitid);
            }
            Ownership.GetInstance().SignalConstructorIsIdle(deployedunitid);
            double       highestpriority = 0;
            List <Order> bestorders      = new List <Order>();

            foreach (Order order in orders)
            {
                double thispriority = order.priority;
                if (thispriority >= highestpriority)
                {
                    int currentunits = order.unitsunderconstruction.Count;
                    if (UnitController.GetInstance().UnitDefsByName.ContainsKey(order.unitname))
                    {
                        currentunits += UnitController.GetInstance().UnitDefsByName[order.unitname].Count;
                    }
                    if (currentunits < order.quantity)
                    {
                        if (BuildTree.GetInstance().CanBuild(unitdef.name.ToLower(), order.unitname))
                        {
                            //if( CanBuild(deployedunitid,
                            if (thispriority > highestpriority)
                            {
                                highestpriority = thispriority;
                                bestorders      = new List <Order>();
                                bestorders.Add(order);
                                csai.DebugSay("Possible order: " + order.ToString());
                            }
                            else if (thispriority == highestpriority)
                            {
                                bestorders.Add(order);
                                csai.DebugSay("Possible order: " + order.ToString());
                            }
                        }
                    }
                }
            }
            //if (bestorders.Count == 0)
            //  {
            //      csai.DebugSay("No orders found");
            //      return;
            //  }
            List <Order> possibleorders = new List <Order>(); // get orders this unit can build
            bool         metalneeded    = false;
            bool         energyneeded   = false;
            IUnitDef     deftobuild     = null;

            foreach (Order order in bestorders)
            {
                csai.DebugSay("bestorder " + order.unitname);
                //if( BuildTree.GetInstance().CanBuild( unitdef.name.ToLower(), order.unitname ) )
                //{
                deftobuild = BuildTable.GetInstance().UnitDefByName[order.unitname];
                if (MetalController.GetInstance().CanBuild(deftobuild))
                {
                    if (EnergyController.GetInstance().CanBuild(deftobuild))
                    {
                        possibleorders.Add(order);
                        csai.DebugSay("possible: " + order.unitname);
                    }
                    else
                    {
                        csai.DebugSay("needs energy");
                        energyneeded = true;
                    }
                }
                else
                {
                    csai.DebugSay("needs metal");
                    metalneeded = true;
                }
                //}
            }
            if (possibleorders.Count == 0)
            {
                if (Level1ConstructorList.GetInstance().defbyid.Count < 1 &&
                    !UnitController.GetInstance().UnitDefsByName.ContainsKey("armcom"))
                {
                    if (BuildConstructionVehicle(deployedunitid, unitdef))
                    {
                        return;
                    }
                }

                if (energyneeded || aicallback.GetEnergy() < aicallback.GetEnergyStorage() / 5)
                {
                    if (BuildSolarCell(deployedunitid))
                    {
                        logfile.WriteLine("building solarcell");
                        if (AssistingConstructors.ContainsKey(deployedunitid))
                        {
                            AssistingConstructors.Remove(deployedunitid);
                        }
                        return;
                    }
                }
                if (metalneeded || aicallback.GetMetal() < aicallback.GetMetalStorage() / 5)
                {
                    Float3 reclaimpos = ReclaimHelper.GetNearestReclaim(aicallback.GetUnitPos(deployedunitid), deployedunitid);
                    if (reclaimpos != null)
                    {
                        GiveOrderWrapper.GetInstance().Reclaim(deployedunitid, reclaimpos, 100);
                        return;
                    }
                    if (BuildMex(deployedunitid))
                    {
                        logfile.WriteLine("building mex");
                        if (AssistingConstructors.ContainsKey(deployedunitid))
                        {
                            AssistingConstructors.Remove(deployedunitid);
                        }
                        return;
                    }
                }


                logfile.WriteLine("offering assistance");
                OfferAssistance(deployedunitid);
                return;
            }
            Order ordertodo = possibleorders[random.Next(0, possibleorders.Count)];

            if (ordertodo.unitname == "armmex")
            {
                BuildMex(deployedunitid);
                if (AssistingConstructors.ContainsKey(deployedunitid))
                {
                    AssistingConstructors.Remove(deployedunitid);
                }
            }
            else
            {
                //ordertodo.unitsunderconstruction += 1;
                deftobuild = BuildTable.GetInstance().UnitDefByName[ordertodo.unitname];
                Float3           pos            = BuildUnit(deployedunitid, ordertodo.unitname);
                Ownership.IOrder ownershiporder = Ownership.GetInstance().RegisterBuildingOrder(this,
                                                                                                deployedunitid,
                                                                                                deftobuild, pos);
                logfile.WriteLine("building: " + ordertodo.unitname);
                ordertodo.unitsunderconstruction.Add(ownershiporder);
                if (AssistingConstructors.ContainsKey(deployedunitid))
                {
                    AssistingConstructors.Remove(deployedunitid);
                }
            }
        }
예제 #23
0
 public void UnitFinished(int id, IUnitDef def)
 {
     logfile.WriteLine("RadarController UnitAdded: " + def.humanName + " id: " + id);
     Radars.Add(id, new Radar(aicallback.GetUnitPos(id), def.radarRadius, def));
 }