public override float GetDiscontentmentValue(Unit unit, WorldModel worldModel)
    {
        var unitTeam       = unit.UnitIdentifier.TeamId;
        int allies         = 0;
        int shieldedAllies = 0;

        foreach (var modelUnit in worldModel.ModelActiveCharacters)
        {
            if (UnitHelpers.GetRelativeOwner(unitTeam, modelUnit.UnitIdentifier.TeamId) == UnitRelativeOwner.Self)
            {
                allies++;

                if (modelUnit.UnitState.ActiveActionEffects.Exists((x) => x is ShieldEffect))
                {
                    shieldedAllies++;
                }
            }
        }

        if (allies == 0)
        {
            return(ProcessDiscontentmentValue(0f));
        }

        return(ProcessDiscontentmentValue(MAX_GOAL_URGENCY - (float)shieldedAllies / allies * MAX_GOAL_URGENCY));
    }
예제 #2
0
    public override float GetDiscontentmentValue(Unit unit, WorldModel worldModel)
    {
        var unitTeam       = unit.UnitIdentifier.TeamId;
        int enemies        = 0;
        int tauntedEnemies = 0;

        foreach (var modelUnit in worldModel.ModelActiveCharacters)
        {
            if (UnitHelpers.GetRelativeOwner(unitTeam, modelUnit.UnitIdentifier.TeamId) == UnitRelativeOwner.Opponent)
            {
                enemies++;

                if (modelUnit.UnitState.ActiveActionEffects.Exists((x) => x is TauntEffect))
                {
                    tauntedEnemies++;
                }
            }
        }

        if (enemies == 0)
        {
            return(0f);
        }

        return(ProcessDiscontentmentValue(MAX_GOAL_URGENCY - (float)tauntedEnemies / enemies * MAX_GOAL_URGENCY));
    }
예제 #3
0
        private bool HandleUnits()
        {
            // Makes a token for the units identifier after a number

            int start = CS.Position;

            if (CS.CurrentChar == '%')
            {
                AddToken(CssTokenType.Units, start, 1);
                CS.Advance(1);
                return(true);
            }

            if (SkipIdentifier())
            {
                UnitType unitType = UnitHelpers.GetUnitType(CS.TextProvider, start, CS.Position - start);

                if (unitType != UnitType.Unknown)
                {
                    // only known units after whitespace (CSS2)
                    AddToken(CssTokenType.Units, start, CS.Position - start);
                    return(true);
                }
            }

            // Not a valid unit identifier, go back
            CS.Position = start;

            return(false);
        }
    public override float GetDiscontentmentValue(Unit unit, WorldModel worldModel)
    {
        var unitTeam     = unit.UnitIdentifier.TeamId;
        int enemies      = 0;
        int aliveEnemies = 0;

        foreach (var modelUnit in worldModel.ModelActiveCharacters)
        {
            if (UnitHelpers.GetRelativeOwner(unitTeam, modelUnit.UnitIdentifier.TeamId) == UnitRelativeOwner.Opponent)
            {
                enemies++;

                if (modelUnit.UnitState.IsAlive)
                {
                    aliveEnemies++;
                }
            }
        }

        if (enemies == 0)
        {
            return(ProcessDiscontentmentValue(0f));
        }

        return(ProcessDiscontentmentValue((float)aliveEnemies / enemies * MAX_GOAL_URGENCY));
    }
예제 #5
0
        public static async Task GenerateClient(string repositoryLocation)
        {
            var outputAbstract    = Path.Combine(repositoryLocation, "src", "ch1seL.TonNet.Abstract", "Generated");
            var outputPathClient  = Path.Combine(repositoryLocation, "src", "ch1seL.TonNet.Client", "Generated");
            var outputPathModules = Path.Combine(repositoryLocation, "src", "ch1seL.TonNet.Client.Modules", "Generated");
            var outputPathModels  = Path.Combine(repositoryLocation, "src", "ch1seL.TonNet.Client.Models", "Generated");

            foreach (var path in new[] { outputAbstract, outputPathClient, outputPathModules, outputPathModels })
            {
                PrepareDirectory(path);
            }

            var apiFilePath = Path.Combine(repositoryLocation, "tools", "ClientGenerator", "Resources", "api.json");

            await using FileStream apiFileStream = File.OpenRead(apiFilePath);
            var tonApi = await JsonSerializer.DeserializeAsync <TonApi>(apiFileStream, Options);

            //Create ITonClient
            UnitHelpers.CreateUnit("ITonClient", unitName =>
                                   ClientClassHelpers.CreateTonClientInterface(unitName, tonApi), Path.Combine(outputAbstract, "ITonClient.cs"), "ch1seL.TonNet.Abstract.Modules");

            //Create TonClient
            UnitHelpers.CreateUnit("TonClient", unitName =>
                                   ClientClassHelpers.CreateTonClientClass(unitName, tonApi), Path.Combine(outputPathClient, "TonClient.cs"),
                                   "System", "Microsoft.Extensions.DependencyInjection", "ch1seL.TonNet.Abstract", "ch1seL.TonNet.Abstract.Modules");

            //Save all used types
            var allTypes = tonApi !.Modules
                           .SelectMany(m => m.Types)
                           .Select(t => NamingConventions.Normalize(t.Name))
                           .ToArray();

            IReadOnlyDictionary <string, string> numberTypesMapping = NumberUtils.MapNumericTypes(tonApi !.Modules);

            foreach (Module module in tonApi !.Modules)
            {
                //Create Interface for Modules
                UnitHelpers.CreateUnit(module.Name, unitName => ModulesClassHelpers.CreateTonModuleInterface(unitName, module),
                                       Path.Combine(outputAbstract, nameof(TonApi.Modules), $"I{NamingConventions.Normalize(module.Name)}Module.cs"), ModulesNamespaces);

                //Create Modules
                UnitHelpers.CreateUnit(module.Name, unitName => ModulesClassHelpers.CreateTonModuleClass(unitName, module),
                                       Path.Combine(outputPathModules, nameof(TonApi.Modules), $"{NamingConventions.Normalize(module.Name)}Module.cs"),
                                       ModulesNamespaces.Union(new[] { "ch1seL.TonNet.Abstract", "ch1seL.TonNet.Abstract.Modules" }).ToArray());

                //Create Models
                var modelClassBuilder = new ModelsClassHelpers(numberTypesMapping, allTypes);
                foreach (TypeElement typeElement in module.Types.Where(t => t.Type != TypeType.None && t.Type != TypeType.Number))
                {
                    UnitHelpers.CreateUnit(module.Name, _ => modelClassBuilder.CreateTonModelClass(typeElement),
                                           Path.Combine(outputPathModels, "Models", $"{NamingConventions.Normalize(typeElement.Name)}.cs"), ModelsNamespaces);
                }
            }
        }
예제 #6
0
        public async Task <IActionResult> RegisterUnit([FromBody] TblUnit unit)
        {
            var result = await Task.Run(() =>
            {
                APIResponse apiResponse = null;
                if (unit == null)
                {
                    return(Ok(new APIResponse()
                    {
                        status = APIStatus.PASS.ToString(), response = "object can not be null"
                    }));
                }

                try
                {
                    var unitlist = new UnitHelpers().GetList(unit.UnitName);
                    if (unitlist.Count() > 0)
                    {
                        return(Ok(new APIResponse()
                        {
                            status = APIStatus.PASS.ToString(), response = $"unit Code {nameof(unitlist)} is already exists ,Please Use Different Code "
                        }));
                    }

                    var result = new UnitHelpers().Register(unit);
                    if (result != null)
                    {
                        apiResponse = new APIResponse()
                        {
                            status = APIStatus.PASS.ToString(), response = result
                        };
                    }
                    else
                    {
                        apiResponse = new APIResponse()
                        {
                            status = APIStatus.FAIL.ToString(), response = "Registration Failed."
                        };
                    }

                    return(Ok(apiResponse));
                }
                catch (Exception ex)
                {
                    return(Ok(new APIResponse()
                    {
                        status = APIStatus.FAIL.ToString(), response = ex.Message
                    }));
                }
            });

            return(result);
        }
    private void OnTriggerExit(Collider other)
    {
        var bcm = other.GetComponent <BaseCharacterMaster>();

        if (bcm != null && unitsInArea.Contains(bcm))
        {
            if (!targetGroup.Contains(UnitHelpers.GetRelativeOwner(CurrentTeamId, bcm.Unit.UnitIdentifier.TeamId)))
            {
                return;
            }
            unitsInArea.Remove(bcm);
            bcm.SetTargeted(false);
        }
    }
예제 #8
0
        public async Task <IActionResult> GetUnitList()
        {
            var result = await Task.Run(() =>
            {
                try
                {
                    var unitList = new UnitHelpers().GetList();
                    if (unitList.Count() > 0)
                    {
                        dynamic expdoObj  = new ExpandoObject();
                        expdoObj.unitList = unitList;
                        return(Ok(new APIResponse {
                            status = APIStatus.PASS.ToString(), response = expdoObj
                        }));
                    }
                    else
                    {
                        return(Ok(new APIResponse {
                            status = APIStatus.FAIL.ToString(), response = "No Data Found."
                        }));
                    }
                }
                catch (Exception ex)
                {
                    return(Ok(new APIResponse()
                    {
                        status = APIStatus.FAIL.ToString(), response = ex.Message
                    }));
                }
                //try
                //{
                //    dynamic expando = new ExpandoObject();
                //    var unitList = new UnitHelpers().GetList();
                //    return Ok(new APIResponse() { status = APIStatus.PASS.ToString(), response = expando });
                //}
                //catch (Exception ex)
                //{
                //    return Ok(new APIResponse() { status = APIStatus.FAIL.ToString(), response = ex.Message });
                //}
            });

            return(result);
        }
예제 #9
0
    public List <Unit> GetUnitsFittingRequirement(Unit actor, List <UnitRelativeOwner> unitRelativeOwners)
    {
        var fittingUnits = new List <Unit>();

        foreach (var modelActiveCharacter in ModelActiveCharacters)
        {
            if (!unitRelativeOwners.Contains(UnitHelpers.GetRelativeOwner(actor.UnitIdentifier.TeamId, modelActiveCharacter.UnitIdentifier.TeamId)))
            {
                continue;
            }

            if (!modelActiveCharacter.UnitState.IsAlive)
            {
                continue;
            }

            fittingUnits.Add(modelActiveCharacter);
        }

        return(fittingUnits);
    }
    public override float GetDiscontentmentValue(Unit unit, WorldModel worldModel)
    {
        var unitTeam            = unit.UnitIdentifier.TeamId;
        int alliesTotalHealth   = 0;
        int alliesCurrentHealth = 0;

        foreach (var modelUnit in worldModel.ModelActiveCharacters)
        {
            if (UnitHelpers.GetRelativeOwner(unitTeam, modelUnit.UnitIdentifier.TeamId) == UnitRelativeOwner.Self)
            {
                alliesTotalHealth   += modelUnit.UnitData.MaxHp;
                alliesCurrentHealth += modelUnit.UnitState.CurrentHp;
            }
        }

        if (alliesTotalHealth == 0)
        {
            return(ProcessDiscontentmentValue(0f));
        }

        return(ProcessDiscontentmentValue(MAX_GOAL_URGENCY - (float)alliesCurrentHealth / alliesTotalHealth * MAX_GOAL_URGENCY));
    }
예제 #11
0
        public IActionResult DeleteUnit(string code)
        {
            try
            {
                if (code == null)
                {
                    return(Ok(new APIResponse()
                    {
                        status = APIStatus.FAIL.ToString(), response = "code can not be null"
                    }));
                }

                var         rs = new UnitHelpers().Delete(code);
                APIResponse apiResponse;
                if (rs != null)
                {
                    apiResponse = new APIResponse()
                    {
                        status = APIStatus.PASS.ToString(), response = rs
                    };
                }
                else
                {
                    apiResponse = new APIResponse()
                    {
                        status = APIStatus.FAIL.ToString(), response = "Deletion Failed."
                    };
                }
                return(Ok(apiResponse));
            }
            catch (Exception ex)
            {
                return(Ok(new APIResponse()
                {
                    status = APIStatus.FAIL.ToString(), response = ex.Message
                }));
            }
        }
예제 #12
0
        public IActionResult UpdateUnit([FromBody] TblUnit unit)
        {
            if (unit == null)
            {
                return(Ok(new APIResponse {
                    status = APIStatus.FAIL.ToString(), response = $"{nameof(unit)} cannot be null"
                }));
            }

            try
            {
                var         rs = new UnitHelpers().Update(unit);
                APIResponse apiResponse;
                if (rs != null)
                {
                    apiResponse = new APIResponse()
                    {
                        status = APIStatus.PASS.ToString(), response = rs
                    };
                }
                else
                {
                    apiResponse = new APIResponse()
                    {
                        status = APIStatus.FAIL.ToString(), response = "Updation Failed."
                    };
                }
                return(Ok(apiResponse));
            }
            catch (Exception ex)
            {
                return(Ok(new APIResponse()
                {
                    status = APIStatus.FAIL.ToString(), response = ex.Message
                }));
            }
        }
예제 #13
0
    public bool DidTeamLose(int teamId)
    {
        int alliesAlive    = 0;
        int opponentsAlive = 0;

        foreach (var modelActiveCharacter in ModelActiveCharacters)
        {
            if (!modelActiveCharacter.UnitState.IsAlive)
            {
                continue;
            }

            if (UnitHelpers.GetRelativeOwner(modelActiveCharacter.UnitIdentifier.TeamId, teamId) == UnitRelativeOwner.Self)
            {
                alliesAlive++;
            }
            else
            {
                opponentsAlive++;
            }
        }

        return(alliesAlive == 0 && opponentsAlive > 0);
    }
    public TurnAction WIP_CalculateGOAPAction(Unit unit, int AIDepth = -1)
    {
        var rootWorldModel    = GetCurrentWorldModelLayer();
        var currentWorldModel = new WorldModel(rootWorldModel.ModelActiveCharacters, rootWorldModel.Queue, rootWorldModel.CurrentlyActiveUnit);

        WorldModelStack.Push(currentWorldModel);

        if (AIDepth == -1)
        {
            AIDepth = DEFAULT_AI_DEPTH;
        }
        int currentDepth = 0;

        var possibleActions = GetAllViableActions(unit);

        Stack <TurnAction> currentActionSequence = new Stack <TurnAction>();
        TurnAction         currentInitialMove    = null;
        var bestAction = possibleActions[0];
        var bestDiscontentmentValue = float.MaxValue;

        bool victoryActionPlanFound = false;
        int  leastStepsToWin        = Int32.MaxValue;

        var DEBUG_loops          = 0;
        var DEBUG_timestampStart = Time.realtimeSinceStartup;

        do
        {
            DEBUG_loops++;

            var isVictoryPlan = currentWorldModel.DidTeamWin(unit.UnitIdentifier.TeamId);
            var isLostPlan    = currentWorldModel.DidTeamLose(unit.UnitIdentifier.TeamId);

            if (WorldModelStack.Count >= AIDepth || isVictoryPlan || isLostPlan)
            {
                var currentDiscontentment = currentWorldModel.GetDiscontentmentForUnit(unit);

                // Basically after finding a VictoryPlan stop considering those plans that don't end in likely victory
                if (!isVictoryPlan && victoryActionPlanFound)
                {
                    continue;
                }
                else if (!isVictoryPlan && !victoryActionPlanFound)
                {
                    if (currentDiscontentment < bestDiscontentmentValue)
                    {
                        bestAction = currentInitialMove;
                        bestDiscontentmentValue = currentDiscontentment;
                    }
                }
                else if (isVictoryPlan && !victoryActionPlanFound)
                {
                    victoryActionPlanFound  = true;
                    bestDiscontentmentValue = currentDiscontentment;
                    leastStepsToWin         = currentActionSequence.Count;
                }
                else if (isVictoryPlan && victoryActionPlanFound)
                {
                    if (currentDiscontentment < bestDiscontentmentValue)
                    {
                        if (leastStepsToWin > currentActionSequence.Count)
                        {
                            leastStepsToWin         = currentActionSequence.Count;
                            bestAction              = currentInitialMove;
                            bestDiscontentmentValue = currentDiscontentment;
                        }
                    }
                }

                try
                {
                    currentActionSequence.Pop();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
                WorldModelStack.Pop();
                currentWorldModel = WorldModelStack.Peek();
            }
            else
            {
                // We should assume AI opponent (player) will make optimal moves as well, we do this at minimum depth to avoid bottlenecks (only checking state right after action)
                if (UnitHelpers.GetRelativeOwner(currentWorldModel.CurrentlyActiveUnit.TeamId, unit.UnitIdentifier.TeamId) == UnitRelativeOwner.Opponent)
                {
                    if (!currentWorldModel.IsProcessed)
                    {
                        if (currentWorldModel.TryGetUnit(currentWorldModel.CurrentlyActiveUnit, out var independentUnit))
                        {
                            var nextAction = CalculateGOBAction(independentUnit, currentWorldModel);
                            currentActionSequence.Push(nextAction);

                            var nextQueueState = currentWorldModel.GetNextQueueState();
                            var nextWorldState = new WorldModel(currentWorldModel.CopyUnits(), nextQueueState.Queue, nextQueueState.CurrentlyActiveUnit);
                            WorldModelStack.Push(nextWorldState);
                            nextWorldState.ApplyTurnAction(nextAction);

                            currentWorldModel.IsProcessed = true;
                        }
                    }
                    else
                    {
                        if (currentActionSequence.Count > 0)
                        {
                            currentActionSequence.Pop();
                        }
                        WorldModelStack.Pop();
                        currentWorldModel = WorldModelStack.Count > 0 ? WorldModelStack.Peek() : null;
                    }
                }
                else
                {
                    var nextActionEnumerator = currentWorldModel.GetNextActionEnumerator();

                    if (nextActionEnumerator.MoveNext())
                    {
                        if (currentActionSequence.Count == 0)
                        {
                            currentInitialMove = nextActionEnumerator.Current;
                        }

                        currentActionSequence.Push(nextActionEnumerator.Current);

                        var nextQueueState = currentWorldModel.GetNextQueueState();
                        WorldModelStack.Push(new WorldModel(currentWorldModel.CopyUnits(), nextQueueState.Queue, nextQueueState.CurrentlyActiveUnit));
                        currentWorldModel = WorldModelStack.Peek();

                        currentWorldModel.ApplyTurnAction(nextActionEnumerator.Current);
                    }
                    else
                    {
                        nextActionEnumerator.Dispose();
                        if (currentActionSequence.Count > 0)
                        {
                            currentActionSequence.Pop();
                        }
                        WorldModelStack.Pop();
                        currentWorldModel = WorldModelStack.Count > 0 ? WorldModelStack.Peek() : null;
                    }
                }
            }
        } while (WorldModelStack.Count > 1);

        Debug.Log($"AI Calculation Report: loops: {DEBUG_loops}, time: {Time.realtimeSinceStartup - DEBUG_timestampStart}, action taken: {bestAction.CommonCommandData.unitAbility.AbilityName}");

        return(bestAction);
    }