Beispiel #1
0
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word,
                                            UserWordModel[] examList)
        {
            var variants = examList.Randomize().SelectMany(e => e.GetTranslations()).ToArray();

            var msg = $"=====>   {word.Word}    <=====\r\n" +
                      $"Choose the translation";
            await chatIo.SendMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chatIo.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(ExamResult.Retry);
            }

            if (word.GetTranslations().Contains(variants[choice.Value]))
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }

            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
Beispiel #2
0
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word,
                                            UserWordModel[] examList)
        {
            var words    = word.Word.Split(',').Select(s => s.Trim()).ToArray();
            var minCount = words.Min(t => t.Count(c => c == ' '));

            if (minCount > 0 && word.AbsoluteScore < minCount * 4)
            {
                return(ExamResult.Impossible);
            }

            await chatIo.SendMessageAsync($"=====>   {word.TranslationAsList}    <=====\r\n" +
                                          $"Write the translation... ");

            var userEntry = await chatIo.WaitUserTextInputAsync();

            if (string.IsNullOrEmpty(userEntry))
            {
                return(ExamResult.Retry);
            }

            if (words.Any(t => string.Compare(userEntry.Trim(), t, StringComparison.OrdinalIgnoreCase) == 0))
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }
            //search for other translation
            var translationCandidate = await _dictionaryService.GetAllTranslationWords(userEntry.ToLower());

            if (translationCandidate.Any(t1 =>
                                         word.GetTranslations().Any(t2 => string.CompareOrdinal(t1.Trim(), t2.Trim()) == 0)))
            {
                //translation is correct, but for other word
                await chatIo.SendMessageAsync(
                    $"the translation was correct, but the question was about the word '{word.Word} - {word.TranslationAsList}'\r\nlet's try again");

                return(ExamResult.Retry);
            }

            var translates = string.Join(",", translationCandidate);

            if (!string.IsNullOrWhiteSpace(translates))
            {
                await chatIo.SendMessageAsync($"'{userEntry}' translates as {translates}");
            }
            await chatIo.SendMessageAsync("The right translation was: " + word.Word);

            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
Beispiel #3
0
        public async Task <ExamResult> Pass(
            ChatIO chatIo,
            UsersWordsService service,
            UserWordModel word,
            UserWordModel[] examList)
        {
            if (!word.HasAnyPhrases)
            {
                return(ExamResult.Impossible);
            }

            var targetPhrase = word.GetRandomExample();

            var otherExamples = examList
                                .SelectMany(e => e.Phrases)
                                .Where(p => p != targetPhrase)
                                .Take(8).ToArray();

            if (!otherExamples.Any())
            {
                return(ExamResult.Impossible);
            }

            var variants = otherExamples
                           .Append(targetPhrase)
                           .Randomize()
                           .Select(e => e.TranslatedPhrase)
                           .ToArray();

            var msg = $"=====>   {targetPhrase.OriginPhrase}    <=====\r\n" +
                      $"Choose the translation";
            await chatIo.SendMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chatIo.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(ExamResult.Retry);
            }

            if (variants[choice.Value] == targetPhrase.TranslatedPhrase)
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }
            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
Beispiel #4
0
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word, UserWordModel[] examList)
        {
            if (!word.Phrases.Any())
            {
                return(ExamResult.Impossible);
            }

            var phrase = word.GetRandomExample();

            var replaced = phrase.OriginPhrase.Replace(phrase.OriginWord, "...");

            if (replaced == phrase.OriginPhrase)
            {
                return(ExamResult.Impossible);
            }

            var sb = new StringBuilder();

            sb.AppendLine($"\"{phrase.TranslatedPhrase}\"");
            sb.AppendLine();
            sb.AppendLine($" translated as ");
            sb.AppendLine();
            sb.AppendLine($"\"{replaced}\"");
            sb.AppendLine($"Choose missing word...");

            var variants = examList.Randomize().Select(e => e.Word).ToArray();
            var _        = chatIo.SendMessageAsync(sb.ToString(), InlineButtons.CreateVariants(variants));

            var choice = await chatIo.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(ExamResult.Retry);
            }

            if (variants[choice.Value] == word.Word)
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }

            await chatIo.SendMessageAsync($"Origin was: \"{phrase.OriginPhrase}\"");

            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word,
                                            UserWordModel[] examList)
        {
            if (!word.Phrases.Any())
            {
                return(ExamResult.Impossible);
            }

            var phrase = word.GetRandomExample();

            var replaced = phrase.TranslatedPhrase.Replace(phrase.TranslatedWord, "...");

            if (replaced == phrase.TranslatedPhrase)
            {
                return(ExamResult.Impossible);
            }

            var sb = new StringBuilder();

            sb.AppendLine($"\"{phrase.OriginPhrase}\"");
            sb.AppendLine($" translated as ");
            sb.AppendLine($"\"{replaced}\"");
            sb.AppendLine();
            sb.AppendLine($"Enter missing word: ");
            await chatIo.SendMessageAsync(sb.ToString());

            while (true)
            {
                var enter = await chatIo.WaitUserTextInputAsync();

                if (string.IsNullOrWhiteSpace(enter))
                {
                    continue;
                }
                if (string.Compare(phrase.OriginWord, enter.Trim(), StringComparison.OrdinalIgnoreCase) == 0)
                {
                    await service.RegisterSuccess(word);

                    return(ExamResult.Passed);
                }

                await chatIo.SendMessageAsync($"Origin phrase was \"{phrase.TranslatedPhrase}\"");

                await service.RegisterFailure(word);

                return(ExamResult.Failed);
            }
        }
Beispiel #6
0
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word,
                                            UserWordModel[] examList)
        {
            var translations = word.GetTranslations().ToArray();

            var minCount = translations.Min(t => t.Count(c => c == ' '));

            if (minCount > 0 && word.AbsoluteScore < minCount * 4)
            {
                return(ExamResult.Impossible);
            }

            await chatIo.SendMessageAsync($"=====>   {word.Word}    <=====\r\n" +
                                          $"Write the translation... ");

            var translation = await chatIo.WaitUserTextInputAsync();

            if (string.IsNullOrEmpty(translation))
            {
                return(ExamResult.Retry);
            }

            if (translations.Any(t => string.Compare(translation.Trim(), t, StringComparison.OrdinalIgnoreCase) == 0))
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }

            var allMeaningsOfWord = await _dictionaryService.GetAllTranslationWords(word.Word);

            if (allMeaningsOfWord
                .Any(t => string.Compare(translation, t, StringComparison.OrdinalIgnoreCase) == 0))
            {
                await chatIo.SendMessageAsync(
                    $"Chosen translation is out of scope (but it is correct). Expected translations are: " +
                    word.TranslationAsList);

                return(ExamResult.Impossible);
            }

            await chatIo.SendMessageAsync("The translation was: " + word.TranslationAsList);

            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word, UserWordModel[] examList)
        {
            if (!word.HasAnyPhrases)
            {
                return(ExamResult.Impossible);
            }

            var targetPhrase = word.GetRandomExample();

            string shuffled;

            while (true)
            {
                var wordsInExample = targetPhrase.OriginWords;

                if (wordsInExample.Length < 2)
                {
                    return(ExamResult.Impossible);
                }

                shuffled = string.Join(" ", wordsInExample.Randomize());
                if (shuffled != targetPhrase.OriginPhrase)
                {
                    break;
                }
            }

            await chatIo.SendMessageAsync("Words in phrase are shuffled. Write them in correct order:\r\n'" + shuffled + "'");

            var entry = await chatIo.WaitUserTextInputAsync();

            entry = entry.Trim();

            if (string.Compare(targetPhrase.OriginPhrase, entry.Trim(), StringComparison.OrdinalIgnoreCase) == 0)
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }

            await chatIo.SendMessageAsync($"Original phrase was: '{targetPhrase.OriginPhrase}'");

            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
Beispiel #8
0
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word,
                                            UserWordModel[] examList)
        {
            var msg = $"=====>   {word.Word}    <=====\r\n" +
                      $"Do you know the translation?";
            var _ = chatIo.SendMessageAsync(msg,
                                            new InlineKeyboardButton()
            {
                CallbackData = "1",
                Text         = "See the translation"
            });
            await chatIo.WaitInlineIntKeyboardInput();

            _ = chatIo.SendMessageAsync($"Translation is \r\n" +
                                        $"{word.TranslationAsList}\r\n" +
                                        $" Did you guess?",

                                        new InlineKeyboardButton
            {
                CallbackData = "1",
                Text         = "Yes"
            },
                                        new InlineKeyboardButton
            {
                CallbackData = "0",
                Text         = "No"
            });

            var choice = await chatIo.WaitInlineIntKeyboardInput();

            if (choice == 1)
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }
            else
            {
                await service.RegisterFailure(word);

                return(ExamResult.Failed);
            }
        }
        public async Task<ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word, UserWordModel[] examList)
        {
            if (!word.Phrases.Any())
                return ExamResult.Impossible;
            
            var targetPhrase = word.GetRandomExample();

            var other = examList.SelectMany(e => e.Phrases)
                .Where(p => !string.IsNullOrWhiteSpace(p?.OriginPhrase) && p!= targetPhrase)
                .Take(8).ToArray();

            if(!other.Any())
                return ExamResult.Impossible;

            var variants = other
                .Append(targetPhrase)
                .Randomize()
                .Select(e => e.OriginPhrase)
                .ToArray();
            
            var msg = $"=====>   {targetPhrase.TranslatedPhrase}    <=====\r\n" +
                      $"Choose the translation";
            await chatIo.SendMessageAsync(msg,
                variants.Select((v, i) => new InlineKeyboardButton
                {
                    CallbackData = i.ToString(),
                    Text = v
                }).ToArray());
            
            var choice = await chatIo.TryWaitInlineIntKeyboardInput();
            if (choice == null)
                return ExamResult.Retry;
            
            if (variants[choice.Value] == targetPhrase.OriginPhrase)
            {
                await service.RegisterSuccess(word);
                return ExamResult.Passed;
            }
            await service.RegisterFailure(word);
            return ExamResult.Failed;
        }
Beispiel #10
0
        public async Task EnterAsync()
        {
            if (!await _usersWordsService.HasWordsFor(Chat.User))
            {
                await Chat.SendMessageAsync(Chat.Texts.NeedToAddMoreWordsBeforeLearning);

                return;
            }

            var startupScoreUpdate = _usersWordsService.UpdateCurrentScoreForRandomWords(Chat.User, _examSettings.MaxLearningWordsCountInOneExam * 2);
            var typing             = Chat.SendTyping();

            var c = Rand.RandomIn(_examSettings.MinLearningWordsCountInOneExam,
                                  _examSettings.MaxLearningWordsCountInOneExam);
            await startupScoreUpdate;
            await typing;
            var   learningWords
                = await _usersWordsService.GetWordsForLearningWithPhrasesAsync(Chat.User, c, 3);

            var learningWordsCount = learningWords.Length;

            if (learningWords.Average(w => w.AbsoluteScore) <= WordLeaningGlobalSettings.FamiliarWordMinScore)
            {
                var sb = new StringBuilder($"{Emojis.Learning} " + Chat.Texts.LearningCarefullyStudyTheListMarkdown + "\r\n\r\n```\r\n");

                foreach (var pairModel in learningWords.Shuffle())
                {
                    sb.AppendLine($"{pairModel.Word.EscapeForMarkdown()}\t\t:{pairModel.AllTranslationsAsSingleString.EscapeForMarkdown()}");
                }
                sb.AppendLine($"\r\n```\r\n\\.\\.\\. {Chat.Texts.thenClickStartMarkdown}");
                await Chat.SendMarkdownMessageAsync(sb.ToString(), new[] { new[] { new InlineKeyboardButton
                                                                                   {
                                                                                       CallbackData = "/startExamination",
                                                                                       Text         = Chat.Texts.StartButton
                                                                                   }, new InlineKeyboardButton
                                                                                   {
                                                                                       CallbackData = BotCommands.Start,
                                                                                       Text         = Chat.Texts.CancelButton,
                                                                                   } } });

                var userInput = await Chat.WaitInlineKeyboardInput();

                if (userInput != "/startExamination")
                {
                    return;
                }
            }
            var started = DateTime.Now;

            var learningAndAdvancedWords
                = (await _usersWordsService.AppendAdvancedWordsToExamList(
                       Chat.User, learningWords, _examSettings));

            var distinctLearningWords = learningAndAdvancedWords.Distinct().ToArray();

            var originWordsScore = new Dictionary <string, double>();

            foreach (var word in distinctLearningWords)
            {
                if (!originWordsScore.ContainsKey(word.Word))
                {
                    originWordsScore.Add(word.Word, word.AbsoluteScore);
                }
            }

            var gamingScoreBefore = Chat.User.GamingScore;

            var            questionsCount     = 0;
            var            questionsPassed    = 0;
            var            wordQuestionNumber = 0;
            QuestionResult lastExamResult     = null;

            foreach (var word in learningAndAdvancedWords)
            {
                var allLearningWordsWereShowedAtLeastOneTime = wordQuestionNumber < learningWordsCount;
                var question =
                    QuestionSelector.Singletone.GetNextQuestionFor(allLearningWordsWereShowedAtLeastOneTime, word);
                wordQuestionNumber++;

                var learnList = learningWords;

                if (!learningWords.Contains(word))
                {
                    learnList = learningWords.Append(word).ToArray();
                }

                if (wordQuestionNumber > 1 && question.NeedClearScreen)
                {
                    await WriteDontPeakMessage(lastExamResult?.ResultsBeforeHideousText);
                }

                Chat.User.OnAnyActivity();
                var originRate = word.Score;

                var questionMetric = new QuestionMetric(word, question.Name);
                var result         = await PassWithRetries(question, word, learnList, wordQuestionNumber);

                switch (result.Results)
                {
                case ExamResult.Passed:
                    var succTask = _usersWordsService.RegisterSuccess(word);
                    questionsCount++;
                    questionsPassed++;
                    questionMetric.OnExamFinished(word.Score, true);
                    Botlog.SaveQuestionMetricInfo(questionMetric, Chat.ChatId);
                    await succTask;
                    Chat.User.OnQuestionPassed(word.Score - originRate);
                    break;

                case ExamResult.Failed:
                    var failureTask = _usersWordsService.RegisterFailure(word);
                    questionMetric.OnExamFinished(word.Score, false);
                    Botlog.SaveQuestionMetricInfo(questionMetric, Chat.ChatId);
                    questionsCount++;
                    await failureTask;
                    Chat.User.OnQuestionFailed(word.Score - originRate);
                    break;

                case ExamResult.Retry:
                case ExamResult.Impossible:
                    throw new NotSupportedException(result.Results.ToString());
                }

                if (!string.IsNullOrWhiteSpace(result.OpenResultsText))
                {
                    await Chat.SendMarkdownMessageAsync(result.OpenResultsText);
                }

                lastExamResult = result;

                Botlog.RegisterExamInfo(Chat.User.TelegramId, started, questionsCount, questionsPassed);
            }

            Chat.User.OnLearningDone();
            var updateUserTask           = _userService.Update(Chat.User);
            var finializeScoreUpdateTask = _usersWordsService.UpdateCurrentScoreForRandomWords(Chat.User, 10);

            //info after examination
            await SendExamResultToUser(
                distinctLearningWords : distinctLearningWords,
                originWordsScore : originWordsScore,
                questionsPassed : questionsPassed,
                questionsCount : questionsCount,
                learningWords : learningWords,
                gamingScoreBefore : gamingScoreBefore);

            await updateUserTask;
            await finializeScoreUpdateTask;
        }