示例#1
0
        public ActionResult RemoveDictata(string removeId = "", string authorizeRemove = "")
        {
            string message;
            if (!string.IsNullOrWhiteSpace(authorizeRemove) && removeId.Equals(authorizeRemove))
            {
                ApplicationUser authedUser = UserManager.FindById(User.Identity.GetUserId());

                ILexeme lex = ConfigDataCache.Get<ILexeme>(removeId.Substring(0, removeId.LastIndexOf("_") - 1));
                IDictata obj = lex?.WordForms?.FirstOrDefault(form => form.UniqueKey == removeId);

                if (obj == null)
                {
                    message = "That does not exist";
                }
                else 
                {
                    HashSet<IDictata> wordForms = lex.WordForms.ToHashSet();
                    wordForms.RemoveWhere(form => form.UniqueKey == removeId);
                    lex.WordForms = wordForms.ToArray();

                    lex.Save(authedUser.GameAccount, authedUser.GetStaffRank(User));
                    LoggingUtility.LogAdminCommandUsage("*WEB* - RemoveConstants[" + removeId + "]", authedUser.GameAccount.GlobalIdentityHandle);
                    message = "Delete Successful.";
                }
            }
            else
            {
                message = "You must check the proper remove or unapprove authorization radio button first.";
            }

            return RedirectToAction("Index", new { Message = message });
        }
示例#2
0
        private IDictata GetExistingMeaning(string word, LexicalType wordType = LexicalType.Noun)
        {
            List <string> allContext = new List <string>();

            //Get all local nouns
            allContext.AddRange(_currentPlace.GetContents <IInanimate>().SelectMany(thing => thing.Keywords));
            allContext.AddRange(_currentPlace.GetContents <IMobile>().SelectMany(thing => thing.Keywords));
            allContext.AddRange(_currentPlace.Keywords);
            allContext.AddRange(_actor.Keywords);

            IDictata existingMeaning = null;

            //It's a thing we can see
            if (allContext.Contains(word))
            {
                existingMeaning = new Dictata()
                {
                    Name = word, WordType = LexicalType.ProperNoun
                };
            }
            else
            {
                //TODO: We need to discriminate based on lexical type as well, we could have multiple of the same word with different types
                if (_currentDictionary.Any(dict => dict.Name.Equals(word, StringComparison.InvariantCultureIgnoreCase)))
                {
                    existingMeaning = _currentDictionary.FirstOrDefault(dict => dict.Name.Equals(word, StringComparison.InvariantCultureIgnoreCase))?.GetForm(wordType);
                }
            }

            return(existingMeaning);
        }
示例#3
0
        /// <summary>
        /// Alter the lex entirely including all of its sublex
        /// </summary>
        /// <param name="context">Contextual nature of the request.</param>
        /// <param name="obfuscationLevel">-100 to 100 range.</param>
        /// <returns>the new lex</returns>
        private ILexica Mutate(MessagingType sensoryType, short obfuscationLevel = 0)
        {
            IDictata dict   = GetDictata();
            ILexica  newLex = Clone();

            if (dict != null)
            {
                IDictata newDict = null;
                if (obfuscationLevel != 0)
                {
                    newDict = Thesaurus.ObscureWord(dict, obfuscationLevel);
                }
                else if (Type != LexicalType.ProperNoun &&
                         (Context.Severity + Context.Elegance + Context.Quality > 0 ||
                          Context.Language != dict.Language ||
                          Context.Plural != dict.Plural ||
                          Context.Possessive != dict.Possessive ||
                          Context.Tense != dict.Tense ||
                          Context.Perspective != dict.Perspective ||
                          Context.Determinant != dict.Determinant ||
                          Context.GenderForm.Feminine != dict.Feminine))
                {
                    newDict = Thesaurus.GetSynonym(dict, Context);
                }

                if (newDict != null)
                {
                    newLex.Phrase = newDict.Name;
                }
            }

            return(newLex);
        }
示例#4
0
        public ActionResult AddDictata(string lexemeId, AddEditDictataViewModel vModel)
        {
            ApplicationUser authedUser = UserManager.FindById(User.Identity.GetUserId());

            ILexeme lex = ConfigDataCache.Get<ILexeme>(new ConfigDataCacheKey(typeof(ILexeme), lexemeId, ConfigDataType.Dictionary));
            if (lex == null)
            {
                return RedirectToAction("Index", new { Message = "That does not exist" });
            }

            IDictata newObj = vModel.DataObject;

            lex.AddNewForm(newObj);

            string message;
            if (lex.Save(authedUser.GameAccount, authedUser.GetStaffRank(User)))
            {
                LoggingUtility.LogAdminCommandUsage("*WEB* - AddDictata[" + newObj.UniqueKey + "]", authedUser.GameAccount.GlobalIdentityHandle);
                message = "Creation Successful.";
            }
            else
            {
                message = "Error; Creation failed.";
            }

            return RedirectToAction("Index", new { Message = message });
        }
示例#5
0
 public AddEditDictataViewModel(ILexeme parent, IDictata obj)
 {
     ParentObject   = (Lexeme)parent;
     ValidLanguages = ConfigDataCache.GetAll <ILanguage>();
     DataObject     = (Dictata)obj;
     ValidWords     = ConfigDataCache.GetAll <ILexeme>().Where(lex => lex.Language == parent.Language && lex != parent).SelectMany(lex => lex.WordForms).OrderBy(form => form.Name);
 }
示例#6
0
        /// <summary>
        /// Add a new word form to this lexeme
        /// </summary>
        /// <param name="newWord">The word</param>
        /// <returns>the word with changes</returns>
        public IDictata AddNewForm(IDictata newWord)
        {
            HashSet <IDictata> existingWords = new HashSet <IDictata>(WordForms);

            //Easy way - we dont have one with this type at all
            //Hard way - reject if our semantics are similar by count and the semantics lists match
            if (!existingWords.Any(form => form.WordType == newWord.WordType) ||
                (newWord.Semantics.Count() > 0 && !existingWords.Where(form => form.WordType == newWord.WordType)
                 .Any(form => form.Semantics.Count() == newWord.Semantics.Count() && form.Semantics.All(semantic => newWord.Semantics.Contains(semantic)))))
            {
                int maxForm = 0;

                if (existingWords.Any())
                {
                    maxForm = existingWords.Max(form => form.FormGroup);
                }

                newWord.FormGroup = (short)(maxForm + 1);
                existingWords.Add(newWord);
                WordForms = existingWords.ToArray();
                SystemSave();
                PersistToCache();
            }

            return(newWord);
        }
示例#7
0
        private Dictionary <string, IDictata> BrandWords(IList <Tuple <string, bool> > words)
        {
            Dictionary <string, IDictata> brandedWords = new Dictionary <string, IDictata>();

            //Brand all the words with their current meaning. Continues are in there because the listword inflation might cause collision
            foreach (Tuple <string, bool> word in words.Distinct())
            {
                if (brandedWords.ContainsKey(word.Item1))
                {
                    continue;
                }

                //We have a comma/and list
                if (word.Item2)
                {
                    string[] listWords = word.Item1.Split(new string[] { "and", ",", " " }, StringSplitOptions.RemoveEmptyEntries);

                    IDictata listMeaning = null;
                    foreach (string listWord in listWords)
                    {
                        if (listMeaning != null)
                        {
                            break;
                        }

                        if (brandedWords.ContainsKey(listWord))
                        {
                            listMeaning = brandedWords[listWord];
                        }

                        if (listMeaning == null)
                        {
                            listMeaning = GetExistingMeaning(listWord);
                        }
                    }

                    foreach (string listWord in listWords)
                    {
                        if (brandedWords.ContainsKey(listWord))
                        {
                            continue;
                        }

                        Dictata meaning = new Dictata()
                        {
                            Name     = listWord,
                            WordType = listMeaning.WordType
                        };

                        brandedWords.Add(listWord, meaning);
                    }

                    continue;
                }

                brandedWords.Add(word.Item1, GetExistingMeaning(word.Item1));
            }

            return(brandedWords);
        }
示例#8
0
        public static IDictata GetSynonym(IDictata baseWord, LexicalContext context)
        {
            if (baseWord == null)
            {
                return(baseWord);
            }

            return(FocusFindWord(baseWord.Synonyms.ToList(), context, baseWord));
        }
示例#9
0
        public static IDictataPhrase GetSynonymPhrase(IDictata baseWord, LexicalContext context)
        {
            if (baseWord == null)
            {
                return(null);
            }

            return(FocusFindPhrase(baseWord.PhraseSynonyms.ToList(), context, baseWord));
        }
示例#10
0
        private void ParsePhrase(IEnumerable <ILexica> lexes, ILanguage language)
        {
            if (language?.PhraseRules != null && language.PhraseRules.Count() > 0)
            {
                foreach (DictataPhraseRule phraseRule in language.PhraseRules)
                {
                    int validCount = 0;
                    foreach (IGrouping <LexicalType, ILexica> lexGroup in lexes.GroupBy(lex => lex.Type))
                    {
                        short minCount = phraseRule.Elements.FirstOrDefault(rule => rule.WordType == lexGroup.Key)?.MinimumNumber ?? 0;

                        if (minCount == -1 ||
                            (minCount == 0 && lexGroup.Count() == 0) ||
                            (minCount > 0 && lexGroup.Count() >= minCount))
                        {
                            validCount++;
                        }
                    }

                    //Prepositional position phrase
                    if (validCount == Enum.GetNames(typeof(LexicalType)).Count())
                    {
                        LexicalType primaryType = phraseRule.Elements.FirstOrDefault(ruleLex => ruleLex.Primary)?.WordType ?? LexicalType.Preposition;
                        IDictata    primaryWord = lexes.FirstOrDefault(lex => lex.Type == primaryType)?.GetDictata();

                        if (primaryWord == null)
                        {
                            primaryWord = lexes.FirstOrDefault().GetDictata();
                        }

                        DictataPhrase newPhrase = new DictataPhrase()
                        {
                            Elegance       = (int)Math.Truncate((primaryWord.Elegance + 1) * 1.2),
                            Quality        = (int)Math.Truncate((primaryWord.Quality + 1) * 1.2),
                            Severity       = (int)Math.Truncate((primaryWord.Severity + 1) * 1.2),
                            Antonyms       = primaryWord.Antonyms,
                            PhraseAntonyms = primaryWord.PhraseAntonyms,
                            Synonyms       = primaryWord.Synonyms,
                            PhraseSynonyms = primaryWord.PhraseSynonyms,
                            Feminine       = primaryWord.Feminine,
                            Language       = primaryWord.Language,
                            Perspective    = primaryWord.Perspective,
                            Positional     = primaryWord.Positional,
                            Semantics      = primaryWord.Semantics,
                            Tense          = primaryWord.Tense,
                            Words          = new HashSet <IDictata>(lexes.Select(lex => lex.GetDictata()))
                        };

                        if (!CheckForExistingPhrase(newPhrase))
                        {
                            newPhrase.SystemSave();
                        }
                    }
                }
            }
        }
示例#11
0
 private static int GetSynonymRanking(IDictata word, LexicalContext context)
 {
     return((word.Positional == context.Position ? 5 : 0) +
            (word.Tense == context.Tense ? 5 : 0) +
            (word.Perspective == context.Perspective ? 5 : 0) +
            (word.Possessive == context.Possessive ? 7 : 0) +
            ((context.GenderForm == null || word.Feminine == context.GenderForm?.Feminine) ? 10 : 0) +
            (word.Plural == context.Plural ? 2 : 0) +
            (word.Determinant == context.Determinant ? 2 : 0) +
            (context.Semantics.Any() ? word.Semantics.Count(wrd => context.Semantics.Contains(wrd)) * 10 : 0));
 }
示例#12
0
        /// <summary>
        /// Get the dictata from this lexica
        /// </summary>
        /// <returns>A dictata</returns>
        public IDictata GetDictata()
        {
            ILexeme  lex  = ConfigDataCache.Get <ILexeme>(new ConfigDataCacheKey(typeof(ILexeme), string.Format("{0}_{1}", Context?.Language?.Name, Phrase), ConfigDataType.Dictionary));
            IDictata dict = lex?.GetForm(Type);

            if (dict == null)
            {
                dict = GenerateDictata();
            }

            return(dict);
        }
示例#13
0
        /// <summary>
        /// Fluent (returns itself), add a lexica to the sentence, sentence logic applies here
        /// </summary>
        /// <param name="lex"></param>
        /// <returns></returns>
        public ILexicalSentence AddEvent(ISensoryEvent lex, bool recursive = true)
        {
            lex.Event.Context.Language = Language;

            //Contractive rules
            IDictata lexDict = lex.Event.GetDictata();

            foreach (IContractionRule contractionRule in Language.ContractionRules.Where(rul => rul.First == lexDict || rul.Second == lexDict))
            {
                if (!lex.Event.Modifiers.Any(mod => contractionRule.First.Equals(mod.GetDictata()) || contractionRule.Second.Equals(mod.GetDictata())))
                {
                    continue;
                }

                lex.Event.Modifiers.RemoveWhere(mod => contractionRule.First.Equals(mod.GetDictata()) || contractionRule.Second.Equals(mod.GetDictata()));

                lex.Event.Phrase = contractionRule.Contraction.Name;
            }

            //Sentence placement rules
            SentenceGrammarRule rule = Language.SentenceRules.FirstOrDefault(rul => rul.Type == Type && rul.Fragment == lex.Event.Role);

            if (rule != null)
            {
                //subject
                if (rule.SubjectPredicate)
                {
                    Subject.Add(new Tuple <ISensoryEvent, short>(lex, rule.ModificationOrder));
                }
                else
                {
                    Predicate.Add(new Tuple <ISensoryEvent, short>(lex, rule.ModificationOrder));
                }
            }
            else
            {
                Modifiers.Add(new Tuple <ISensoryEvent, short>(lex, 99));
            }

            if (recursive)
            {
                HashSet <ILexica> newMods = new HashSet <ILexica>();
                foreach (ILexica mod in lex.Event.Modifiers.Where(mod => mod.Role != GrammaticalType.None && mod.Role != GrammaticalType.Descriptive))
                {
                    AddEvent(new SensoryEvent(mod, lex.Strength, lex.SensoryType));
                    newMods.Add(mod);
                }

                lex.Event.Modifiers.RemoveWhere(modi => newMods.Any(mods => mods.Equals(modi)));
            }

            return(this);
        }
示例#14
0
        public override object Convert(object input)
        {
            string stringInput = input.ToString();

            if (string.IsNullOrWhiteSpace(stringInput))
            {
                return(null);
            }

            IDictata returnValue = ConfigDataCache.Get <ILexeme>(new ConfigDataCacheKey(typeof(ILexeme), stringInput, ConfigDataType.Dictionary))?.WordForms.FirstOrDefault();

            return(returnValue);
        }
示例#15
0
        public static IDictata ObscureWord(IDictata word, short obscureStrength)
        {
            if (word.Language == null)
            {
                IGlobalConfig globalConfig = ConfigDataCache.Get <IGlobalConfig>(new ConfigDataCacheKey(typeof(IGlobalConfig), "LiveSettings", ConfigDataType.GameWorld));

                word.Language = globalConfig.BaseLanguage;
            }

            IEnumerable <IDictata> possibleWords = ConfigDataCache.GetAll <IDictata>().Where(dict => dict.GetLexeme().SuitableForUse &&
                                                                                             dict.Language == word.Language &&
                                                                                             dict.WordType == word.WordType);

            return(GetObscuredWord(word, possibleWords, obscureStrength));
        }
示例#16
0
        public ActionResult EditDictata(string lexemeId, string id)
        {
            ILexeme lex = ConfigDataCache.Get<ILexeme>(new ConfigDataCacheKey(typeof(ILexeme), lexemeId, ConfigDataType.Dictionary));
            IDictata obj = lex?.WordForms?.FirstOrDefault(form => form.UniqueKey == id);

            if (obj == null)
            {
                return RedirectToAction("Index", new { Message = "That does not exist" });
            }

            AddEditDictataViewModel vModel = new AddEditDictataViewModel(lex, obj)
            {
                AuthedUser = UserManager.FindById(User.Identity.GetUserId())
            };

            return View("~/Views/GameAdmin/Dictionary/EditDictata.cshtml", vModel);
        }
示例#17
0
        /// <summary>
        /// Map the synonyms of this
        /// </summary>
        /// <param name="dictata">the word in question</param>
        /// <returns>a trigger boolean to end a loop</returns>
        public static bool GetSynSet(IDictata dictata)
        {
            try
            {
                if (dictata.WordType != LexicalType.None)
                {
                    var wordList = new List <string>();
                    CreateOrModifyLexeme(dictata.Language, dictata.Name, dictata.WordType, ref wordList);
                }
            }
            catch (Exception ex)
            {
                LoggingUtility.LogError(ex);
                //don't barf on this
            }

            return(false);
        }
示例#18
0
        /// <summary>
        /// Get a word form by criteria
        /// </summary>
        /// <param name="word">the text name of the word</param>
        /// <param name="form">the lexical type</param>
        /// <param name="semantics">the semantic meaning</param>
        /// <param name="bestFit">should we grab best fit for meaning or be more exacting</param>
        /// <returns>the word, or nothing</returns>
        public IDictata GetForm(LexicalType form, string[] semantics, bool bestFit = true)
        {
            IDictata returnValue = null;

            if (bestFit || semantics.Count() == 0)
            {
                returnValue = WordForms.Where(wordForm => wordForm.WordType == form)
                              .OrderByDescending(wordForm => semantics.Sum(sem => wordForm.Semantics.Contains(sem) ? 1 : 0))
                              .FirstOrDefault();
            }
            else
            {
                var expectedMinimumSemanticSimilarity = semantics.Count() / 2;
                returnValue = WordForms.FirstOrDefault(wordForm => wordForm.WordType == form &&
                                                       semantics.Sum(sem => wordForm.Semantics.Contains(sem) ? 1 : 0) >= expectedMinimumSemanticSimilarity);
            }

            return(returnValue);
        }
示例#19
0
        private static IDictataPhrase GetRelatedPhrase(IDictata baseWord, IEnumerable <IDictataPhrase> possibleWords, int severityModifier, int eleganceModifier, int qualityModifier)
        {
            Dictionary <IDictataPhrase, int> rankedPhrasess = new Dictionary <IDictataPhrase, int>();

            foreach (IDictataPhrase word in possibleWords)
            {
                int rating = 0;

                rating += Math.Abs(baseWord.Severity + severityModifier - word.Severity);
                rating += Math.Abs(baseWord.Elegance + eleganceModifier - word.Elegance);
                rating += Math.Abs(baseWord.Quality + qualityModifier - word.Quality);

                rankedPhrasess.Add(word, rating);
            }

            KeyValuePair <IDictataPhrase, int> closestPhrase = rankedPhrasess.OrderBy(pair => pair.Value).FirstOrDefault();

            return(closestPhrase.Key);
        }
示例#20
0
        /// <summary>
        /// Initial experience, takes in an observance and emits the new contexts related to it. Merge and Convey will merge new contexts into existing ones
        /// </summary>
        /// <param name="actor">Who did the action</param>
        /// <param name="action">The raw input that was observed</param>
        /// <returns>A list of the new contexts generated</returns>
        public IEnumerable <IDictata> Parse(IEntity actor, string action, bool push = false)
        {
            List <IDictata> returnList = new List <IDictata>();

            _currentPlace = actor.CurrentLocation.CurrentLocation();
            _actor        = actor;

            string[] spaceSplit = action.Split(new char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries);

            Dictionary <string, IDictata> brandedWords = BrandWords(spaceSplit);

            List <string> sentences = new List <string>();

            if (brandedWords.Count(bWord => bWord.Value != null && bWord.Value.WordType == LexicalType.Verb) > 1)
            {
                //multiple verbs means multiple sentences
                IEnumerable <string> punctuationSentences = IsolateSentences(action);

                foreach (string sentence in punctuationSentences)
                {
                    string[] innerSplit = sentence.Split(new char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries);

                    Dictionary <string, IDictata> innerBrands = BrandWords(innerSplit);

                    if (!innerBrands.Any(inWord => inWord.Value != null && inWord.Value.WordType == LexicalType.Conjunction))
                    {
                        sentences.Add(sentence);
                        continue;
                    }

                    bool found = false;
                    foreach ((KeyValuePair <string, IDictata> value, int i)innerVerb in innerBrands.Select((value, i) => (value, i)))
                    {
                        KeyValuePair <string, IDictata> value = innerVerb.value;
                        int index = innerVerb.i;

                        if (value.Value != null && value.Value.WordType != LexicalType.Verb)
                        {
                            continue;
                        }

                        found = true;
                        if (index > 0 && index < innerBrands.Count() - 1)
                        {
                            IDictata wordBefore = innerBrands.ElementAt(index - 1).Value;

                            if (wordBefore.WordType == LexicalType.Conjunction)
                            {
                                int splitIndex = innerBrands.Take(index - 1).Sum(brand => brand.Key.Length + 1);

                                int bumpCount = sentence.Substring(0, splitIndex - 1).Count(ch => ch == ',' || ch == ':');

                                string sentenceOne = sentence.Substring(0, splitIndex - 1 + bumpCount);
                                string sentenceTwo = sentence.Substring(splitIndex + wordBefore.Name.Length + bumpCount);

                                sentences.Add(sentenceOne);
                                sentences.Add(sentenceTwo);
                            }
                        }
                    }

                    if (!found)
                    {
                        sentences.Add(sentence);
                    }
                }
            }
            else
            {
                sentences.Add(action);
            }

            IDictata currentSubject = null;

            foreach (string sentence in sentences)
            {
                IList <Tuple <string, bool> > words = IsolateIndividuals(sentence);

                //can't parse nothing
                if (words.Count == 0)
                {
                    continue;
                }

                IEnumerable <IDictata> fullCommand = ParseAction(words, push, currentSubject);
                currentSubject = fullCommand.LastOrDefault(word => word.WordType == LexicalType.Noun || word.WordType == LexicalType.ProperNoun);

                returnList.AddRange(fullCommand);
            }

            return(returnList);
        }
示例#21
0
        /// <summary>
        /// Add language translations for this
        /// </summary>
        public void FillLanguages()
        {
            IGlobalConfig globalConfig = ConfigDataCache.Get <IGlobalConfig>(new ConfigDataCacheKey(typeof(IGlobalConfig), "LiveSettings", ConfigDataType.GameWorld));

            //Don't do this if: we have no config, translation is turned off or lacking in the azure key, the language is not a human-ui language
            //it isn't an approved language, the word is a proper noun or the language isnt the base language at all
            if (globalConfig == null || !globalConfig.TranslationActive || string.IsNullOrWhiteSpace(globalConfig.AzureTranslationKey) ||
                !Language.UIOnly || !Language.SuitableForUse || ContainedTypes().Contains(LexicalType.ProperNoun) || Language != globalConfig.BaseLanguage)
            {
                return;
            }

            IEnumerable <ILanguage> otherLanguages = ConfigDataCache.GetAll <ILanguage>().Where(lang => lang != Language && lang.SuitableForUse && lang.UIOnly);

            foreach (ILanguage language in otherLanguages)
            {
                short  formGrouping = -1;
                string newName      = string.Empty;

                Lexeme newLexeme = new Lexeme()
                {
                    Language = language
                };

                foreach (IDictata word in WordForms)
                {
                    LexicalContext context = new LexicalContext(null)
                    {
                        Language    = language,
                        Perspective = word.Perspective,
                        Tense       = word.Tense,
                        Position    = word.Positional,
                        Determinant = word.Determinant,
                        Plural      = word.Plural,
                        Possessive  = word.Possessive,
                        Elegance    = word.Elegance,
                        Quality     = word.Quality,
                        Semantics   = word.Semantics,
                        Severity    = word.Severity,
                        GenderForm  = new Gender()
                        {
                            Feminine = word.Feminine
                        }
                    };

                    IDictata translatedWord = Thesaurus.GetSynonym(word, context);

                    //no linguistic synonym
                    if (translatedWord == this)
                    {
                        string newWord = Thesaurus.GetTranslatedWord(globalConfig.AzureTranslationKey, Name, Language, language);

                        if (!string.IsNullOrWhiteSpace(newWord))
                        {
                            newName        = newWord;
                            newLexeme.Name = newName;

                            Dictata newDictata = new Dictata(newWord, formGrouping++)
                            {
                                Elegance       = word.Elegance,
                                Severity       = word.Severity,
                                Quality        = word.Quality,
                                Determinant    = word.Determinant,
                                Plural         = word.Plural,
                                Perspective    = word.Perspective,
                                Feminine       = word.Feminine,
                                Positional     = word.Positional,
                                Possessive     = word.Possessive,
                                Semantics      = word.Semantics,
                                Antonyms       = word.Antonyms,
                                Synonyms       = word.Synonyms,
                                PhraseAntonyms = word.PhraseAntonyms,
                                PhraseSynonyms = word.PhraseSynonyms,
                                Tense          = word.Tense,
                                WordType       = word.WordType
                            };

                            newDictata.Synonyms = new HashSet <IDictata>(word.Synonyms)
                            {
                                word
                            };
                            word.Synonyms = new HashSet <IDictata>(word.Synonyms)
                            {
                                newDictata
                            };
                            newLexeme.AddNewForm(newDictata);
                        }
                    }
                }

                if (newLexeme.WordForms.Count() > 0)
                {
                    newLexeme.SystemSave();
                    newLexeme.PersistToCache();
                }
            }

            SystemSave();
            PersistToCache();
        }
示例#22
0
        public ActionResult WordFight(short wordOneId, string wordOneName, short wordTwoId, string wordTwoName, WordFightViewModel vModel)
        {
            string        message      = string.Empty;
            IGlobalConfig globalConfig = ConfigDataCache.Get <IGlobalConfig>(new ConfigDataCacheKey(typeof(IGlobalConfig), "LiveSettings", ConfigDataType.GameWorld));

            ILexeme lexOne = ConfigDataCache.Get <ILexeme>(string.Format("{0}_{1}_{2}", ConfigDataType.Dictionary, globalConfig.BaseLanguage.Name, wordOneName));
            ILexeme lexTwo = ConfigDataCache.Get <ILexeme>(string.Format("{0}_{1}_{2}", ConfigDataType.Dictionary, globalConfig.BaseLanguage.Name, wordTwoName));

            if (lexOne != null && lexTwo != null)
            {
                IDictata wordOne = lexOne.GetForm(wordOneId);
                IDictata wordTwo = lexTwo.GetForm(wordTwoId);

                if (wordOne != null || wordTwo != null)
                {
                    switch (vModel.Elegance)
                    {
                    case 1:
                        wordOne.Elegance += 1;
                        wordTwo.Elegance -= 1;
                        break;

                    case 2:
                        wordOne.Elegance -= 1;
                        wordTwo.Elegance += 1;
                        break;
                    }

                    switch (vModel.Severity)
                    {
                    case 1:
                        wordOne.Severity += 1;
                        wordTwo.Severity -= 1;
                        break;

                    case 2:
                        wordOne.Severity -= 1;
                        wordTwo.Severity += 1;
                        break;
                    }
                    switch (vModel.Quality)
                    {
                    case 1:
                        wordOne.Quality += 1;
                        wordTwo.Quality -= 1;
                        break;

                    case 2:
                        wordOne.Quality -= 1;
                        wordTwo.Quality += 1;
                        break;
                    }

                    wordOne.TimesRated += 1;
                    wordTwo.TimesRated += 1;

                    lexOne.PersistToCache();
                    lexOne.SystemSave();

                    lexTwo.PersistToCache();
                    lexTwo.SystemSave();
                }
                else
                {
                    message = "Invalid data";
                }
            }
            else
            {
                message = "Invalid data";
            }

            return(RedirectToAction("WordFight", new { Message = message }));
        }
示例#23
0
        public ActionResult EditDictata(string lexemeId, string id, AddEditDictataViewModel vModel)
        {
            string message = string.Empty;
            ApplicationUser authedUser = UserManager.FindById(User.Identity.GetUserId());

            ILexeme lex = ConfigDataCache.Get<ILexeme>(new ConfigDataCacheKey(typeof(ILexeme), lexemeId, ConfigDataType.Dictionary));
            IDictata obj = lex?.WordForms?.FirstOrDefault(form => form.UniqueKey == id);

            if (obj == null)
            {
                message = "That does not exist";
                return RedirectToAction("Index", new { Message = message });
            }

            obj.Name = vModel.DataObject.Name;
            obj.Severity = vModel.DataObject.Severity;
            obj.Quality = vModel.DataObject.Quality;
            obj.Elegance = vModel.DataObject.Elegance;
            obj.Tense = vModel.DataObject.Tense;
            obj.Synonyms = vModel.DataObject.Synonyms;
            obj.Antonyms = vModel.DataObject.Antonyms;
            obj.PhraseSynonyms = vModel.DataObject.PhraseSynonyms;
            obj.PhraseAntonyms = vModel.DataObject.PhraseAntonyms;
            obj.Language = vModel.DataObject.Language;
            obj.WordType = vModel.DataObject.WordType;
            obj.Feminine = vModel.DataObject.Feminine;
            obj.Possessive = vModel.DataObject.Possessive;
            obj.Plural = vModel.DataObject.Plural;
            obj.Determinant = vModel.DataObject.Determinant;
            obj.Positional = vModel.DataObject.Positional;
            obj.Perspective = vModel.DataObject.Perspective;
            obj.Semantics = vModel.DataObject.Semantics;

            lex.AddNewForm(obj);

            if (lex.Save(authedUser.GameAccount, authedUser.GetStaffRank(User)))
            {
                foreach (IDictata syn in obj.Synonyms)
                {
                    if (!syn.Synonyms.Any(dict => dict == obj))
                    {
                        HashSet<IDictata> synonyms = syn.Synonyms;
                        synonyms.Add(obj);

                        ILexeme synLex = syn.GetLexeme();
                        syn.Synonyms = synonyms;

                        synLex.AddNewForm(syn);
                        synLex.Save(authedUser.GameAccount, authedUser.GetStaffRank(User));
                    }
                }

                foreach (IDictata ant in obj.Antonyms)
                {
                    if (!ant.Antonyms.Any(dict => dict == obj))
                    {
                        HashSet<IDictata> antonyms = ant.Antonyms;
                        antonyms.Add(obj);

                        ILexeme antLex = ant.GetLexeme();
                        ant.Antonyms = antonyms;
                        antLex.AddNewForm(ant);
                        antLex.Save(authedUser.GameAccount, authedUser.GetStaffRank(User));
                    }
                }

                foreach (IDictataPhrase syn in obj.PhraseSynonyms)
                {
                    if (!syn.Synonyms.Any(dict => dict == obj))
                    {
                        HashSet<IDictata> synonyms = syn.Synonyms;
                        synonyms.Add(obj);

                        syn.Synonyms = synonyms;
                        syn.Save(authedUser.GameAccount, authedUser.GetStaffRank(User));
                    }
                }

                foreach (IDictataPhrase ant in obj.PhraseAntonyms)
                {
                    if (!ant.Antonyms.Any(dict => dict == obj))
                    {
                        HashSet<IDictata> antonyms = ant.Antonyms;
                        antonyms.Add(obj);

                        ant.Antonyms = antonyms;
                        ant.Save(authedUser.GameAccount, authedUser.GetStaffRank(User));
                    }
                }

                LoggingUtility.LogAdminCommandUsage("*WEB* - EditDictata[" + obj.UniqueKey + "]", authedUser.GameAccount.GlobalIdentityHandle);
                message = "Edit Successful.";
            }
            else
            {
                message = "Error; Edit failed.";
            }

            return RedirectToAction("Index", new { Message = message });
        }
示例#24
0
        private static IDictata FocusFindWord(IEnumerable <IDictata> possibleWords, LexicalContext context, IDictata baseWord)
        {
            if (context.Language == null)
            {
                context.Language = baseWord.Language;
            }

            possibleWords = possibleWords.Where(word => word != null && word.Language == context.Language && word.GetLexeme().SuitableForUse);

            if (context.Severity + context.Elegance + context.Quality == 0)
            {
                List <Tuple <IDictata, int> > rankedWords = new List <Tuple <IDictata, int> >
                {
                    new Tuple <IDictata, int>(baseWord, GetSynonymRanking(baseWord, context))
                };

                rankedWords.AddRange(possibleWords.Select(word => new Tuple <IDictata, int>(word, GetSynonymRanking(word, context))));

                return(rankedWords.OrderByDescending(pair => pair.Item2).Select(pair => pair.Item1).FirstOrDefault());
            }

            return(GetRelatedWord(baseWord, possibleWords, context.Severity, context.Elegance, context.Quality));
        }
示例#25
0
        /// <summary>
        /// Unpacks this applying language rules to expand and add articles/verbs where needed
        /// </summary>
        /// <param name="overridingContext">The full lexical context</param>
        /// <returns>A long description</returns>
        public IEnumerable <ILexica> Unpack(MessagingType sensoryType, short strength, LexicalContext overridingContext = null)
        {
            if (overridingContext != null)
            {
                IGlobalConfig globalConfig = ConfigDataCache.Get <IGlobalConfig>(new ConfigDataCacheKey(typeof(IGlobalConfig), "LiveSettings", ConfigDataType.GameWorld));

                //Sentence must maintain the same language, tense and personage
                Context.Language    = overridingContext.Language ?? Context.Language ?? globalConfig.BaseLanguage;
                Context.Tense       = overridingContext.Tense;
                Context.Perspective = overridingContext.Perspective;
                Context.Elegance    = overridingContext.Elegance;
                Context.Severity    = overridingContext.Severity;
                Context.Quality     = overridingContext.Quality;
            }

            ILexica newLex = Mutate(sensoryType, strength);

            foreach (IWordRule wordRule in Context.Language.WordRules.Where(rul => rul.Matches(newLex))
                     .OrderByDescending(rul => rul.RuleSpecificity()))
            {
                if (wordRule.NeedsArticle && (!wordRule.WhenPositional || Context.Position != LexicalPosition.None) &&
                    !newLex.Modifiers.Any(mod => (mod.Type == LexicalType.Article && !wordRule.WhenPositional && mod.Context.Position == LexicalPosition.None) ||
                                          (mod.Type == LexicalType.Preposition && wordRule.WhenPositional && mod.Context.Position != LexicalPosition.None)))
                {
                    LexicalContext articleContext = Context.Clone();

                    //Make it determinant if the word is plural
                    articleContext.Determinant = Context.Plural || articleContext.Determinant;

                    IDictata article = null;
                    if (wordRule.SpecificAddition != null)
                    {
                        article = wordRule.SpecificAddition;
                    }
                    else
                    {
                        article = Thesaurus.GetWord(articleContext, wordRule.WhenPositional ? LexicalType.Preposition : LexicalType.Article);
                    }

                    if (article != null && !newLex.Modifiers.Any(lx => article.Name.Equals(lx.Phrase, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        ILexica newArticle = newLex.TryModify(wordRule.WhenPositional ? LexicalType.Preposition : LexicalType.Article
                                                              , GrammaticalType.Descriptive, article.Name, false);

                        if (!wordRule.WhenPositional)
                        {
                            newArticle.Context.Position = LexicalPosition.None;
                        }
                    }
                }
                else if (wordRule.SpecificAddition != null && !newLex.Modifiers.Any(lx => wordRule.SpecificAddition.Equals(lx.GetDictata())))
                {
                    newLex.TryModify(wordRule.SpecificAddition.WordType, GrammaticalType.Descriptive, wordRule.SpecificAddition.Name);
                }

                if (!string.IsNullOrWhiteSpace(wordRule.AddPrefix) && !newLex.Phrase.StartsWith(wordRule.AddPrefix))
                {
                    newLex.Phrase = string.Format("{0}{1}", wordRule.AddPrefix, newLex.Phrase.Trim());
                }

                if (!string.IsNullOrWhiteSpace(wordRule.AddSuffix) && !newLex.Phrase.EndsWith(wordRule.AddSuffix))
                {
                    newLex.Phrase = string.Format("{1}{0}", wordRule.AddSuffix, newLex.Phrase.Trim());
                }
            }

            //Placement ordering
            List <Tuple <ILexica, int> > modifierList = new List <Tuple <ILexica, int> >
            {
                new Tuple <ILexica, int>(newLex, 0)
            };

            //modification rules ordered by specificity
            List <ILexica> currentModifiers = new List <ILexica>(newLex.Modifiers);

            foreach (ILexica modifier in currentModifiers)
            {
                foreach (IWordPairRule wordRule in Context.Language.WordPairRules.Where(rul => rul.Matches(newLex, modifier))
                         .OrderByDescending(rul => rul.RuleSpecificity()))
                {
                    if (wordRule.NeedsArticle && (!wordRule.WhenPositional || Context.Position != LexicalPosition.None) &&
                        !newLex.Modifiers.Any(mod => (mod.Type == LexicalType.Article && !wordRule.WhenPositional && mod.Context.Position == LexicalPosition.None) ||
                                              (mod.Type == LexicalType.Preposition && wordRule.WhenPositional && mod.Context.Position != LexicalPosition.None)))
                    {
                        LexicalContext articleContext = Context.Clone();

                        //Make it determinant if the word is plural
                        articleContext.Determinant = Context.Plural || articleContext.Determinant;

                        IDictata article = null;
                        if (wordRule.SpecificAddition != null)
                        {
                            article = wordRule.SpecificAddition;
                        }
                        else
                        {
                            article = Thesaurus.GetWord(articleContext, wordRule.WhenPositional ? LexicalType.Preposition : LexicalType.Article);
                        }

                        if (article != null && !newLex.Modifiers.Any(lx => article.Name.Equals(lx.Phrase, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            ILexica newArticle = newLex.TryModify(wordRule.WhenPositional ? LexicalType.Preposition : LexicalType.Article
                                                                  , GrammaticalType.Descriptive, article.Name, false);

                            if (!wordRule.WhenPositional)
                            {
                                newArticle.Context.Position = LexicalPosition.None;
                            }
                        }
                    }
                    else if (wordRule.SpecificAddition != null && !newLex.Modifiers.Any(lx => wordRule.SpecificAddition.Equals(lx.GetDictata())))
                    {
                        newLex.TryModify(wordRule.SpecificAddition.WordType, GrammaticalType.Descriptive, wordRule.SpecificAddition.Name);
                    }


                    if (!string.IsNullOrWhiteSpace(wordRule.AddPrefix) && !newLex.Phrase.StartsWith(wordRule.AddPrefix))
                    {
                        newLex.Phrase = string.Format("{0}{1}", wordRule.AddPrefix, newLex.Phrase.Trim());
                    }

                    if (!string.IsNullOrWhiteSpace(wordRule.AddSuffix) && !newLex.Phrase.EndsWith(wordRule.AddSuffix))
                    {
                        newLex.Phrase = string.Format("{1}{0}", wordRule.AddSuffix, newLex.Phrase.Trim());
                    }
                }
            }

            foreach (ILexica modifier in newLex.Modifiers)
            {
                IWordPairRule rule = Context.Language.WordPairRules.OrderByDescending(rul => rul.RuleSpecificity())
                                     .FirstOrDefault(rul => rul.Matches(newLex, modifier));

                if (rule != null)
                {
                    int i = 0;
                    foreach (ILexica subModifier in modifier.Unpack(sensoryType, strength, overridingContext ?? Context).Distinct())
                    {
                        modifierList.Add(new Tuple <ILexica, int>(subModifier, rule.ModificationOrder + i++));
                    }
                }
            }

            return(modifierList.OrderBy(tup => tup.Item2).Select(tup => tup.Item1));
        }
示例#26
0
        public ActionResult AddRelatedWord(string lexemeId, string id, AddEditDictataViewModel vModel)
        {
            ApplicationUser authedUser = UserManager.FindById(User.Identity.GetUserId());

            ILexeme lex = ConfigDataCache.Get<ILexeme>(new ConfigDataCacheKey(typeof(ILexeme), lexemeId, ConfigDataType.Dictionary));
            if (lex == null)
            {
                return RedirectToAction("Index", new { Message = "That does not exist" });
            }

            IDictata dict = lex.WordForms.FirstOrDefault(form => form.UniqueKey == id);
            if (dict == null)
            {
                return RedirectToAction("Index", new { Message = "That does not exist" });
            }

            Lexeme relatedLex = new Lexeme
            {
                Name = vModel.Word,
                Language = lex.Language
            };

            Dictata relatedWord = new Dictata()
            {
                Name = vModel.Word,
                Severity = dict.Severity + vModel.Severity,
                Quality = dict.Quality + vModel.Quality,
                Elegance = dict.Elegance + vModel.Elegance,
                Tense = dict.Tense,
                Language = dict.Language,
                WordType = dict.WordType,
                Feminine = dict.Feminine,
                Possessive = dict.Possessive,
                Plural = dict.Plural,
                Determinant = dict.Determinant,
                Positional = dict.Positional,
                Perspective = dict.Perspective,
                Semantics = dict.Semantics
            };

            HashSet<IDictata> synonyms = dict.Synonyms;
            synonyms.Add(dict);

            if (vModel.Synonym)
            {
                relatedWord.Synonyms = synonyms;
                relatedWord.Antonyms = dict.Antonyms;
                relatedWord.PhraseSynonyms = dict.PhraseSynonyms;
                relatedWord.PhraseAntonyms = dict.PhraseAntonyms;
            }
            else
            {
                relatedWord.Synonyms = dict.Antonyms;
                relatedWord.Antonyms = synonyms;
                relatedWord.PhraseSynonyms = dict.PhraseAntonyms;
                relatedWord.PhraseAntonyms = dict.PhraseSynonyms;
            }

            relatedLex.AddNewForm(relatedWord);

            string message;
            if (relatedLex.Save(authedUser.GameAccount, authedUser.GetStaffRank(User)))
            {
                if (vModel.Synonym)
                {
                    HashSet<IDictata> mySynonyms = dict.Synonyms;
                    mySynonyms.Add(relatedWord);

                    dict.Synonyms = mySynonyms;
                }
                else
                {
                    HashSet<IDictata> antonyms = dict.Antonyms;
                    antonyms.Add(relatedWord);

                    dict.Antonyms = antonyms;
                }

                lex.Save(authedUser.GameAccount, authedUser.GetStaffRank(User));
                relatedLex.Save(authedUser.GameAccount, authedUser.GetStaffRank(User));

                LoggingUtility.LogAdminCommandUsage("*WEB* - EditLexeme[" + lex.UniqueKey + "]", authedUser.GameAccount.GlobalIdentityHandle);
                message = "Edit Successful.";
            }
            else
            {
                message = "Error; Edit failed.";
            }

            return RedirectToAction("Index", new { Message = message });
        }
示例#27
0
        /*
         * TODO: Wow this is inefficient, maybe clean up how many loops we do
         */
        private IEnumerable <IDictata> ParseAction(IList <Tuple <string, bool> > words, bool push, IDictata lastSubject)
        {
            /*
             * I kick the can
             * kick the can
             * kicks the can
             * kick the red can
             * kick the large red can
             */
            List <IDictata> returnList = new List <IDictata>();

            Dictionary <string, IDictata> brandedWords = BrandWords(words);

            IDictata currentVerb = null;

            //Find unknown nouns potentially with conjunctions
            foreach ((KeyValuePair <string, IDictata> value, int i)item in brandedWords.Where(ctx => ctx.Value == null).Select((value, i) => (value, i)).OrderByDescending(keypair => keypair.i))
            {
                KeyValuePair <string, IDictata> value = item.value;
                int index = item.i;

                if (index < brandedWords.Count() - 1 && index > 0)
                {
                    IDictata wordAfter  = brandedWords.ElementAt(index + 1).Value;
                    IDictata wordBefore = brandedWords.ElementAt(index - 1).Value;

                    if (wordBefore != null && wordBefore.WordType == LexicalType.Adverb && wordAfter != null && wordAfter.WordType == LexicalType.Verb)
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Adverb
                        };
                        continue;
                    }

                    if ((wordBefore != null && (wordBefore.WordType == LexicalType.Adjective) || wordBefore.WordType == LexicalType.Article) &&
                        (wordAfter != null && (wordAfter.WordType == LexicalType.Noun) || wordAfter.WordType == LexicalType.ProperNoun))
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Adjective
                        };
                        continue;
                    }

                    continue;
                }

                if (index < brandedWords.Count() - 1)
                {
                    IDictata wordAfter = brandedWords.ElementAt(index + 1).Value;

                    if (wordAfter != null && wordAfter.WordType == LexicalType.Noun)
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Adjective
                        };
                        continue;
                    }

                    if (wordAfter != null && wordAfter.WordType == LexicalType.Verb)
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Adverb
                        };
                        continue;
                    }
                }

                if (index > 0)
                {
                    IDictata wordBefore = brandedWords.ElementAt(index - 1).Value;

                    if (wordBefore != null && (wordBefore.WordType == LexicalType.Article || wordBefore.WordType == LexicalType.Adjective))
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Noun
                        };
                        continue;
                    }

                    if (wordBefore != null && wordBefore.WordType == LexicalType.Adverb)
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Verb
                        };
                        continue;
                    }
                }
            }

            //No verb?
            if (!brandedWords.Any(ctx => ctx.Value != null && ctx.Value.WordType == LexicalType.Verb))
            {
                string verbWord = brandedWords.First(ctx => ctx.Value == null).Key;

                currentVerb = new Dictata()
                {
                    Name = verbWord, WordType = LexicalType.Verb
                };
                brandedWords[verbWord] = currentVerb;
            }
            else
            {
                currentVerb = brandedWords.FirstOrDefault(ctx => ctx.Value != null && ctx.Value.WordType == LexicalType.Verb).Value;
            }

            //We might have nouns already
            if (!brandedWords.Any(ctx => ctx.Value == null || (ctx.Value != null &&
                                                               (ctx.Value.WordType == LexicalType.Noun || ctx.Value.WordType == LexicalType.ProperNoun))))
            {
                bool lastSubjectReplaced = false;
                if (lastSubject != null)
                {
                    List <string> keyList = new List <string>();
                    foreach (KeyValuePair <string, IDictata> word in brandedWords.Where(ctx => ctx.Value != null && ctx.Value.WordType == LexicalType.Pronoun))
                    {
                        keyList.Add(word.Key);
                        lastSubjectReplaced = true;
                    }

                    foreach (string key in keyList)
                    {
                        brandedWords[key] = (IDictata)lastSubject.Clone();
                    }
                }

                if (!lastSubjectReplaced)
                {
                    string targetWord = string.Empty;

                    //No valid nouns to make the target? Pick the last one
                    if (!brandedWords.Any(ctx => ctx.Value == null))
                    {
                        targetWord = brandedWords.LastOrDefault().Key;
                    }
                    else
                    {
                        targetWord = brandedWords.LastOrDefault(ctx => ctx.Value == null).Key;
                    }

                    brandedWords[targetWord] = new Dictata()
                    {
                        Name = targetWord, WordType = LexicalType.Noun
                    };
                }
            }

            List <IDictata> descriptors = new List <IDictata>();

            foreach ((KeyValuePair <string, IDictata> value, int i)item in brandedWords.Where(ctx => ctx.Value == null).Select((value, i) => (value, i)))
            {
                KeyValuePair <string, IDictata> value = item.value;
                int index = item.i;

                LexicalType wordType = LexicalType.Adjective;
                if (index == brandedWords.Count() - 1)
                {
                    IDictata wordAfter = brandedWords.ElementAt(index + 1).Value;

                    if (wordAfter != null)
                    {
                        if (wordAfter.WordType == LexicalType.Verb)
                        {
                            wordType = LexicalType.Adverb;
                        }

                        if (wordAfter.WordType == LexicalType.Pronoun)
                        {
                            wordType = LexicalType.Article;
                        }
                    }
                }

                descriptors.Add(new Dictata()
                {
                    Name = value.Key, WordType = wordType
                });
            }

            //Add the nonadjectives and the adjectives
            returnList.AddRange(brandedWords.Where(bws => bws.Value != null).Select(bws => bws.Value));
            returnList.AddRange(descriptors.Select(desc => desc));

            if (push)
            {
                foreach (IDictata item in returnList)
                {
                    LexicalProcessor.VerifyLexeme(item.GetLexeme());
                }
            }

            return(returnList);
        }
示例#28
0
        private static IDictataPhrase FocusFindPhrase(IEnumerable <IDictataPhrase> possiblePhrases, LexicalContext context, IDictata baseWord)
        {
            if (context.Language == null)
            {
                context.Language = baseWord.Language;
            }

            possiblePhrases = possiblePhrases.Where(phrase => phrase != null && phrase.Language == context.Language && phrase.SuitableForUse);

            if (context.Severity + context.Elegance + context.Quality == 0)
            {
                List <Tuple <IDictataPhrase, int> > rankedPhrases = new List <Tuple <IDictataPhrase, int> >();
                int baseRanking = GetSynonymRanking(baseWord, context);

                rankedPhrases.AddRange(possiblePhrases.Select(phrase => new Tuple <IDictataPhrase, int>(phrase, GetSynonymRanking(phrase, context))));

                if (baseRanking > rankedPhrases.Max(phrase => phrase.Item2))
                {
                    return(null);
                }

                return(rankedPhrases.OrderByDescending(pair => pair.Item2).Select(pair => pair.Item1).FirstOrDefault());
            }

            return(GetRelatedPhrase(baseWord, possiblePhrases, context.Severity, context.Elegance, context.Quality));
        }
示例#29
0
        /// <summary>
        /// Create a narrative description from this
        /// </summary>
        /// <param name="overridingContext">Context to override the lexica with</param>
        /// <param name="anonymize">Should we omit the proper name of the initial subject entirely (and only resort to pronouns)</param>
        /// <returns>A long description</returns>
        public IEnumerable <ILexicalSentence> Unpack(LexicalContext overridingContext = null, bool anonymize = false)
        {
            List <ILexicalSentence> sentences = new List <ILexicalSentence>();

            //short circuit empty lexica
            if (string.IsNullOrWhiteSpace(Event?.Phrase))
            {
                return(sentences);
            }

            if (overridingContext != null)
            {
                //Sentence must maintain the same language, tense and personage as well as the weight values
                Event.Context.Language    = overridingContext.Language;
                Event.Context.Tense       = overridingContext.Tense;
                Event.Context.Perspective = overridingContext.Perspective;
                Event.Context.Elegance    = overridingContext.Elegance;
                Event.Context.Severity    = overridingContext.Severity;
                Event.Context.Quality     = overridingContext.Quality;
            }

            //Language rules engine, default to base language if we have an empty language
            if (Event.Context.Language == null || (Event.Context.Language?.WordPairRules?.Count == 0 && Event.Context.Language?.WordRules?.Count == 0))
            {
                IGlobalConfig globalConfig = ConfigDataCache.Get <IGlobalConfig>(new ConfigDataCacheKey(typeof(IGlobalConfig), "LiveSettings", ConfigDataType.GameWorld));

                Event.Context.Language = globalConfig.BaseLanguage;
            }

            if (anonymize)
            {
                LexicalContext pronounContext = Event.Context.Clone();
                pronounContext.Perspective = NarrativePerspective.SecondPerson;
                pronounContext.Position    = LexicalPosition.None;
                pronounContext.Tense       = LexicalTense.None;
                pronounContext.Determinant = false;
                pronounContext.Semantics   = new HashSet <string>();

                IDictata pronoun = Thesaurus.GetWord(pronounContext, LexicalType.Pronoun);
                Event.Phrase = pronoun.Name;
                Event.Type   = LexicalType.Pronoun;
            }

            List <ILexica> subjects = new List <ILexica>
            {
                Event
            };

            subjects.AddRange(Event.Modifiers.Where(mod => mod != null && mod.Role == GrammaticalType.Subject));

            Event.Modifiers.RemoveWhere(mod => mod == null || mod.Role == GrammaticalType.Subject);

            foreach (ILexica subject in subjects)
            {
                //This is to catch directly described entities, we have to add a verb to it for it to make sense. "Complete sentence rule"
                if (subject.Modifiers.Any() && !subject.Modifiers.Any(mod => mod.Role == GrammaticalType.Verb))
                {
                    LexicalContext verbContext = subject.Context.Clone();
                    verbContext.Semantics = new HashSet <string> {
                        "existential"
                    };
                    verbContext.Determinant = false;
                    IDictata verb = Thesaurus.GetWord(verbContext, LexicalType.Verb);

                    ILexica verbLex = verb.GetLexica(GrammaticalType.Verb, verbContext);
                    verbLex.TryModify(subject.Modifiers);

                    subject.Modifiers = new HashSet <ILexica>();
                    subject.TryModify(verbLex);
                }

                if (subject.Modifiers.Any(mod => mod.Role == GrammaticalType.Subject))
                {
                    sentences.Add(subject.MakeSentence(SentenceType.Partial, SensoryType, Strength));

                    //fragment sentences
                    foreach (ILexica subLex in subject.Modifiers.Where(mod => mod.Role == GrammaticalType.Subject))
                    {
                        sentences.Add(subLex.MakeSentence(SentenceType.Statement, SensoryType, Strength));
                    }
                }
                else
                {
                    //full obfuscation happens at 100 only
                    if (Strength <= -100 || Strength >= 100)
                    {
                        ILexica lex = RunObscura(SensoryType, subject, subject.Context.Observer, Strength > 0);

                        sentences.Add(lex.MakeSentence(SentenceType.Statement, SensoryType, Strength));
                    }
                    else
                    {
                        sentences.Add(subject.MakeSentence(SentenceType.Statement, SensoryType, Strength));
                    }
                }
            }

            return(sentences);
        }
示例#30
0
        private static IDictata GetObscuredWord(IDictata word, IEnumerable <IDictata> possibleWords, short obscureStrength)
        {
            if (word == null || possibleWords.Count() == 0 || obscureStrength == 0)
            {
                return(word);
            }

            //try to downgrade word
            Dictionary <IDictata, int> rankedWords = new Dictionary <IDictata, int>();

            foreach (IDictata possibleWord in possibleWords)
            {
                int rating = Math.Abs(word.Quality + (Math.Abs(obscureStrength) * -1) - possibleWord.Quality);

                rankedWords.Add(possibleWord, rating);
            }

            KeyValuePair <IDictata, int> closestWord = rankedWords.OrderBy(pair => pair.Value).FirstOrDefault();
            IDictata newWord = closestWord.Key;

            LexicalType[] descriptiveWordTypes = new LexicalType[] { LexicalType.Adjective, LexicalType.Adverb };
            LexicalType[] remainderWordTypes   = new LexicalType[] { LexicalType.Verb, LexicalType.Preposition, LexicalType.Conjunction, LexicalType.Article };
            LexicalType[] nounWordTypes        = new LexicalType[] { LexicalType.Pronoun, LexicalType.ProperNoun, LexicalType.Noun };
            if (newWord != null)
            {
                //Adjectives/adverbs/articles get eaten
                if (descriptiveWordTypes.Contains(newWord.WordType))
                {
                    newWord = null;
                }

                //if it's a verb or preposition or structural leave it alone
                if (remainderWordTypes.Contains(newWord.WordType))
                {
                    newWord = word;
                }

                //pronouns become "it"
                if (nounWordTypes.Contains(newWord.WordType))
                {
                    LexicalContext itContext = new LexicalContext(null)
                    {
                        Determinant = false,
                        Plural      = false,
                        Possessive  = false,
                        Tense       = LexicalTense.None,
                        Language    = word.Language,
                        Perspective = NarrativePerspective.None
                    };

                    newWord = GetWord(itContext, LexicalType.Pronoun);
                }

                //TODO: if it's a noun try to downgrade it to a shape or single aspect
            }
            else
            {
                newWord = word;
            }

            return(newWord);
        }