Example #1
0
    public void NextQuestion()
    {
        _currentCorrectAnswersCount = 0;
        _currentQuestionTeamsPlayedIndeces.Clear();
        _currentTeamIndex = -1;

        _currentTeamIndex = GetNextTeamIndex(_currentQuestionTeamsPlayedIndeces, _currentTeamIndex);

        if (_currentTeamIndex != -1)
        {
            ++_currentQuestionIndex;

            if (_currentQuestionIndex < _questions.Length)
            {
                // Set question
                _view.SetAnswers(CurrentQuestion.Question, CurrentQuestion.GetTimeRewards(), CurrentQuestion.GetAnswers());

                _view.SetActiveTeam(_currentTeamIndex, false);

                _onWaitingForTimerStart();
            }
            else
            {
                GameManager.NextRound();
            }
        }
        else
        {
            GameManager.NextRound();
        }
    }
Example #2
0
        private async Task StartGame()
        {
            while (!ShouldStopGame)
            {
                // reset the cancellation source
                triviaCancelSource = new CancellationTokenSource();
                var token = triviaCancelSource.Token;
                // load question
                CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(oldQuestions);
                if (CurrentQuestion == null)
                {
                    await channel.SendMessage($":exclamation: Failed loading a trivia question").ConfigureAwait(false);
                    await End().ConfigureAwait(false);

                    return;
                }
                oldQuestions.Add(CurrentQuestion); //add it to exclusion list so it doesn't show up again
                                                   //sendquestion
                await channel.SendMessage($":question: **{CurrentQuestion.Question}**").ConfigureAwait(false);

                //receive messages
                WizBot.Client.MessageReceived += PotentialGuess;

                //allow people to guess
                GameActive = true;

                try
                {
                    //hint
                    await Task.Delay(HintTimeoutMiliseconds, token).ConfigureAwait(false);

                    if (ShowHints)
                    {
                        await channel.SendMessage($":exclamation:**Hint:** {CurrentQuestion.GetHint()}").ConfigureAwait(false);
                    }

                    //timeout
                    await Task.Delay(QuestionDurationMiliseconds - HintTimeoutMiliseconds, token).ConfigureAwait(false);
                }
                catch (TaskCanceledException)
                {
                    Console.WriteLine("Trivia cancelled");
                }
                GameActive = false;
                if (!triviaCancelSource.IsCancellationRequested)
                {
                    await channel.Send($":clock2: :question: **Time's up!** The correct answer was **{CurrentQuestion.Answer}**").ConfigureAwait(false);
                }
                WizBot.Client.MessageReceived -= PotentialGuess;
                // load next question if game is still running
                await Task.Delay(2000).ConfigureAwait(false);
            }
            await End().ConfigureAwait(false);
        }
Example #3
0
 // Method
 public void ScoreCurrentQuestion()
 {
     if (!CurrentQuestion.Scored)
     {
         if (CurrentQuestion.IsCorrect())
         {
             Score += CurrentQuestion.Points;
         }
     }
     CurrentQuestion.Scored = true;
 }
Example #4
0
    public void CorrectAnswer(int answerIndex)
    {
        // Show answer
        _view.ShowAnswer(answerIndex, CurrentQuestion.GetAnswerWordIndeces(answerIndex), true);

        CurrentTeam.Time += CurrentQuestion.Answers[answerIndex].TimeReward;

        if (++_currentCorrectAnswersCount == CurrentQuestion.Answers.Length)
        {
            CurrentTeam.Time = Mathf.CeilToInt(CurrentTeam.Time);
            EndQuestion();
        }
    }
Example #5
0
        private async void PotentialGuess(object sender, MessageEventArgs e)
        {
            try
            {
                if (e.Channel.IsPrivate)
                {
                    return;
                }
                if (e.Server != server)
                {
                    return;
                }
                if (e.User.Id == WizBot.Client.CurrentUser.Id)
                {
                    return;
                }

                var guess = false;
                await _guessLock.WaitAsync().ConfigureAwait(false);

                try
                {
                    if (GameActive && CurrentQuestion.IsAnswerCorrect(e.Message.Text) && !triviaCancelSource.IsCancellationRequested)
                    {
                        Users.TryAdd(e.User, 0); //add if not exists
                        Users[e.User]++;         //add 1 point to the winner
                        guess = true;
                    }
                }
                finally { _guessLock.Release(); }
                if (!guess)
                {
                    return;
                }
                triviaCancelSource.Cancel();
                await channel.SendMessage($"☑️ {e.User.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**").ConfigureAwait(false);

                if (Users[e.User] != WinRequirement)
                {
                    return;
                }
                ShouldStopGame = true;
                await channel.Send($":exclamation: We have a winner! It's {e.User.Mention}.").ConfigureAwait(false);

                // add points to the winner
                await FlowersHandler.AddFlowersAsync(e.User, "Won Trivia", 2).ConfigureAwait(false);
            }
            catch { }
        }
Example #6
0
        private async Task StartGame()
        {
            while (!ShouldStopGame)
            {
                // reset the cancellation source
                triviaCancelSource = new CancellationTokenSource();
                var token = triviaCancelSource.Token;
                // load question
                CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(oldQuestions);
                if (CurrentQuestion == null)
                {
                    try { await channel.SendErrorAsync($":exclamation: Failed loading a trivia question.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
                    await End().ConfigureAwait(false);

                    return;
                }
                oldQuestions.Add(CurrentQuestion); //add it to exclusion list so it doesn't show up again
                                                   //sendquestion
                try { await channel.SendConfirmAsync($":question: Question", $"**{CurrentQuestion.Question}**").ConfigureAwait(false); }
                catch (HttpException ex) when(ex.StatusCode == System.Net.HttpStatusCode.NotFound || ex.StatusCode == System.Net.HttpStatusCode.Forbidden)
                {
                    break;
                }
                catch (Exception ex) { _log.Warn(ex); }

                //receive messages
                NadekoBot.Client.MessageReceived += PotentialGuess;

                //allow people to guess
                GameActive = true;

                try
                {
                    //hint
                    await Task.Delay(HintTimeoutMiliseconds, token).ConfigureAwait(false);

                    if (ShowHints)
                    {
                        try { await channel.SendConfirmAsync($":exclamation: Hint", CurrentQuestion.GetHint()).ConfigureAwait(false); }
                        catch (HttpException ex) when(ex.StatusCode == System.Net.HttpStatusCode.NotFound || ex.StatusCode == System.Net.HttpStatusCode.Forbidden)
                        {
                            break;
                        }
                    }
                    catch (Exception ex) { _log.Warn(ex); }

                    //timeout
                    await Task.Delay(QuestionDurationMiliseconds - HintTimeoutMiliseconds, token).ConfigureAwait(false);
                }
Example #7
0
    public void NextQuestion()
    {
        ++_currentQuestionIndex;

        if (_currentQuestionIndex < _questions.Length)
        {
            Debug.LogFormat("[ThreeSixNine] Next question\n{0}", CurrentQuestion.ToString());
            _view.SetQuestion(_currentQuestionIndex, CurrentQuestion.Question, CurrentQuestion.PlayerQuestion, CurrentQuestion.Answer);
        }
        else
        {
            Debug.LogFormat("[ThreeSixNine] Next round");
            GameManager.NextRound();
        }
    }
Example #8
0
    public void CorrectAnswer(int answerIndex)
    {
        int timeReward = CurrentQuestion.GetNextTimeReward();

        CurrentTeam.Time += timeReward;

        // show answer
        _view.ShowAnswer(answerIndex, timeReward, true);

        ++_currentCorrectAnswersCount;

        if (_currentCorrectAnswersCount >= CurrentQuestion.Answers.Length)
        {
            EndQuestion();
        }
    }
Example #9
0
        private async Task StartGame()
        {
            while (!ShouldStopGame)
            {
                //reset the cancellation source
                TriviaCancelSource = new CancellationTokenSource();
                var token = TriviaCancelSource.Token;
                //load question
                CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(OldQuestions);
                if (CurrentQuestion == null)
                {
                    await Channel.SendMessage("null").ConfigureAwait(false);
                    await End().ConfigureAwait(false);

                    return;
                }
                //add current question to the exclusion list
                OldQuestions.Add(CurrentQuestion);
                await Channel.SendMessage(CurrentQuestion.ToString());

                //add PotentialGuess to OnMessageReceived
                Client.OnMessageRecieved += PotentialGuess;
                //allow people to guess
                GameActive = true;

                try
                {
                    //hint
                    await Task.Delay(HintTimeoutMilliseconds, token).ConfigureAwait(false);

                    if (ShowHints)
                    {
                        await Channel.SendMessage("hint");
                    }
                    await
                    Task.Delay(QuestionDurationMilliseconds - HintTimeoutMilliseconds, token).ConfigureAwait(false);
                }
                catch (TaskCanceledException) { }
                GameActive = false;
                if (!TriviaCancelSource.IsCancellationRequested)
                {
                    await Channel.SendMessage("correct answer was : asdf").ConfigureAwait(false);
                }
            }
        }
Example #10
0
        public bool SubmitAnswer(string PlayerAnswer)
        {
            if (IsComplete)
            {
                // TODO: What do we want to do here? Exception?
                return(false);
            }

            bool Correct = CurrentQuestion.IsCorrect(PlayerAnswer);

            if (Correct)
            {
                _numberCorrect++;
            }

            _currentQuestionIndex++;
            RaiseNewQuestion();
            return(Correct);
        }
Example #11
0
        private async void PotentialGuess(object sender, MessageEventArgs e)
        {
            try {
                if (e.Channel.IsPrivate)
                {
                    return;
                }
                if (e.Server != _server)
                {
                    return;
                }

                bool guess = false;
                lock (_guessLock) {
                    if (GameActive && CurrentQuestion.IsAnswerCorrect(e.Message.Text) && !triviaCancelSource.IsCancellationRequested)
                    {
                        users.TryAdd(e.User, 0); //add if not exists
                        users[e.User]++;         //add 1 point to the winner
                        guess = true;
                    }
                }
                if (guess)
                {
                    triviaCancelSource.Cancel();
                    await _channel.SendMessage($"☑️ {e.User.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**");

                    if (users[e.User] == WinRequirement)
                    {
                        ShouldStopGame = true;
                        await _channel.Send($":exclamation: We have a winner! Its {e.User.Mention}.");

                        // add points to the winner
                        await FlowersHandler.AddFlowersAsync(e.User, "Won Trivia", 2);
                    }
                }
            }
            catch { }
        }
        public async Task AskQuestion(SocketCommandContext context)
        {
            CurrentQuestion = Questions.Dequeue();
            await context.Channel.SendMessageAsync(CurrentQuestion.ToString());

            AcceptingAnswers = true;
            await Task.Delay(20 * 1000);

            await context.Channel.SendMessageAsync("10 seconds remain!");

            await Task.Delay(10 * 1000);

            AcceptingAnswers = false;

            var sb = new StringBuilder();
            //foreach (var result in CurrentQuestion)
            //{
            //    Players[result]++;
            //    sb.AppendLine(result);
            //}

            await context.Channel.SendMessageAsync($"Round over!\n These players answered correctly:\n {sb}");
        }
Example #13
0
        private async void PotentialGuess(object sender, MessageEventArgs e)
        {
            try
            {
                var guess = false;
                await _guessLock.WaitAsync().ConfigureAwait(false);

                try
                {
                    if (GameActive && CurrentQuestion.IsAnswerCorrect(e.Message.Text) &&
                        !TriviaCancelSource.IsCancellationRequested)
                    {
                        Users.TryAdd(e.User, 0);
                        Users[e.User]++;
                        guess = true;
                    }
                }
                finally
                {
                    _guessLock.Release();
                }

                if (!guess)
                {
                    return;
                }
                TriviaCancelSource.Cancel();
                await Channel.SendMessage("correct answer guessed").ConfigureAwait(false);

                if (Users[e.User] != WinRequirement)
                {
                    return;
                }
                ShouldStopGame = true;
                await Channel.SendMessage("winner winner chicken dinner");
            } catch { }
        }
Example #14
0
    public void NextQuestion()
    {
        _currentCorrectAnswersCount = 0;
        _currentQuestionTeamsPlayedIndeces.Clear();

        _currentQuestionTeamIndex = GetNextTeamIndex(_roundTeamsPlayedIndeces, _currentQuestionTeamIndex);

        if (_currentQuestionTeamIndex != -1)
        {
            ++_currentQuestionIndex;

            _currentTeamIndex = _currentQuestionTeamIndex;

            // Show question
            _view.SetAnswers(CurrentQuestion.GetTimeRewards(), CurrentQuestion.GetAnswers());
            _view.SetPuzzleWords(CurrentQuestion.GetWords());

            StartTimer();
        }
        else
        {
            GameManager.NextRound();
        }
    }
Example #15
0
 public TaskDetailsWindowViewModel(StudentEducationTask task, IEducationTasksManager tasksManager, IEducationTaskExaminationManager examination)
 {
     Theme           = task.Material.Theme;
     _random         = new Random();
     Questions       = new ObservableCollection <QuestionSelectorViewModel>(task.Questions.Select(i => new QuestionSelectorViewModel(i, _random)));
     CurrentQuestion = Questions.First();
     _prev           = new DelegateCommand(() => {
         var index = Questions.IndexOf(CurrentQuestion);
         if (index > 0)
         {
             CurrentQuestion.Check();
             CurrentQuestion       = Questions[--index];
             CurrentQuestionNumber = ++index;
         }
     }, () => CurrentQuestionNumber - 1 > 0);
     _next = new DelegateCommand(() => {
         var index = Questions.IndexOf(CurrentQuestion);
         if (index < Questions.Count - 1)
         {
             CurrentQuestion.Check();
             CurrentQuestion       = Questions[++index];
             CurrentQuestionNumber = ++index;
         }
     }, () => CurrentQuestionNumber - 1 < Questions.Count - 1);
     Finish = new DelegateCommand(() => {
         var result = examination.Examine(task, Questions.Select(i => new KeyValuePair <TaskQuestion, string>(task.Questions.FirstOrDefault(j => j.Question.Trim() == i.Question.Trim()), i.CurrentAnswer)));
         tasksManager.Insert(result);
         if (ViewService.GetIfOpened(out var view, this))
         {
             view.Close();
             ViewService.Message($"Ваша оценка {result.Solution.Mark}");
         }
     });
     SelectAnswer          = new DelegateCommand <string>((param) => CurrentQuestion.CurrentAnswer = param);
     CurrentQuestionNumber = 1;
 }
Example #16
0
        public async Task StartGame()
        {
            while (!ShouldStopGame)
            {
                // reset the cancellation source
                _triviaCancelSource = new CancellationTokenSource();

                // load question
                CurrentQuestion = _questionPool.GetRandomQuestion(OldQuestions, _options.IsPokemon);
                if (string.IsNullOrWhiteSpace(CurrentQuestion?.Answer) || string.IsNullOrWhiteSpace(CurrentQuestion.Question))
                {
                    await Channel.SendErrorAsync(GetText("trivia_game"), GetText("failed_loading_question")).ConfigureAwait(false);

                    return;
                }
                OldQuestions.Add(CurrentQuestion); //add it to exclusion list so it doesn't show up again

                EmbedBuilder questionEmbed;
                IUserMessage questionMessage;
                try
                {
                    questionEmbed = new EmbedBuilder().WithOkColor()
                                    .WithTitle(GetText("trivia_game"))
                                    .AddField(eab => eab.WithName(GetText("category")).WithValue(CurrentQuestion.Category))
                                    .AddField(eab => eab.WithName(GetText("question")).WithValue(CurrentQuestion.Question));
                    if (Uri.IsWellFormedUriString(CurrentQuestion.ImageUrl, UriKind.Absolute))
                    {
                        questionEmbed.WithImageUrl(CurrentQuestion.ImageUrl);
                    }

                    questionMessage = await Channel.EmbedAsync(questionEmbed).ConfigureAwait(false);
                }
                catch (HttpException ex) when(ex.HttpCode == System.Net.HttpStatusCode.NotFound ||
                                              ex.HttpCode == System.Net.HttpStatusCode.Forbidden ||
                                              ex.HttpCode == System.Net.HttpStatusCode.BadRequest)
                {
                    return;
                }
                catch (Exception ex)
                {
                    _log.Warn(ex);
                    await Task.Delay(2000).ConfigureAwait(false);

                    continue;
                }

                //receive messages
                try
                {
                    _client.MessageReceived += PotentialGuess;

                    //allow people to guess
                    GameActive = true;
                    try
                    {
                        //hint
                        await Task.Delay(_options.QuestionTimer * 1000 / 2, _triviaCancelSource.Token).ConfigureAwait(false);

                        if (!_options.NoHint)
                        {
                            try
                            {
                                await questionMessage.ModifyAsync(m => m.Embed = questionEmbed.WithFooter(efb => efb.WithText(CurrentQuestion.GetHint())).Build())
                                .ConfigureAwait(false);
                            }
                            catch (HttpException ex) when(ex.HttpCode == System.Net.HttpStatusCode.NotFound || ex.HttpCode == System.Net.HttpStatusCode.Forbidden)
                            {
                                break;
                            }
                        }
                        catch (Exception ex) { _log.Warn(ex); }

                        //timeout
                        await Task.Delay(_options.QuestionTimer * 1000 / 2, _triviaCancelSource.Token).ConfigureAwait(false);
                    }
                    catch (TaskCanceledException) { _timeoutCount = 0; } //means someone guessed the answer
                }
        public List <_TwilioMSGViewModel> GetAllMessages()
        {
            // Twilio request of list of messages
            TwilioRestClient   client  = new TwilioRestClient(AuthTwilio.ACCOUNT_SID, AuthTwilio.AUTH_TOKEN);
            MessageListRequest request = new MessageListRequest();
            DateTime           today   = DateTime.Now;

            request.DateSent = today;
            var messages = client.ListMessages(request);
            List <_TwilioMSGViewModel> msg;

            msg = messages.Messages.Select(s => new _TwilioMSGViewModel()
            {
                Body     = s.Body,
                From     = s.From,
                To       = s.To,
                Sid      = s.Sid,
                DateSent = s.DateSent
            }).ToList();

            // Takes Msg looks into Active Campaigns for Keyword, assigns SurveyClient to Campaign
            List <string> TwilioSid = msg.Select(t => t.Sid).ToList();
            List <_TwilioMSGViewModel> newMessages;
            List <_TwilioMSGViewModel> newSurveyClient;

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                List <TwilioMSG> previousMessages = db.TwilioMSGs.Where(m => TwilioSid.Contains(m.TwiilioMSGSid)).ToList();
                newMessages = msg.Where(m => !previousMessages.Any(m2 => m2.TwiilioMSGSid == m.Sid)).ToList();
                if (newMessages.Count != 0)
                {
                    using (ApplicationDbContext context = new ApplicationDbContext())
                    {
                        foreach (_TwilioMSGViewModel element in newMessages)
                        {
                            TwilioMSG dbModel = context.TwilioMSGs.Create();
                            dbModel.TwilioMSGBody = element.Body;
                            dbModel.TwilioMSGFrom = element.From;
                            dbModel.TwilioMSGTo   = element.To;
                            dbModel.TwiilioMSGSid = element.Sid;
                            dbModel.TwilioMSGDate = element.DateSent;
                            context.TwilioMSGs.Add(dbModel);
                        }
                        context.SaveChanges();
                    }
                    List <Campaign>            activeCampaings = db.Campaigns.Where(c => c.CampaignActive == true).ToList();
                    List <string>              activeKeywords  = activeCampaings.Select(k => k.CampaignKeyword).ToList();
                    List <_TwilioMSGViewModel> MsgWithKeywords = newMessages.Where(c => activeKeywords.Contains(c.Body)).ToList();
                    if (MsgWithKeywords.Count != 0)
                    {
                        List <string>       activePhoneNumbers    = db.SurveyClients.Select(p => p.SurveyClientPhone).ToList();
                        List <SurveyClient> previousSurveyClients = db.SurveyClients.Where(s => activePhoneNumbers.Contains(s.SurveyClientPhone)).ToList();
                        newSurveyClient = MsgWithKeywords.Where(q => !previousSurveyClients.Any(q2 => q2.SurveyClientPhone == q.From)).ToList();
                        if (newSurveyClient.Count != 0)
                        {
                            foreach (_TwilioMSGViewModel SClient in newSurveyClient)
                            {
                                using (ApplicationDbContext context = new ApplicationDbContext())
                                {
                                    SurveyClient dbClient = context.SurveyClients.Create();
                                    dbClient.SurveyClientPhone = SClient.From;
                                    context.SurveyClients.Add(dbClient);
                                    context.SaveChanges();
                                }
                                using (ApplicationDbContext context = new ApplicationDbContext())
                                {
                                    SurveyClientControl SCdb = context.SurveyClientControls.Create();
                                    SCdb.SurveyClientId        = context.SurveyClients.Where(x => x.SurveyClientPhone == SClient.From).FirstOrDefault().SurveyClientId;
                                    SCdb.SurveyClientControlId = context.SurveyClients.Where(x => x.SurveyClientPhone == SClient.From).FirstOrDefault().SurveyClientId;
                                    SCdb.SurveyClientPhone     = SClient.From;
                                    SCdb.CampaignId            = context.Campaigns.Where(y => y.CampaignKeyword == SClient.Body).FirstOrDefault().CampaignId;
                                    SCdb.Questions             = context.Questions.Where(q => q.CampaignId == SCdb.CampaignId).ToList();
                                    context.SurveyClientControls.Add(SCdb);
                                    context.SaveChanges();
                                }
                                using (ApplicationDbContext questionDb = new ApplicationDbContext())
                                {
                                    SurveyClientControl dbQuestions = questionDb.SurveyClientControls.Include(s => s.Questions).Where(q => q.SurveyClientPhone == SClient.From).FirstOrDefault();
                                    if (dbQuestions.Questions.Count != 0)
                                    {
                                        foreach (var element in dbQuestions.Questions)
                                        {
                                            using (ApplicationDbContext progressDb = new ApplicationDbContext())
                                            {
                                                Progress dbProgress = progressDb.ProgressSwitches.Create();
                                                dbProgress.ProgressSwitch        = false;
                                                dbProgress.QuestionId            = element.QuestionId;
                                                dbProgress.SurveyClientControlId = dbQuestions.SurveyClientControlId;
                                                progressDb.ProgressSwitches.Add(dbProgress);
                                                progressDb.SaveChanges();
                                            }

                                            using (ApplicationDbContext currentQuestionDb = new ApplicationDbContext())
                                            {
                                                CurrentQuestion dbCQuestion = currentQuestionDb.CurrentQuestionSwitches.Create();
                                                dbCQuestion.CurrentQuestionSwitch = false;
                                                dbCQuestion.QuestionId            = element.QuestionId;
                                                dbCQuestion.SurveyClientControlId = dbQuestions.SurveyClientControlId;
                                                currentQuestionDb.CurrentQuestionSwitches.Add(dbCQuestion);
                                                currentQuestionDb.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // If Msg does not includes a Keyword, is considered as san Answer and it comes here
                    else
                    {
                        using (ApplicationDbContext questionsCompare = new ApplicationDbContext())
                        {
                            List <SurveyClientControl> SurveyClients = questionsCompare.SurveyClientControls.ToList();
                            List <string> Questions             = questionsCompare.Questions.Select(q => q.QuestionBody).ToList();
                            List <_TwilioMSGViewModel> leftMsgs = newMessages.Where(m => !Questions.Contains(m.Body)).ToList();
                            if (leftMsgs.Count != 0)
                            {
                                foreach (var MsgElement in leftMsgs)
                                {
                                    if (MsgElement.From != "+18324101832")
                                    {
                                        using (ApplicationDbContext LogResponse = new ApplicationDbContext())
                                        {
                                            List <int> Progress_QuestionId      = LogResponse.ProgressSwitches.Where(d => d.ProgressSwitch == true).Select(c => c.QuestionId).ToList();
                                            int        Last_Progress_QuestionId = Progress_QuestionId.LastOrDefault();
                                            Response   AddResponse = LogResponse.Responses.Create();
                                            AddResponse.ResponseBody          = MsgElement.Body;
                                            AddResponse.QuestionId            = Last_Progress_QuestionId;
                                            AddResponse.SurveyClientControlId = SurveyClients.Where(b => b.SurveyClientPhone == MsgElement.From).FirstOrDefault().SurveyClientControlId;
                                            LogResponse.Responses.Add(AddResponse);
                                            LogResponse.SaveChanges();
                                            break;
                                        }
                                    }
                                }
                                using (ApplicationDbContext StatusChangeCurrentQuestion = new ApplicationDbContext())
                                {
                                    foreach (var ClientElement in leftMsgs)
                                    {
                                        List <int> Progress_QuestionId      = StatusChangeCurrentQuestion.ProgressSwitches.Where(d => d.ProgressSwitch == true).Select(c => c.QuestionId).ToList();
                                        List <int> Current_Switches_False   = StatusChangeCurrentQuestion.CurrentQuestionSwitches.Where(c => c.CurrentQuestionSwitch == false).Select(d => d.QuestionId).ToList();
                                        int        Last_Progress_QuestionId = Progress_QuestionId.LastOrDefault();
                                        if (Progress_QuestionId.Count != 0 && Current_Switches_False.Count != 0 && ClientElement.From != "+18324101832")
                                        {
                                            SurveyClientControl CurrentClient = SurveyClients.Where(q => q.SurveyClientPhone == ClientElement.From).FirstOrDefault();
                                            CurrentQuestion     CurrentStatus = StatusChangeCurrentQuestion.CurrentQuestionSwitches.Where(c => c.QuestionId == Last_Progress_QuestionId && c.SurveyClientControlId == CurrentClient.SurveyClientControlId).FirstOrDefault();
                                            CurrentStatus.CurrentQuestionSwitch = true;
                                            StatusChangeCurrentQuestion.SaveChanges();
                                            break;
                                        }
                                        if (Progress_QuestionId.Count != 0 && Current_Switches_False.Count != 0 && ClientElement.From == "+18324101832")
                                        {
                                            SurveyClientControl CurrentClient = SurveyClients.Where(q => q.SurveyClientPhone == ClientElement.To).FirstOrDefault();
                                            CurrentQuestion     CurrentStatus = StatusChangeCurrentQuestion.CurrentQuestionSwitches.Where(c => c.QuestionId == Last_Progress_QuestionId && c.SurveyClientControlId == CurrentClient.SurveyClientControlId).FirstOrDefault();
                                            CurrentStatus.CurrentQuestionSwitch = true;
                                            StatusChangeCurrentQuestion.SaveChanges();
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // If Not new message, system will send questions to Survey Clients
                else
                {
                    List <SurveyClientControl> SurveyClientsReady;
                    using (ApplicationDbContext serviceReady = new ApplicationDbContext())
                    {
                        SurveyClientsReady = serviceReady.SurveyClientControls.Include(s => s.Questions).Include(s => s.ProgressSwitches).Include(s => s.CurrentQuestionSwitches).Where(q => q.BlackList == false).ToList();
                        foreach (var ClientElement in SurveyClientsReady)
                        {
                            List <int> ProgressIds        = ClientElement.ProgressSwitches.Where(o => o.ProgressSwitch == false).Select(p => p.QuestionId).ToList();
                            List <int> ProgressTrue       = ClientElement.ProgressSwitches.Where(p => p.ProgressSwitch == true).Select(z => z.QuestionId).ToList();
                            List <int> CurrentQuestionIds = ClientElement.CurrentQuestionSwitches.Where(q => q.CurrentQuestionSwitch == true).Select(r => r.CurrentQuestionId).ToList();
                            if (ProgressIds.Count != 0 && CurrentQuestionIds.Count != 0 && ProgressTrue.Count == CurrentQuestionIds.Count)
                            {
                                Question         Question_Filter_Progress = ClientElement.Questions.Where(q => ProgressIds.Contains(q.QuestionId)).FirstOrDefault();
                                TwilioRestClient clientSendMsg            = new TwilioRestClient(AuthTwilio.ACCOUNT_SID, AuthTwilio.AUTH_TOKEN);
                                clientSendMsg.SendSmsMessage("832-410-1832", ClientElement.SurveyClientPhone, Question_Filter_Progress.QuestionBody);
                                using (ApplicationDbContext changeProgress = new ApplicationDbContext())
                                {
                                    Progress ProgressChangeStatus = changeProgress.ProgressSwitches.Where(i => i.QuestionId == Question_Filter_Progress.QuestionId).FirstOrDefault();
                                    ProgressChangeStatus.ProgressSwitch = true;
                                    changeProgress.SaveChanges();
                                }
                            }
                            else
                            {
                                if (ProgressTrue.Count == 0 && CurrentQuestionIds.Count == 0)
                                {
                                    Question         Question_Filter_Progress = ClientElement.Questions.Where(q => ProgressIds.Contains(q.QuestionId)).FirstOrDefault();
                                    TwilioRestClient clientSendMsg            = new TwilioRestClient(AuthTwilio.ACCOUNT_SID, AuthTwilio.AUTH_TOKEN);
                                    clientSendMsg.SendSmsMessage("832-410-1832", ClientElement.SurveyClientPhone, Question_Filter_Progress.QuestionBody);
                                    using (ApplicationDbContext changeProgress = new ApplicationDbContext())
                                    {
                                        Progress ProgressChangeStatus = changeProgress.ProgressSwitches.Where(i => i.QuestionId == Question_Filter_Progress.QuestionId).FirstOrDefault();
                                        ProgressChangeStatus.ProgressSwitch = true;
                                        changeProgress.SaveChanges();
                                    }
                                }
                            }
                            if (ProgressIds.Count == 0 && ClientElement.BlackList == false)
                            {
                                Campaign Coupon;
                                using (ApplicationDbContext lastMsg = new ApplicationDbContext())
                                {
                                    Coupon = lastMsg.Campaigns.Where(q => q.CampaignId == ClientElement.CampaignId).FirstOrDefault();
                                }
                                TwilioRestClient clientSendMsg = new TwilioRestClient(AuthTwilio.ACCOUNT_SID, AuthTwilio.AUTH_TOKEN);
                                clientSendMsg.SendMessage("832-410-1832", ClientElement.SurveyClientPhone, "Thank you for Participating", new string[] { Coupon.CampaignGift });
                                ClientElement.BlackList = true;
                                serviceReady.SaveChanges();
                            }
                        }
                    }
                }
            }
            return(msg);
        }
Example #18
0
 public void ShowAnswer(int answerIndex)
 {
     // Show answer
     _view.ShowAnswer(answerIndex, CurrentQuestion.GetAnswerWordIndeces(answerIndex), false);
 }
Example #19
0
        void DisplayQuestion()
        {
            Question CurrentQuestion;

            if (CurrentQuestionId > 0 && CurrentQuestionId <= Quiz4TRule.Questions.Count)
            {
                //TODO : Remettre un peu d'ordre ! Je pense que ce traitement n'a rien à faire ici (encore que?)
                if (CurrentQuestionId == 2 && Quiz4TRule.Questions[0].SelectedChoice != 0)
                {
                    Quiz4TRule.Questions[CurrentQuestionId - 1].SelectChoice(-1);
                    CurrentQuestionId++;
                }

                CurrentQuestion = Quiz4TRule.Questions[CurrentQuestionId - 1];
            }
            else
            {
                DisplayResult();
                return;
            }

            SetContentView(Resource.Layout.Question);
            TextView IssueTextView   = FindViewById <TextView>(Resource.Id.TextViewQuestion);
            ListView ChoicesListView = FindViewById <ListView>(Resource.Id.ListViewChoices);


            IssueTextView.Text = CurrentQuestion.Issue;
            ArrayAdapter ChoicesListViewAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, CurrentQuestion.GetChoicesTexts());

            ChoicesListView.Adapter = ChoicesListViewAdapter;

            ChoicesListView.ItemClick += ChoiceClick;
        }
Example #20
0
 public List <Comment> GetComments()
 {
     return(CurrentQuestion.GetAllComments());
 }
Example #21
0
        public async Task StartGame()
        {
            while (!ShouldStopGame)
            {
                // reset the cancellation source
                triviaCancelSource = new CancellationTokenSource();

                // load question
                CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(oldQuestions);
                if (CurrentQuestion == null ||
                    string.IsNullOrWhiteSpace(CurrentQuestion.Answer) ||
                    string.IsNullOrWhiteSpace(CurrentQuestion.Question))
                {
                    await channel.SendErrorAsync("Trivia Game", "Failed loading a question.").ConfigureAwait(false);

                    return;
                }
                oldQuestions.Add(CurrentQuestion); //add it to exclusion list so it doesn't show up again

                EmbedBuilder questionEmbed;
                IUserMessage questionMessage;
                try
                {
                    questionEmbed = new EmbedBuilder().WithOkColor()
                                    .WithTitle("Trivia Game")
                                    .AddField(eab => eab.WithName("Category").WithValue(CurrentQuestion.Category))
                                    .AddField(eab => eab.WithName("Question").WithValue(CurrentQuestion.Question));

                    questionMessage = await channel.EmbedAsync(questionEmbed).ConfigureAwait(false);
                }
                catch (HttpException ex) when(ex.HttpCode == System.Net.HttpStatusCode.NotFound ||
                                              ex.HttpCode == System.Net.HttpStatusCode.Forbidden ||
                                              ex.HttpCode == System.Net.HttpStatusCode.BadRequest)
                {
                    return;
                }
                catch (Exception ex)
                {
                    _log.Warn(ex);
                    await Task.Delay(2000).ConfigureAwait(false);

                    continue;
                }

                //receive messages
                try
                {
                    NadekoBot.Client.MessageReceived += PotentialGuess;

                    //allow people to guess
                    GameActive = true;
                    try
                    {
                        //hint
                        await Task.Delay(HintTimeoutMiliseconds, triviaCancelSource.Token).ConfigureAwait(false);

                        if (ShowHints)
                        {
                            try
                            {
                                await questionMessage.ModifyAsync(m => m.Embed = questionEmbed.WithFooter(efb => efb.WithText(CurrentQuestion.GetHint())).Build())
                                .ConfigureAwait(false);
                            }
                            catch (HttpException ex) when(ex.HttpCode == System.Net.HttpStatusCode.NotFound || ex.HttpCode == System.Net.HttpStatusCode.Forbidden)
                            {
                                break;
                            }
                        }
                        catch (Exception ex) { _log.Warn(ex); }

                        //timeout
                        await Task.Delay(QuestionDurationMiliseconds - HintTimeoutMiliseconds, triviaCancelSource.Token).ConfigureAwait(false);
                    }
                    catch (TaskCanceledException) { } //means someone guessed the answer
                }
 public GameQuestion UseJoker()
 {
     return(CurrentQuestion.UseJoker());
 }