/// <summary>
 /// Check if the location provided contains an existing game
 /// </summary>
 public bool CheckIfGameExists(string storageLocation, string gameName, out IntegratedAuthoringToolAsset iat)
 {
     if (Directory.Exists(Path.Combine(storageLocation, gameName)))
     {
         var files = Directory.GetFiles(Path.Combine(storageLocation, gameName), "*.iat");
         foreach (var file in files)
         {
             try
             {
                 var game = IntegratedAuthoringToolAsset.LoadFromFile(file);
                 if (game != null && string.Equals(game.ScenarioName, gameName, StringComparison.CurrentCultureIgnoreCase))
                 {
                     iat = game;
                     return(true);
                 }
             }
             //do not want loading errors to result in exceptions, so catch all
             catch
             {
                 iat = null;
                 return(false);
             }
         }
     }
     iat = null;
     return(false);
 }
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    _iatAsset = IntegratedAuthoringToolAsset.LoadFromFile(ofd.FileName);
                    if (_iatAsset.ErrorOnLoad != null)
                    {
                        MessageBox.Show(_iatAsset.ErrorOnLoad, Resources.ErrorDialogTitle, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                    foreach (var character in _iatAsset.GetAllCharacters())
                    {
                        if (character.ErrorOnLoad != null)
                        {
                            MessageBox.Show("Error when loading character '" + character.CharacterName + "': " + character.ErrorOnLoad, Resources.ErrorDialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                    _saveFileName = ofd.FileName;
                    Reset(false);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "-" + ex.StackTrace, Resources.ErrorDialogTitle, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }
            }
        }
        public ScenarioData(string path, string tts)
        {
            ScenarioPath = path;
            TTSFolder    = tts;

            _iat = IntegratedAuthoringToolAsset.LoadFromFile(ScenarioPath);
        }
Example #4
0
 public SuecaRolePlayCharacter(string agentType, string scenarioPath)
 {
     _randomNumberGenerator = new Random(System.Guid.NewGuid().GetHashCode());
     _events = new List <SuecaEvent>();
     AssetManager.Instance.Bridge = new AssetManagerBridge();
     _iat       = IntegratedAuthoringToolAsset.LoadFromFile(scenarioPath);
     eventsLock = new Object();
     loadScenario(agentType);
     usedUtterances = new List <Utterance>();
     Task.Run(() => { UpdateCoroutine(); });
 }
 public SuecaRolePlayCharacter(int nameId, string agentType, string scenarioPath, EmotionalSuecaPlayer esp)
 {
     _esp                         = esp;
     _agentName                   = "EMYS-" + nameId + "(" + agentType + ")";
     _randomNumberGenerator       = new Random(System.Guid.NewGuid().GetHashCode());
     _events                      = new List <SuecaEvent>();
     AssetManager.Instance.Bridge = new AssetManagerBridge();
     _iat                         = IntegratedAuthoringToolAsset.LoadFromFile(scenarioPath);
     eventsLock                   = new Object();
     LoadScenario(agentType);
     usedUtterances = new List <Utterance>();
     Task.Run(() => { UpdateCoroutine(); });
 }
Example #6
0
    // Use this for initialization
    private void Start()
    {
        AssetManager.Instance.Bridge = new AssetManagerBridge();

        var streamingAssetsPath = Application.streamingAssetsPath;

#if UNITY_EDITOR || UNITY_STANDALONE
        streamingAssetsPath = "file://" + streamingAssetsPath;
#endif
        if (string.IsNullOrEmpty(IATScenario))
        {
            Debug.LogError("Please specify an IAT scenario file!");
            return;
        }

        iat = IntegratedAuthoringToolAsset.LoadFromFile(IATScenario);
        var characterSources = iat.GetAllCharacterSources().ToList();

        //AGENT 1
        agent1RPC = RolePlayCharacterAsset.LoadFromFile(characterSources[1].Source);
        agent1RPC.LoadAssociatedAssets();
        iat.BindToRegistry(agent1RPC.DynamicPropertiesRegistry);

        //AGENT 2
        agent2RPC = RolePlayCharacterAsset.LoadFromFile(characterSources[2].Source);
        agent2RPC.LoadAssociatedAssets();
        iat.BindToRegistry(agent2RPC.DynamicPropertiesRegistry);

        //PLAYER
        playerRPC = RolePlayCharacterAsset.LoadFromFile(characterSources[0].Source);
        playerRPC.LoadAssociatedAssets();
        iat.BindToRegistry(playerRPC.DynamicPropertiesRegistry);

        playerDialogues = DeterminePlayerDialogues();
        UpdatePlayerDialogOptions(true);

        AgentUtterance.text = String.Empty;

        StartCoroutine(UpdateEmotionalState(1f));
        StartCoroutine(DetermineAgentDialogue(0.2f));

        NextPageButton.onClick.RemoveAllListeners();
        NextPageButton.onClick.AddListener(() => OnNextPage());

        PreviousPageButton.onClick.RemoveAllListeners();
        PreviousPageButton.onClick.AddListener(() => OnPreviousPage());

        RestartButton.onClick.RemoveAllListeners();
        RestartButton.onClick.AddListener(() => RestartScene());
    }
Example #7
0
        internal ConfigStore(Platform platform = Platform.Windows)
        {
            Platform     = platform;
            ConfigValues = new Dictionary <ConfigKey, float>();
            var configText       = Templates.ResourceManager.GetString("config");
            var contractResolver = new PrivatePropertyResolver();
            var settings         = new JsonSerializerSettings
            {
                ContractResolver = contractResolver
            };

            ConfigValues = JsonConvert.DeserializeObject <Dictionary <ConfigKey, float> >(configText, settings);
            foreach (var key in (ConfigKey[])Enum.GetValues(typeof(ConfigKey)))
            {
                if (!ConfigValues.ContainsKey(key))
                {
                    throw new Exception("Config key " + key + " not included in config!");
                }
            }
            BoatTypes = new Dictionary <string, List <Position> >();
            var boatText = Templates.ResourceManager.GetString("boat_config");

            BoatTypes     = JsonConvert.DeserializeObject <Dictionary <string, List <Position> > >(boatText);
            GameConfig    = new GameConfig().GetConfig();
            NameConfig    = new NameConfig().GetConfig();
            Avatar.Config = new AvatarGeneratorConfig().GetConfig();

            AssetManager.Instance.Bridge = new TemplateBridge();
            RolePlayCharacter            = RolePlayCharacterAsset.LoadFromFile("template_rpc");
            EmotionalAppraisal           = EmotionalAppraisalAsset.LoadFromFile("template_ea");
            EmotionalDecisionMaking      = EmotionalDecisionMakingAsset.LoadFromFile("template_edm");
            SocialImportance             = SocialImportanceAsset.LoadFromFile("template_si");
            IntegratedAuthoringTool      = IntegratedAuthoringToolAsset.LoadFromFile("template_iat");

            switch (Platform)
            {
            case Platform.Android:
                AssetManager.Instance.Bridge = new AndroidBaseBridge();
                break;

            case Platform.iOS:
                AssetManager.Instance.Bridge = new IOSBaseBridge();
                break;

            case Platform.Windows:
                AssetManager.Instance.Bridge = new BaseBridge();
                break;
            }
        }
        public ScenarioData(string path, string tts)
        {
            ScenarioPath = path;
            TTSFolder    = tts;
            var auxPath = "";

            if (Application.platform.ToString().Contains("OS"))
            {
                auxPath = path.Replace('\\', '/');
            }
            else
            {
                auxPath = path;
            }
            _iat = IntegratedAuthoringToolAsset.LoadFromFile(auxPath);
        }
Example #9
0
    public void NextLevel()
    {
        CurrentLevel++;

        _feedbackScores.Clear();
        GetFeedbackEvent?.Invoke(_feedbackScores, FeedbackLevel);
        if (_scenarios.Any(data => data.LevelId.Equals(CurrentLevel)))
        {
            CurrentScenario = _scenarios.First(data => data.LevelId.Equals(CurrentLevel));
        }
        else
        {
            var validPaths = _allScenarioPaths.Where(p => p.Contains('#')).ToArray();
            var prefixes = validPaths.Select(p => p.Substring(0, p.IndexOf('-', p.IndexOf('-') + 1) + 1)).ToList();
            var character = new List <string> {
                "Positive", "Neutral", "Negative"
            }.OrderBy(dto => random.Next()).First();

            var prefix = _isDemo
                                ? _demoScenarioPrefix + _demoUtterance
                                : prefixes.OrderBy(dto => random.Next()).First();

            // MaxPoints currently hardcoded to 8 for random scenarios.
            // TODO Review validity/balance of MaxPoints = 8
            CurrentScenario = new ScenarioData(CurrentLevel, _allScenarioPaths.Where(x => x.Contains(prefix)).ToArray(), character, 8, prefix);
        }
        if (CurrentScenario != null)
        {
            var index = random.Next(CurrentScenario.ScenarioPaths.Length);
            Debug.Log(CurrentScenario.ScenarioPaths[index]);
            string error;

            ScenarioCode = _isDemo
                                ? _demoUtterance.Split('#')[0]
                                : CurrentScenario.ScenarioPaths[index].Replace(CurrentScenario.Prefix, string.Empty).Split('#')[0];

            _integratedAuthoringTool = IntegratedAuthoringToolAsset.LoadFromFile(Path.Combine("Scenarios", CurrentScenario.ScenarioPaths[index]), out error);
            if (!string.IsNullOrEmpty(error))
            {
                Debug.LogError(error);
            }
            CurrentCharacter = RolePlayCharacterAsset.LoadFromFile(_integratedAuthoringTool.GetAllCharacterSources().First(c => c.Source.Contains(CurrentScenario.Character)).Source);
            CurrentCharacter.LoadAssociatedAssets();
            _integratedAuthoringTool.BindToRegistry(CurrentCharacter.DynamicPropertiesRegistry);
            CurrentCharacter.BodyName = random.NextDouble() >= 0.5 ? "Male" : "Female";
        }
    }
Example #10
0
    public void NextQuestionnaire()
    {
        // Pilot logic to set level id to match CurrentLevel divided by 5, as questionnaires occur every 5 levels. Needs changing if occurance rate of questionnaires change
        CurrentScenario = new ScenarioData(CurrentLevel / 5, _allScenarioPaths.Where(x => x.Contains("Questions")).ToArray(), "Neutral", 0, "Questionnaire");
        string error;

        // Pilot logic to set different questionnaire depending on how many levels have been played. Needs changing if expected appearence of questionnaire changes
        ScenarioCode             = (CurrentLevel < LevelMax && LevelMax > 0 ? 1 : 2).ToString();
        _integratedAuthoringTool = IntegratedAuthoringToolAsset.LoadFromFile(Path.Combine("Scenarios", _allScenarioPaths.First(x => x.Contains("Questions" + ScenarioCode))), out error);
        if (!string.IsNullOrEmpty(error))
        {
            Debug.LogError(error);
        }
        CurrentCharacter = RolePlayCharacterAsset.LoadFromFile(_integratedAuthoringTool.GetAllCharacterSources().First(c => c.Source.Contains("Neutral")).Source);
        CurrentCharacter.LoadAssociatedAssets();
        _integratedAuthoringTool.BindToRegistry(CurrentCharacter.DynamicPropertiesRegistry);
    }
Example #11
0
        static void Main(string[] args)
        {
            var iat = IntegratedAuthoringToolAsset.LoadFromFile("../../../Examples/CiF-Tutorial/JobInterview.iat");

            rpcList = new List <RolePlayCharacterAsset>();

            foreach (var source in iat.GetAllCharacterSources())
            {
                var rpc = RolePlayCharacterAsset.LoadFromFile(source.Source);


                //rpc.DynamicPropertiesRegistry.RegistDynamicProperty(Name.BuildName("Volition"),cif.VolitionPropertyCalculator);
                rpc.LoadAssociatedAssets();

                iat.BindToRegistry(rpc.DynamicPropertiesRegistry);

                rpcList.Add(rpc);
            }


            foreach (var actor in rpcList)
            {
                foreach (var anotherActor in rpcList)
                {
                    if (actor != anotherActor)
                    {
                        var changed = new[] { EventHelper.ActionEnd(anotherActor.CharacterName.ToString(), "Enters", "Room") };
                        actor.Perceive(changed);
                    }
                }
            }


            foreach (var actor in rpcList)
            {
                if (actor.Decide().FirstOrDefault() != null)
                {
                    Console.WriteLine(actor.CharacterName.ToString() + " decided to perform  " + actor.Decide().FirstOrDefault().Name);
                }
            }


            Console.ReadKey();
        }
Example #12
0
        static void Main(string[] args)
        {
            // A lock to proccess requests non concurrently
            // FAtiMA-Toolkit is not thread safe
            Object l = new Object();

            AssetManager.Instance.Bridge = new BasicIOBridge();

            // FAtiMA stuff
            IntegratedAuthoringToolAsset IAT;
            Dictionary <string, RolePlayCharacterAsset> RPCs = new Dictionary <string, RolePlayCharacterAsset>();

            // Ensure that the save directory exists
            Directory.CreateDirectory("Saved Characters");

            // Loading the Scenario
            // Need to use fullpaths for everything due to FAtiMA's handling of paths
            Console.Write("Loading Scenario...");
            IAT = IntegratedAuthoringToolAsset.LoadFromFile(Path.GetFullPath("Example Character\\FAtiMA-DST.iat"));
            Console.WriteLine(" Done");

            WebServer ws = new WebServer(
                (HttpListenerRequest request) =>
            {
                lock (l)
                {
                    Char[] delimiters = { '/' };
                    String[] splitted = request.RawUrl.Split(delimiters);

                    if (splitted.Length < 3)
                    {
                        throw new Exception("Invalid number of arguments for the request.");
                    }

                    RolePlayCharacterAsset RPC;

                    // Check if the referenced RPC already exists (either loaded or saved) and create or load it
                    if (!RPCs.ContainsKey(splitted[1]))
                    {
                        try
                        {
                            // Try and load it from a saved file
                            string s = Path.GetFullPath("Saved Characters\\" + splitted[1] + ".rpc");
                            Console.Write("Loading from saved file... ");

                            RPC = RolePlayCharacterAsset.LoadFromFile(s);
                            RPC.LoadAssociatedAssets();
                            // Bind ValidDialogue dynamic property to RPC
                            IAT.BindToRegistry(RPC.DynamicPropertiesRegistry);

                            RPCs.Add(splitted[1], RPC);
                            Console.WriteLine("Done");
                        }
                        catch
                        {
                            // If it fails we need to load it from the default RPC in the scenario
                            string s = IAT.GetAllCharacterSources().FirstOrDefault().Source;
                            Console.Write("No save file found, loading from default character... ");

                            RPC = RolePlayCharacterAsset.LoadFromFile(s);
                            RPC.LoadAssociatedAssets();
                            // Bind ValidDialogue dynamic property to RPC
                            IAT.BindToRegistry(RPC.DynamicPropertiesRegistry);

                            RPCs.Add(splitted[1], RPC);
                            Console.WriteLine("Done");
                        }
                    }
                    else
                    {
                        // The RPC should exist (already checked)
                        // If we get an error it should stop processing the request with the error
                        // So there is no handling for the ArgumentNullException
                        RPCs.TryGetValue(splitted[1], out RPC);
                    }


                    // Process the request
                    switch (splitted[2])
                    {
                    case "perceptions":
                        if (request.HasEntityBody)
                        {
                            using (System.IO.Stream body = request.InputStream)             // here we have data
                            {
                                using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding))
                                {
                                    string e = reader.ReadToEnd();
                                    var p    = JsonConvert.DeserializeObject <Perceptions>(e);
                                    p.UpdatePerceptions(RPC);
                                    return(JsonConvert.True);
                                }
                            }
                        }
                        return(JsonConvert.Null);

                    case "decide":
                        // If there is a layer for the decision, use it
                        IEnumerable <ActionLibrary.IAction> decision;
                        if (splitted.Count() > 3 && splitted[3] != "")
                        {
                            decision = RPC.Decide((Name)splitted[3]);
                        }
                        else
                        {
                            decision = RPC.Decide();
                        }

                        if (decision.Count() < 1)
                        {
                            return(JsonConvert.Null);
                        }

                        Action action = Action.ToAction(decision.First(), IAT);

                        string t = decision.Count().ToString() + ": ";
                        foreach (ActionLibrary.IAction a in decision)
                        {
                            t += a.Name + " = (" + a.Target + ", " + a.Utility + "); ";
                        }
                        Debug.WriteLine(t);

                        return(JsonConvert.SerializeObject(action));

                    case "events":
                        if (request.HasEntityBody)
                        {
                            using (System.IO.Stream body = request.InputStream)             // here we have data
                            {
                                using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding))
                                {
                                    string s = reader.ReadToEnd();
                                    var e    = JsonConvert.DeserializeObject <Event>(s);
                                    e.Perceive(RPC);
                                    return(JsonConvert.True);
                                }
                            }
                        }
                        return(JsonConvert.Null);

                    default:
                        return(JsonConvert.Null);
                    }
                }
            }
                , "http://localhost:8080/");

            ws.Run();
            Console.WriteLine("Press a key to stop the server and save currently loaded characters.");
            Console.ReadKey();
            Console.WriteLine("Stopping Server...");
            ws.Stop();

            Console.Write("Saving Characters to files... ");
            foreach (KeyValuePair <string, RolePlayCharacterAsset> pair in RPCs)
            {
                pair.Value.SaveToFile(Path.GetFullPath("Saved Characters\\" + pair.Key + ".rpc"));
            }
            Console.WriteLine("Saved {0} characters successfuly.", RPCs.Count);
            Console.WriteLine("Press a key to exit the application...");
            Console.ReadKey();
        }
    private IEnumerator InitGameGlobals()
    {
        string configText = "";

        GameProperties.configurableProperties = new DynamicallyConfigurableGameProperties();


        //Assign configurable game properties from file if any
        //Application.ExternalEval("console.log('streaming assets: "+ Application.streamingAssetsPath + "')");

        string path = Application.streamingAssetsPath + "/config.cfg";

        if (path.Contains("://") || path.Contains(":///")) //url instead of path
        {
            WWW www = new WWW(path);
            yield return(www);

            configText = www.text;
        }
        else
        {
            configText = File.ReadAllText(path);
        }

        UpdateGameConfig(configText);


        GameGlobals.numberOfSpeakingPlayers = 0;
        GameGlobals.currGameId++;
        GameGlobals.currGameRoundId = 0;
        GameGlobals.albumIdCount    = 0;

        GameGlobals.gameDiceNG   = new RandomDiceNG();
        GameGlobals.audioManager = new AudioManager();


        //GameGlobals.playerIdCount = 0;
        //GameGlobals.albumIdCount = 0;

        GameGlobals.albums = new List <Album>(GameProperties.configurableProperties.numberOfAlbumsPerGame);

        //destroy UIs if any
        if (GameGlobals.players != null && GameGlobals.players.Count > 0)
        {
            UIPlayer firstUIPlayer = null;
            int      pIndex        = 0;
            while (firstUIPlayer == null && pIndex < GameGlobals.players.Count)
            {
                firstUIPlayer = (UIPlayer)GameGlobals.players[pIndex++];
                if (firstUIPlayer != null)
                {
                    firstUIPlayer.GetWarningScreenRef().DestroyPoppupPanel();
                    Destroy(firstUIPlayer.GetPlayerCanvas());
                }
            }
        }
        GameGlobals.players = new List <Player>(GameProperties.configurableProperties.numberOfPlayersPerGame);


        GameGlobals.gameLogManager = new MongoDBLogManager();
        GameGlobals.gameLogManager.InitLogs();

        //only generate session data in the first game
        if (GameGlobals.currGameId == 1)
        {
            //GameGlobals.gameLogManager = new DebugLogManager();


            string date = System.DateTime.Now.ToString("ddHHmm");

            //generate external game code from currsessionid and lock it in place
            //gamecode is in the format ddmmhhmmss<3RandomLetters>[TestGameCondition]

            string generatedCode = date; //sb.ToString();

            //generate 3 random letters
            for (int i = 0; i < 3; i++)
            {
                generatedCode += (char)('A' + Random.Range(0, 26));
            }

            GameGlobals.currSessionId = generatedCode;

            //update the gamecode UI
            //GameObject UIGameCodeDisplay = Object.Instantiate(UIGameCodeDisplayPrefab);
            //UIGameCodeDisplay.GetComponentInChildren<Text>().text = "Game Code: " + GameGlobals.currSessionId;
            //Object.DontDestroyOnLoad(UIGameCodeDisplay);
        }
        else
        {
            this.UIStartGameButton.interactable = true;
        }

        if (GameProperties.configurableProperties.isAutomaticalBriefing)                       //generate condition automatically (asynchronous)
        {
            GameGlobals.gameLogManager.GetLastSessionConditionFromLog(YieldedActionsAfterGet); //changes session code
        }
        else
        {
            //create session parameterization
            SessionParameterization mock = new SessionParameterization("mock");
            GameProperties.configurableProperties.possibleParameterizations.Add(mock);
            this.UIStartGameButton.interactable = true;

            GameProperties.configurableProperties.numSessionGames = 0; //not used
        }


        //init fatima strings
        GameGlobals.FAtiMAScenarioPath = "/Scenarios/ForTheRecord-EN.iat";

        AssetManager.Instance.Bridge = new AssetManagerBridge();
        GameGlobals.FAtiMAIat        = IntegratedAuthoringToolAsset.LoadFromFile(GameGlobals.FAtiMAScenarioPath);
    }
Example #14
0
        static void Main(string[] args)
        {
            var iat = IntegratedAuthoringToolAsset.LoadFromFile("../../../Examples/CiF-Tutorial/JobInterview.iat");

            rpcList = new List <RolePlayCharacterAsset>();
            var wm = new WorldModelAsset();

            wm.AddActionEffect((Name)"Event(Action-End, *, Speak(*,*,*,*), [t])", new EffectDTO()
            {
                PropertyName  = (Name)"Has(Floor)",
                NewValue      = (Name)"[t]",
                ObserverAgent = (Name)"*"
            });

            wm.AddActionEffect((Name)"Event(Action-End, [i], Speak([cs],[ns],*,*), SELF)", new EffectDTO()
            {
                PropertyName  = (Name)"DialogueState([i])",
                NewValue      = (Name)"[ns]",
                ObserverAgent = (Name)"[t]"
            });


            wm.AddActionEffect((Name)"Event(Action-End, SELF, Speak([cs],[ns],*,*), [t])", new EffectDTO()
            {
                PropertyName  = (Name)"DialogueState([t])",
                NewValue      = (Name)"[ns]",
                ObserverAgent = (Name)"[i]"
            });

            wm.SaveToFile("../../../Examples/WM-Tutorial/WorldModel.wm");
            foreach (var source in iat.GetAllCharacterSources())
            {
                var rpc = RolePlayCharacterAsset.LoadFromFile(source.Source);


                //rpc.DynamicPropertiesRegistry.RegistDynamicProperty(Name.BuildName("Volition"),cif.VolitionPropertyCalculator);
                rpc.LoadAssociatedAssets();

                iat.BindToRegistry(rpc.DynamicPropertiesRegistry);

                rpcList.Add(rpc);
            }


            foreach (var actor in rpcList)
            {
                foreach (var anotherActor in rpcList)
                {
                    if (actor != anotherActor)
                    {
                        var changed = new[] { EventHelper.ActionEnd(anotherActor.CharacterName.ToString(), "Enters", "Room") };
                        actor.Perceive(changed);
                    }
                }
                //         actor.SaveToFile("../../../Examples/" + actor.CharacterName + "-output1" + ".rpc");
            }



            List <Name>    _events  = new List <Name>();
            List <IAction> _actions = new List <IAction>();

            IAction action = null;

            while (true)
            {
                _actions.Clear();
                foreach (var rpc in rpcList)
                {
                    rpc.Tick++;

                    Console.WriteLine("Character perceiving: " + rpc.CharacterName + " its mood: " + rpc.Mood);

                    rpc.Perceive(_events);
                    var decisions = rpc.Decide();
                    _actions.Add(decisions.FirstOrDefault());

                    foreach (var act in decisions)
                    {
                        Console.WriteLine(rpc.CharacterName + " has this action: " + act.Name);
                    }
                    rpc.SaveToFile("../../../Examples/WM-Tutorial/" + rpc.CharacterName + "-output" + ".rpc");
                }

                _events.Clear();

                var randomGen = new Random(Guid.NewGuid().GetHashCode());

                var pos = randomGen.Next(rpcList.Count);
                int i   = 0;

                var initiator = rpcList[pos];


                action = _actions.ElementAt(pos);

                Console.WriteLine();
                if (action == null)
                {
                    Console.WriteLine(initiator.CharacterName + " does not have any action to do ");
                }

                if (action != null)
                {
                    var initiatorName = initiator.CharacterName.ToString();
                    var targetName    = action.Target.ToString();
                    var nextState     = action.Parameters[1].ToString();
                    var currentState  = action.Parameters[0].ToString();

                    Console.WriteLine("Action: " + initiatorName + " does " + action.Name + " to " +
                                      targetName + "\n" + action.Parameters[1]);

                    _events.Add(EventHelper.ActionEnd(initiatorName, action.Name.ToString(),
                                                      action.Target.ToString()));



                    Console.WriteLine();
                    Console.WriteLine("Dialogue:");
                    Console.WriteLine("Current State: " + currentState);
                    if (iat.GetDialogueActions(action.Parameters[0], action.Parameters[1], action.Parameters[2], action.Parameters[3]).FirstOrDefault() != null)
                    {
                        Console.WriteLine(initiator.CharacterName + " says: ''" +
                                          iat.GetDialogueActions(action.Parameters[0], action.Parameters[1], action.Parameters[2], action.Parameters[3]).FirstOrDefault().Utterance + "'' to " + targetName);
                    }
                    else
                    {
                        Console.WriteLine(initiator.CharacterName + " says: " + "there is no dialogue suited for this action");
                    }


                    // WORLD MODEL
                    var effects = wm.Simulate(_events.ToArray());
                    foreach (var ef in effects)
                    {
                        if (ef.ObserverAgent == (Name)"*")
                        {
                            foreach (var rpc in rpcList)
                            {
                                var proChange =
                                    EventHelper.PropertyChange(ef.PropertyName.ToString(), ef.NewValue.ToString(), "World");
                                rpc.Perceive(proChange);
                            }
                        }

                        else
                        {
                            var proChange =
                                EventHelper.PropertyChange(ef.PropertyName.ToString(), ef.NewValue.ToString(), "World");
                            rpcList.Find(x => x.CharacterName == ef.ObserverAgent).Perceive(proChange);
                        }
                    }

                    Console.WriteLine("Next State: " + nextState);
                }
                Console.WriteLine();
                Console.ReadKey();
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            var playerStr = IATConsts.PLAYER;

            //Loading the asset
            var iat          = IntegratedAuthoringToolAsset.LoadFromFile("../../../Examples/IAT-Tutorial/IATTest.iat");
            var currentState = IATConsts.INITIAL_DIALOGUE_STATE;
            var rpc          = RolePlayCharacterAsset.LoadFromFile(iat.GetAllCharacterSources().FirstOrDefault().Source);

            rpc.LoadAssociatedAssets();
            iat.BindToRegistry(rpc.DynamicPropertiesRegistry);

            iat.GetAllCharacterSources().ToList();
            while (currentState != IATConsts.TERMINAL_DIALOGUE_STATE)
            {
                var playerDialogs = iat.GetDialogueActionsByState(currentState);

                Console.WriteLine("Current Dialogue State: " + currentState);
                Console.WriteLine("Available choices: ");

                for (int i = 0; i < playerDialogs.Count(); i++)
                {
                    Console.WriteLine(i + " - " + playerDialogs.ElementAt(i).Utterance);
                }
                int pos = -1;

                do
                {
                    Console.Write("Select Option: ");
                } while (!Int32.TryParse(Console.ReadLine(), out pos) || pos >= playerDialogs.Count() || pos < 0);

                var chosenDialog = playerDialogs.ElementAt(pos);

                var actionName = iat.BuildSpeakActionName(chosenDialog.Id);
                var speakEvt   = EventHelper.ActionEnd(playerStr, actionName.ToString(), rpc.CharacterName.ToString());

                currentState = chosenDialog.NextState;
                var dialogStateChangeEvt = EventHelper.PropertyChange(string.Format(IATConsts.DIALOGUE_STATE_PROPERTY, playerStr), chosenDialog.NextState, playerStr);

                rpc.Perceive(speakEvt);
                rpc.Perceive(dialogStateChangeEvt);
                var characterActions = rpc.Decide();

                var characterAction = characterActions.FirstOrDefault();

                if (characterAction.Key.ToString() == IATConsts.DIALOG_ACTION_KEY)
                {
                    var dialog = iat.GetDialogueActions(
                        characterAction.Parameters[0],
                        characterAction.Parameters[1],
                        characterAction.Parameters[2],
                        characterAction.Parameters[3]).FirstOrDefault();
                    Console.WriteLine("\n" + rpc.CharacterName + ": " + dialog.Utterance + "\n");
                    currentState = characterAction.Parameters[1].ToString();
                    Console.WriteLine("\nMood: " + rpc.Mood);
                }
                else
                {
                    Console.WriteLine("\n" + rpc.CharacterName + ": " + characterAction.Name + "\n");
                }
            }


            // The next step in this tutorrial is to start using the World Model to cause effects in the belief state of the characters

            Console.WriteLine("Dialogue Reached a Terminal State");
            Console.ReadKey();
        }