コード例 #1
0
            public async Task ExecuteGroupAsync(CommandContext ctx,
                                                [Description("ID of the quiz category.")] int id,
                                                [Description("Amount of questions.")] int amount            = 10,
                                                [Description("Difficulty. (easy/medium/hard)")] string diff = "easy")
            {
                if (this.Shared.IsEventRunningInChannel(ctx.Channel.Id))
                {
                    throw new CommandFailedException("Another event is already running in the current channel.");
                }

                if (amount < 5 || amount > 50)
                {
                    throw new CommandFailedException("Invalid amount of questions specified. Amount has to be in range [5, 50]!");
                }

                QuestionDifficulty difficulty = QuestionDifficulty.Easy;

                switch (diff.ToLowerInvariant())
                {
                case "medium": difficulty = QuestionDifficulty.Medium; break;

                case "hard": difficulty = QuestionDifficulty.Hard; break;
                }

                IReadOnlyList <QuizQuestion> questions = await QuizService.GetQuestionsAsync(id, amount, difficulty);

                if (questions == null || !questions.Any())
                {
                    throw new CommandFailedException("Either the ID is not correct or the category does not yet have enough questions for the quiz :(");
                }

                var quiz = new Quiz(ctx.Client.GetInteractivity(), ctx.Channel, questions);

                this.Shared.RegisterEventInChannel(quiz, ctx.Channel.Id);
                try {
                    await this.InformAsync(ctx, StaticDiscordEmoji.Clock1, "Quiz will start in 10s! Get ready!");

                    await Task.Delay(TimeSpan.FromSeconds(10));

                    await quiz.RunAsync();

                    if (quiz.IsTimeoutReached)
                    {
                        await this.InformAsync(ctx, StaticDiscordEmoji.AlarmClock, "Aborting quiz due to no replies...");

                        return;
                    }

                    await this.HandleQuizResultsAsync(ctx, quiz.Results);
                } finally {
                    this.Shared.UnregisterEventInChannel(ctx.Channel.Id);
                }
            }
コード例 #2
0
ファイル: QuizData.cs プロジェクト: VinceSeely/the-godfather
        public static string ToAPIString(this QuestionDifficulty diff)
        {
            switch (diff)
            {
            case QuestionDifficulty.Easy: return("easy");

            case QuestionDifficulty.Medium: return("medium");

            case QuestionDifficulty.Hard: return("hard");

            default: return("unknown");
            }
        }
コード例 #3
0
        /// <summary>
        /// 修改问题
        /// </summary>
        /// <param name="questionId"></param>
        /// <param name="title"></param>
        /// <param name="questionDifficulty"></param>
        /// <returns></returns>
        public async Task UpdateQuestionAsync(Guid questionId, string title, QuestionDifficulty questionDifficulty)
        {
            var question = repository.Questions.FirstOrDefault(p => p.QuestionGuid.Equals(questionId));

            if (question == null)
            {
                throw new Exception($"问题{questionId}不存在!");
            }

            question.UpdateTitle(title);
            question.UpdateQuestionDifficulty(questionDifficulty);
            await repository.SaveChangesAsync();
        }
コード例 #4
0
 private static void InsertMissingDifficulties(IEnumerable <OpenTriviaDb.Result> validQuestions)
 {
     foreach (var difficulty in validQuestions.Select(r => r.Difficulty))
     {
         if (QuestionDifficulty.Select(difficulty) == null)
         {
             var newDifficulty = new QuestionDifficulty
             {
                 Name = difficulty
             };
             newDifficulty.Insert();
         }
     }
 }
コード例 #5
0
    private void ShowNextQuestion(QuestionDifficulty difficultyToUse)
    {
        var chosenQuestion = FindQuestionByDifficulty(difficultyToUse);

        if (chosenQuestion != null)
        {
            chosenQuestion.isAlreadyShownOnce = true;
            EventSys.onNextQuestionForQuestionWindow.Invoke(chosenQuestion); // sending the question to the question window
        }
        else
        {
            EventSys.onOutOfQuestionsInDiffculty.Invoke(difficultyToUse);//letting the Quizer know.
        }
    }
コード例 #6
0
        /// <summary>
        /// Requests questions from the API.
        /// </summary>
        /// <param name="amount">The amount of questions to request.</param>
        /// <param name="category">The category of the questions. If left empty the questions will have mixed categories.</param>
        /// <param name="difficulty">The difficulty of the questions. Easy, Medium, or Hard. If left empty the questions received will have mixed difficulty levels.</param>
        /// <param name="type">The type of questions. Multiple or Boolean. If left empty the questions will have mixed types.</param>
        /// <param name="encoding">The type of encoding used in the response. Default, urlLegacy, url3986, or base64. If left empty it will use the default encoding (HTML Codes).</param>
        /// <param name="sessionToken">A session token. This token prevents the API from giving you the same question twice until 6 hours of inactivity or you reset the token.</param>
        /// <returns>A <see cref="QuestionsResponse"/> object.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown when <paramref name="amount"/> is out of range.</exception>
        public static QuestionsResponse RequestQuestions(uint amount,
                                                         QuestionCategory category     = QuestionCategory.Any,
                                                         QuestionDifficulty difficulty = QuestionDifficulty.Any,
                                                         QuestionType type             = QuestionType.Any,
                                                         ResponseEncoding encoding     = ResponseEncoding.Default,
                                                         string sessionToken           = "")
        {
            string json;

            using (var wc = new WebClient())
            {
                json = wc.DownloadString(GenerateApiUrl(amount, category, difficulty, type, encoding, sessionToken));
            }
            return(JsonConvert.DeserializeObject <QuestionsResponse>(json));
        }
コード例 #7
0
        private void btnGenerateRandomQuestion_Click(object sender, EventArgs e)
        {
            var selectedDifficulty = QuestionDifficulty.Select(cmbDifficulty.SelectedValue.ToString());
            var selectedType       = QuestionType.Select(cmbType.SelectedValue.ToString());

            if (selectedDifficulty != null && selectedType != null)
            {
                try
                {
                    _currentQuestion = Question.GetRandomQuestion(selectedDifficulty.Id, selectedType.Id);
                    txtCategory.Text = _currentQuestion.Category.Name;
                    rchQuestion.Text = _currentQuestion.QuestionText;
                    rchAnswer.Text   = _currentQuestion.GetAnswer();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
                }
            }
            else if (selectedDifficulty != null)
            {
                try
                {
                    _currentQuestion = Question.GetRandomQuestionByDifficulty(selectedDifficulty.Id);
                    txtCategory.Text = _currentQuestion.Category.Name;
                    rchQuestion.Text = _currentQuestion.QuestionText;
                    rchAnswer.Text   = _currentQuestion.GetAnswer();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
                }
            }
            else if (selectedType != null)
            {
                try
                {
                    _currentQuestion = Question.GetRandomQuestionByType(selectedType.Id);
                    txtCategory.Text = _currentQuestion.Category.Name;
                    rchQuestion.Text = _currentQuestion.QuestionText;
                    rchAnswer.Text   = _currentQuestion.GetAnswer();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// 创建问卷
        /// </summary>
        /// <param name="title"></param>
        /// <param name="questionDifficulty"></param>
        /// <returns></returns>
        public static Questionnaire CreateNew(string title, QuestionDifficulty questionDifficulty, IEnumerable <Question> questions)
        {
            var model = new Questionnaire
            {
                ID    = Guid.NewGuid(),
                Title = title,
                QuestionDifficulty     = questionDifficulty,
                CreatedStamp           = DateTime.Now,
                QuestionnaireQuestions = new List <QuestionnaireQuestion>()
            };

            foreach (var question in questions)
            {
                model.QuestionnaireQuestions.Add(QuestionnaireQuestion.CreateNew(model, question));
            }
            return(model);
        }
コード例 #9
0
        private void FillFormData()
        {
            var locationList = Business.Entities.Location.Select().ToList();

            cmbLocation.DataSource = locationList.Select(l => l.Name).ToList();
            cmbLocation.Update();

            var difficultyList = QuestionDifficulty.Select().Select(q => q.Name).ToList();

            cmbDifficulty.DataSource = difficultyList;
            cmbDifficulty.Update();

            var typeList = QuestionType.Select().Select(q => q.Name).ToList();

            cmbType.DataSource = typeList;
            cmbType.Update();
        }
コード例 #10
0
    private QuestionDifficulty _difficultyToUse = QuestionDifficulty.Easy;//changes from event fired from difficulty adapted defaults to easy

    protected override void SubscribeToEvents()
    {
        EventSys.onPlayButtonTriggered.AddListener(StartQuizSession);
        EventSys.onOutOfQuestions.AddListener(EndQuizSession);
        EventSys.onGameWon.AddListener(EndQuizSession);
        EventSys.onGameLost.AddListener(EndQuizSession);
        EventSys.onQuestionWindowIdle.AddListener(delegate
        {
            _isDisplayingAQuestion = false;
            if (_isQuizSessionRunning)
            {
                RequestNewQuestion();
            }
        });
        EventSys.onOutOfQuestionsInDiffculty.AddListener(ReRequestQuestionInDifferentDifficulty);
        EventSys.onChangeDifficulty.AddListener(delegate(QuestionDifficulty difficulty)
                                                { _difficultyToUse = difficulty; });
    }
コード例 #11
0
        public IEnumerable <QuestionDifficulty> GetAll()
        {
            // Use ADO.Net to DB access
            var Difficulties = new List <QuestionDifficulty>();

            try
            {
                //objet de connection
                using (var connection = new SqlConnection(connectionString))
                {
                    // Do work here
                    connection.Open();
                    //objet permettant de faire des requêtes SQL
                    var scriptGetAllDifficulty = @"
                                                SELECT 
	                                                d.Id,
                                                    d.QuestionDifficultyLevel
	                                                FROM QuestionDifficulty d
                                                ";

                    var sqlCommand = new SqlCommand(scriptGetAllDifficulty, connection);
                    //recupère les données dans la resultReader
                    var resultReader = sqlCommand.ExecuteReader(); //lecture et stockage du resultat dans resultReader
                    //parse ResultReader
                    while (resultReader.Read())
                    {
                        var Difficulty = new QuestionDifficulty()
                        {
                            Id = Convert.ToInt32(resultReader["Id"]),//recupère l'id de Difficulty dans la database et le converti

                            DifficultyLevel = resultReader["QuestionDifficultyLevel"].ToString(),
                        };
                        Difficulties.Add(Difficulty);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("L'erreur suivante a été rencontrée :" + e.Message);
            }

            return(Difficulties);
        }
コード例 #12
0
    /// <param name="emptyDifficulty">The difficulty no question could be found in</param>
    private void ReRequestQuestionInDifferentDifficulty(QuestionDifficulty emptyDifficulty)
    {
        switch (emptyDifficulty)
        {
        case QuestionDifficulty.Easy:
            EventSys.onQuizPlayerWithNewQuestion.Invoke(QuestionDifficulty.Medium);
            break;

        case QuestionDifficulty.Medium:
            EventSys.onQuizPlayerWithNewQuestion.Invoke(QuestionDifficulty.Hard);
            break;

        case QuestionDifficulty.Hard:
            EventSys.onOutOfQuestions.Invoke();
            break;

        default:
            throw new ArgumentOutOfRangeException("emptyDifficulty");
        }
    }
コード例 #13
0
        public static string GenerateApiUrl(uint amount,
                                            QuestionCategory category     = QuestionCategory.Any,
                                            QuestionDifficulty difficulty = QuestionDifficulty.Any,
                                            QuestionType type             = QuestionType.Any,
                                            ResponseEncoding encoding     = ResponseEncoding.Default,
                                            string sessionToken           = "")
        {
            if (amount < 1 || amount > 50)
            {
                throw new ArgumentOutOfRangeException(nameof(amount), amount, "Amount must be between 1 and 50.");
            }

            string query = $"amount={amount}";

            if (category != QuestionCategory.Any)
            {
                query += $"&category={category:D}";
            }

            if (difficulty != QuestionDifficulty.Any)
            {
                query += $"&difficulty={difficulty.ToString().ToLowerInvariant()}";
            }

            if (type != QuestionType.Any)
            {
                query += $"&type={type.ToString().ToLowerInvariant()}";
            }

            if (encoding != ResponseEncoding.Default)
            {
                query += $"&encode={encoding}";
            }

            if (!string.IsNullOrEmpty(sessionToken))
            {
                query += $"&token={sessionToken}";
            }

            return($"{ApiEndpoint}?{query}");
        }
コード例 #14
0
        private static void CreateNewQuestions(IEnumerable <OpenTriviaDb.Result> validQuestions)
        {
            foreach (var question in validQuestions)
            {
                var type       = QuestionType.Select(question.Type);
                var difficulty = QuestionDifficulty.Select(question.Difficulty);
                var category   = Category.Select(question.Category);
                var answers    = CreateAnswerKey(question);

                var newQuestion = new Question
                {
                    Category     = category,
                    Difficulty   = difficulty,
                    QuestionText = question.Question,
                    Type         = type,
                    Answer       = answers
                };

                newQuestion.Insert();
            }
        }
コード例 #15
0
        /** Public methods **/
        public QuestionsResponse RequestQuestions(uint amount,
                                                  QuestionDifficulty difficulty = QuestionDifficulty.Undefined,
                                                  QuestionType type             = QuestionType.Undefined,
                                                  ResponseEncoding encoding     = ResponseEncoding.Undefined,
                                                  uint categoryID     = 0,
                                                  string sessionToken = "")
        {
            string Url = "https://opentdb.com/api.php?amount=" + amount;

            if (categoryID != 0)
            {
                Url += "&category=" + categoryID;
            }

            if (difficulty != QuestionDifficulty.Undefined)
            {
                Url += "&difficulty=" + difficulty.ToString().ToLower();
            }

            if (type != QuestionType.Undefined)
            {
                Url += "&type=" + type.ToString().ToLower();
            }

            if (encoding != ResponseEncoding.Undefined)
            {
                Url += "&encode=" + encoding.ToString();
            }

            if (sessionToken != "")
            {
                Url += "&token=" + sessionToken;
            }

            string JsonString = SendAPIRequest(Url);

            return(JsonConvert.DeserializeObject <QuestionsResponse>(JsonString));
        }
コード例 #16
0
 public static QuestionDifficultiesListModel Create(QuestionDifficulty questionDifficulty)
 {
     return(Projection.Compile().Invoke(questionDifficulty));
 }
コード例 #17
0
 Question FindQuestionByDifficulty(QuestionDifficulty difficulty)
 {
     return((from question in allDownloadedQuestions
             where (question.isAlreadyShownOnce == false && question.questionDifficulty == difficulty)
             select question).FirstOrDefault());
 }
コード例 #18
0
ファイル: QuestionBank.cs プロジェクト: vandhanaa/gameShow
        public Question GetQuestion(QuestionCategory category, QuestionDifficulty difficulty)
        {
            #region Obsolete
            /*if (category == QuestionCategory.Red)
                return new Question()
                {
                    QuestionContent = "Red " + difficulty.ToString() + ": How to design this screen??? How to design this screen??? How to design this screen???",
                    A = "Dunno lah",
                    B = "How can I know",
                    C = "No idea",
                    D = "Why have to design??? Hehehe",
                    CorrectAnswer = "A"
                };
            else if (category == QuestionCategory.Blue)
                return new Question()
                {
                    QuestionContent = "Blue " + difficulty.ToString() + ": Test",
                    A = "A",
                    B = "B",
                    C = "C",
                    D = "D",
                    CorrectAnswer = "A"
                };
            else if (category == QuestionCategory.Green)
                return new Question()
                {
                    QuestionContent = "Green " + difficulty.ToString() + ": Test",
                    A = "A",
                    B = "B",
                    C = "C",
                    D = "D",
                    CorrectAnswer = "B"
                };
            else if (category == QuestionCategory.Yellow)
                return new Question()
                {
                    QuestionContent = "Yellow " + difficulty.ToString() + ": Test",
                    A = "A",
                    B = "B",
                    C = "C",
                    D = "D",
                    CorrectAnswer = "C"
                };
            else if (category == QuestionCategory.Gray)
                return new Question()
                {
                    QuestionContent = "Gray Normal: Test",
                    A = "A",
                    B = "B",
                    C = "C",
                    D = "D",
                    CorrectAnswer = "D"
                };
            else
                return null;*/
            #endregion

            #region Multiple Categories [Obsolete]
            //string queueName = string.Format("queue" + category.ToString() + difficulty.ToString());
            //try
            //{
            //    if (queueName == "queueRedNormal")
            //        return queueRedNormal.Dequeue();
            //    else if (queueName == "queueRedHard")
            //        return queueRedHard.Dequeue();
            //    else if (queueName == "queueBlueNormal")
            //        return queueBlueNormal.Dequeue();
            //    else if (queueName == "queueBlueHard")
            //        return queueBlueHard.Dequeue();
            //    else if (queueName == "queueYellowNormal")
            //        return queueYellowNormal.Dequeue();
            //    else if (queueName == "queueYellowHard")
            //        return queueYellowHard.Dequeue();
            //    else if (queueName == "queueGreenNormal")
            //        return queueGreenNormal.Dequeue();
            //    else if (queueName == "queueGreenHard")
            //        return queueGreenHard.Dequeue();
            //    else if (queueName == "queueGrayNormal")
            //        return queueGrayNormal.Dequeue();
            //    else if (queueName == "queueGrayHard")
            //        return queueGrayHard.Dequeue();
            //    else
            //        return null;
            //}
            //catch(Exception e)
            //{
            //    Debug.WriteLine(e.Message);
            //    return null;
            //}
            #endregion

            #region Multiple Difficulties
            try
            {
                if (difficulty == QuestionDifficulty.Normal)
                    return queueNormal.Dequeue();
                else
                    return queueHard.Dequeue();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return null;
            }
            #endregion

            //try
            //{
            //    return queueQuestion.Dequeue();
            //}
            //catch (Exception e)
            //{
            //    Debug.WriteLine(e.Message);
            //    return null;
            //}
        }
コード例 #19
0
ファイル: APRViewModel.cs プロジェクト: vandhanaa/gameShow
 public void LoadQuestion(QuestionCategory category, QuestionDifficulty difficulty)
 {
     CurrentQuestion = questionBank.GetQuestion(category, difficulty);
 }
コード例 #20
0
 public void UpdateQuestionDifficulty(QuestionDifficulty questionDifficulty)
 {
     QuestionDifficulty = questionDifficulty;
 }
コード例 #21
0
 public void DifficultyChanged(QuestionDifficulty questionDifficulty)
 {
     TriggerDialog("Difficulty Shift:" + questionDifficulty);
 }
コード例 #22
0
        public static async Task <IReadOnlyList <QuizQuestion> > GetQuestionsAsync(int category, int amount = 10, QuestionDifficulty difficulty = QuestionDifficulty.Easy)
        {
            if (category < 0)
            {
                throw new ArgumentException("Category ID is invalid!", nameof(category));
            }

            if (amount < 1 || amount > 20)
            {
                throw new ArgumentException("Question amount out of range (max 20)", nameof(amount));
            }

            string reqUrl   = $"{_url}/api.php?amount={amount}&category={category}&difficulty={difficulty.ToAPIString()}&type=multiple&encode=url3986";
            string response = await _http.GetStringAsync(reqUrl).ConfigureAwait(false);

            var data = JsonConvert.DeserializeObject <QuizData>(response);

            if (data.ResponseCode == 0)
            {
                return(data.Questions.Select(q => {
                    q.Content = WebUtility.UrlDecode(q.Content);
                    q.Category = WebUtility.UrlDecode(q.Category);
                    q.CorrectAnswer = WebUtility.UrlDecode(q.CorrectAnswer);
                    q.Difficulty = difficulty;
                    q.IncorrectAnswers = q.IncorrectAnswers.Select(ans => WebUtility.UrlDecode(ans)).ToList();
                    return q;
                }).ToList().AsReadOnly());
            }
            else
            {
                return(null);
            }
        }
コード例 #23
0
 public void DifficultyChanged(QuestionDifficulty difficulty)
 {
     TriggerDialog("Current Difficulty Set at: " + difficulty + " Player Adeptness Score: " + DynamicDifficultyAdapter.currentPlayerAdeptness);
 }
コード例 #24
0
        public static async Task <IReadOnlyList <QuizQuestion>?> GetQuestionsAsync(int category, int amount, QuestionDifficulty difficulty)
        {
            if (category < 0)
            {
                return(null);
            }

            if (amount is < 1 or > 20)
            {
                amount = 10;
            }

            QuizData?data = null;
            string   url  = $"{ApiUrl}/api.php?amount={amount}&category={category}&difficulty={difficulty.ToString().ToLower()}&type=multiple&encode=url3986";

            try {
                string response = await _http.GetStringAsync(url).ConfigureAwait(false);

                data = JsonConvert.DeserializeObject <QuizData>(response);
            } catch (Exception e) {
                Log.Error(e, "Failed to fetch {QuizQuestionAmount} quiz questions from category {QuizCategoryId}", amount, category);
            }

            if (data?.ResponseCode == 0)
            {
                IEnumerable <QuizQuestion> questions = data.Questions.Select(q => {
                    q.Content          = WebUtility.UrlDecode(q.Content);
                    q.Category         = WebUtility.UrlDecode(q.Category);
                    q.CorrectAnswer    = WebUtility.UrlDecode(q.CorrectAnswer);
                    q.Difficulty       = difficulty;
                    q.IncorrectAnswers = q.IncorrectAnswers.Select(ans => WebUtility.UrlDecode(ans)).ToList();
                    return(q);
                });
                return(questions.ToList().AsReadOnly());
            }
            else
            {
                return(null);
            }
        }