Ejemplo n.º 1
0
        public static Test<string> GetTest()
        {
            var test = new Test<string>("Test");

            var question =
                new Question<string>(
                    "В каком случае в одной области видимости можно объявить два делегата с одним именем?",
                    ComplexityLevel.Hard);
            question.AddAnswer(new Answer<string>("Если у делегатов различное количество параметров.", false));
            question.AddAnswer(new Answer<string>("Ни в каком.", true));
            var textAnswer = new Answer<string>("Если они хранят один и тот же метод.", false);
            question.AddAnswer(textAnswer);
            test.AddQuestion(question);

            question = new Question<string>("Какое утверждение об интерфейсах (Ин.) справедливо?", new Range<int>(2, 2),
                                            ComplexityLevel.Hard);
            question.AddAnswer(new Answer<string>("Ин. поддерживают множественное наследование.", true));
            question.AddAnswer(new Answer<string>("Ин. могут содержать поля.", false));
            question.AddAnswer(new Answer<string>("Ин. могут содержать конструкторы.", false));
            question.AddAnswer(new Answer<string>("Ин. могут содержать cвойства, методы, события", true));
            test.AddQuestion(question);

            question = new Question<string>("Ключевое слово sealed применимо к...", ComplexityLevel.Easy);
            question.AddAnswer(new Answer<string>("Полям.", false));
            question.AddAnswer(new Answer<string>("Интерфейсам.", false));
            question.AddAnswer(new Answer<string>("Методам.", true));
            test.AddQuestion(question);

            question = new Question<string>("Что является особенностью пользовательских структур?", ComplexityLevel.Easy);
            question.AddAnswer(new Answer<string>("Структуры не поддерживают наследование.", true));
            question.AddAnswer(new Answer<string>("Структура не может содержать событий.", false));
            test.AddQuestion(question);

            question =
                new Question<string>(
                    "Какое ключевое слово используется в производном классе для вызова конструктора класса-предка?",
                    ComplexityLevel.Easy);
            question.AddAnswer(new Answer<string>("class", false));
            question.AddAnswer(new Answer<string>("base", true));
            question.AddAnswer(new Answer<string>("this", false));
            test.AddQuestion(question);

            question =
                new Question<string>("В групповой делегат объединили 3 функции и произвели вызов. Что будет получено?");
            question.AddAnswer(new Answer<string>("Исключительная ситуация.", false));
            question.AddAnswer(new Answer<string>("Массив из трех значений.", false));
            question.AddAnswer(new Answer<string>("Значение последней функции в цепочке.", true));
            test.AddQuestion(question);

            return test;
        }
Ejemplo n.º 2
0
        static void TestLINQtoObjects()
        {
            var test = GetTest();

            /* В коллекции 6 вопросов: 3 с уровнем сложности Easy, 1 - Normal, 2 - Hard */

            /* Выполняем фильтрацию коллекции вопросов по уровню сложности Hard (должно быть 2 вопроса) */
            var hardQuestions = test.Where(question =>
                {
                    var question3 = question as Question;
                    return question3 != null && question3.ComplexityLevel == ComplexityLevel.Hard;
                });
            Debug.Assert(hardQuestions.All(question => ((Question)question).ComplexityLevel == ComplexityLevel.Hard));
            /* Выполняем проекцию коллекции вопросов: получаем тексты вопросов */
            var texts = test.Select(question => question.Contents);
            Debug.Assert(texts.Count() == 6);

            /* Выполняем группировку элементов коллекции вопросов по уровню сложности */
            var groups = test.GroupBy(question => ((Question)question).ComplexityLevel).ToArray();
            Debug.Assert(groups.Count() == 3); // должны получить 3 группы вопросов: Easy, Normal, Hard
            var normalQuestions = groups.First(grouping => grouping.Key == ComplexityLevel.Normal); // находим группу Normal вопросов
            var normalQuestion = test.First(question => ((Question)question).ComplexityLevel == ComplexityLevel.Normal); // есть только 1 вопрос Normal
            Debug.Assert(Equals(normalQuestions.First(), normalQuestion));

            /* Выполняем преобразования коллекции */
            var questions = test.ToArray();
            Debug.Assert(questions.SequenceEqual(test.Questions)); // последовательности должны быть одинаковыми

            /* Выполняем вычисления агрегатных функций */
            Debug.Assert(test.Count() == test.QuestionsCount);
            var newBigQuestion = test.Aggregate((question1, question2) =>
                {
                    var newQuestion = new Question(question1.Contents + " " + question2.Contents);
                    newQuestion.AddAnswersRange(question1.Answers);
                    newQuestion.AddAnswersRange(question2.Answers);
                    return newQuestion;
                });
            Console.WriteLine(newBigQuestion.Contents); // длинный текст вопроса
            Console.WriteLine(newBigQuestion.Answers.Count()); // 17 ответов
        }
Ejemplo n.º 3
0
        public static void TestLinqToObjects()
        {
            Test<string> test = GetTest();

            /* В коллекции 6 вопросов: 3 с уровнем сложности Easy, 1 - Normal, 2 - Hard */

            /* Выполняем фильтрацию коллекции вопросов по уровню сложности Hard (должно быть 2 вопроса) */
            IEnumerable<IQuestion<string>> hardQuestions =
                test.Where(question => ((Question<string>) question).ComplexityLevel == ComplexityLevel.Hard);
            Debug.Assert(
                hardQuestions.All(question => ((Question<string>) question).ComplexityLevel == ComplexityLevel.Hard));

            /* Выполняем проекцию коллекции вопросов: получаем тексты вопросов */
            IEnumerable<string> texts = test.Select(question => question.Contents);
            Debug.Assert(texts.Count() == 6);

            /* Выполняем группировку элементов коллекции вопросов по уровню сложности */
            IGrouping<ComplexityLevel, IQuestion<string>>[] groups =
                test.GroupBy(question => ((Question<string>) question).ComplexityLevel).ToArray();
            Debug.Assert(groups.Count() == 3); // должны получить 3 группы вопросов: Easy, Normal, Hard
            IGrouping<ComplexityLevel, IQuestion<string>> normalQuestions =
                groups.First(grouping => grouping.Key == ComplexityLevel.Normal); // находим группу Normal вопросов
            IQuestion<string> normalQuestion =
                test.First(question => ((Question<string>) question).ComplexityLevel == ComplexityLevel.Normal);
            // есть только 1 вопрос Normal
            Debug.Assert(Equals(normalQuestions.First(), normalQuestion));

            /* Выполняем преобразования коллекции */
            IQuestion<string>[] questions = test.ToArray();
            Debug.Assert(questions.SequenceEqual(test.Questions)); // последовательности должны быть одинаковыми

            /* Выполняем вычисления агрегатных функций */
            Debug.Assert(test.Count() == test.QuestionsCount);
            IQuestion<string> newBigQuestion = test.Aggregate((question1, question2) =>
                                                                  {
                                                                      var newQuestion =
                                                                          new Question<string>(question1.Contents + " " +
                                                                                               question2.Contents);
                                                                      newQuestion.AddAnswersRange(question1.Answers);
                                                                      newQuestion.AddAnswersRange(question2.Answers);
                                                                      return newQuestion;
                                                                  });
            Debug.Assert(newBigQuestion.Answers.Any());
        }
Ejemplo n.º 4
0
        static void Play()
        {
            int rightAnswers = 0, money = 0;

            //Here you can add questions manually
            Question[] questions = new Question[]
            {
                new Question("2x9", "21", "37", "1", "18"),
                new Question("3x8", "14", "32", "22", "24"),
                new Question("4x7", "68", "53", "11", "28"),
                new Question("5x6", "21", "23", "28", "30"),
                new Question("6x12", "82", "62", "91", "72"),
                new Question("7x5", "48", "53", "31", "35"),
                new Question("8x6", "34", "43", "52", "48"),
                new Question("9x3", "12", "23", "26", "27"),
                new Question("2x1", "1", "6", "3", "2")
            };

            //main loop
            for (int i = 0; i < questions.Length; i++)
            {
                questions[i].PrintQuestion();
                questions[i].PrintAnswers();

                Console.Write("Введите вариант ответа цифрой: ");
                var answer = Console.ReadLine();

                if (questions[i].CheckAnswers(answer))
                {
                    rightAnswers++;
                    if (rightAnswers == 1) //if right answers number is 1, user will get 100 BYN
                    {
                        money += 100;
                        Console.WriteLine("Вы ответили правильно!");
                        string continueOrNot = "1";
                        Console.WriteLine("Сыграем ещё раз?");
                        Console.WriteLine("Нажмите 1 для продолжения игры, 2 - для выхода из игры.");
                        continueOrNot = Convert.ToString(Console.ReadLine());
                        while (continueOrNot != "1" && continueOrNot != "2")
                        {
                            Console.WriteLine("Нажмите 1 для продолжения игры, 2 - для выхода из игры.");
                            continueOrNot = Convert.ToString(Console.ReadLine());
                        }
                        if (continueOrNot == "2")
                        {
                            GameOver(money);
                            break;
                        }
                    }
                    else if (rightAnswers > 1 && rightAnswers < questions.Length) //if right answers number is more than 1 and less than questions in array, user will get x2 BYN
                    {
                        money *= 2;
                        Console.WriteLine("Вы ответили правильно!");
                        string continueOrNot = "1";
                        Console.WriteLine("Сыграем ещё раз?");
                        Console.WriteLine("Нажмите 1 для продолжения игры, 2 - для выхода из игры.");
                        continueOrNot = Convert.ToString(Console.ReadLine());
                        while (continueOrNot != "1" && continueOrNot != "2")
                        {
                            Console.WriteLine("Нажмите 1 для продолжения игры, 2 - для выхода из игры.");
                            continueOrNot = Convert.ToString(Console.ReadLine());
                        }
                        if (continueOrNot == "2")
                        {
                            GameOver(money);
                            break;
                        }
                    }

                    else if (rightAnswers == questions.Length) //high level - user answered all questions
                    {
                        money *= 2;
                        Console.WriteLine("Вы ответили правильно на все вопросы!");
                        GameOver(money);
                    }
                }
                else
                {
                    money = 0;
                    GameOver(money);
                    break;
                }
            }
        }