Inheritance: MonoBehaviour
Exemple #1
0
	public List<Quiz> GetQuizList () {
		SQLiteDB sqliteDB = OpenDatabase ();
		SQLiteQuery sqliteQuery = new SQLiteQuery (sqliteDB, "select * from quiz_list;");
		List<Quiz> quizList = new List<Quiz> ();
		while (sqliteQuery.Step ()) {
			Quiz quiz = new Quiz ();
			//カラムがない場合アリ
			try {
				quiz.Id = sqliteQuery.GetInteger (ID_FIELD);
				quiz.Title = sqliteQuery.GetString (TITLE_FIELD);
				quiz.QuizUrl = sqliteQuery.GetString (QUIZ_URL_FIELD);
				quiz.BoughtDate = sqliteQuery.GetString (BOUGHT_DATE_FIELD);
				quiz.QuizId = sqliteQuery.GetInteger (QUIZ_ID_FIELD);
				quiz.ChallengeQuizCorrect = sqliteQuery.GetInteger (CHALLENGE_QUIZ_CORRECT);
				quiz.ChallengeQuizCount = sqliteQuery.GetInteger (CHALLENGE_QUIZ_COUNT);
				quiz.ChallengeQuizData = sqliteQuery.GetString (CHALLENGE_QUIZ_DATA_FIELD);
				quiz.OrderNumber = sqliteQuery.GetInteger (ORDER_NUMBER_FIELD);
			} catch (Exception e) {
				Debug.LogError (e.Message);
			} finally {
				quizList.Add (quiz);
			}
		}
		sqliteDB.Close ();
		return quizList;
	}
Exemple #2
0
        public async Task<IHttpActionResult> PostQuiz(Quiz quiz)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Quizzes.Add(quiz);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (QuizExists(quiz.Id))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("DefaultApi", new { id = quiz.Id }, quiz);
        }
Exemple #3
0
 public int CreateQuiz(string title, string description, string category)
 {
     DateTime creationDate = DateTime.Now;
     Quiz newQuiz = new Quiz(title, description, category, creationDate);
     int quizId = myDataBase.AddQuiz(title, description, category, creationDate);
     return quizId;
 }
Exemple #4
0
    void OnCollisionEnter2D(Collision2D coll)
    {
        //If the player is invulnerable we immediately destroy the robot on contact.
        //If the player is not invulnerable then we present them with a quiz!
        if (isPlayerInvulnerable == true) {
            destroyObject();
        }
        else if (QuizNumber < 1  ) {
            QuizNumber++;
            //If the character collides and is not invulnerable
            if (coll.collider.name == characterName && (isPlayerInvulnerable == false) ) {
                Movement.ToggleMovement ();
                //Create one quiz
                Quiz newQuiz = new Quiz (1);

                //Get the currentQuestion
                Question currentQuestion = newQuiz.getCurrentQuestion ();

                //create a quiz window with the new data to display
                QuizWindow quizWindow = gameObject.AddComponent<QuizWindow> ();
                quizWindow.CreateWindow (currentQuestion);

                //show the window after all the data is assigned
                quizWindow.ShowWindow ();

                //print("Current Question :" + currentQuestion.getQuestionString());
                //print("Get Answers : " + currentQuestion.getAnwsers());
                //print("Correct Answer : "+ currentQuestion.correctAnwser);
            }

        }
    }
Exemple #5
0
        public async Task<IHttpActionResult> PutQuiz(string id, Quiz quiz)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != quiz.Id)
            {
                return BadRequest();
            }

            db.Entry(quiz).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!QuizExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
        public void CreateGame_WithValidArguments_SuccessfullyCreatesNewGame()
        {
            var quiz = new Quiz("testquiz", new Question("question", new Choice("choice", 10)));
            var game = GameFactory.Create(quiz);

            Assert.That(game, Is.Not.Null);
            Assert.That(game.Quiz, Is.EqualTo(quiz));
        }
Exemple #7
0
 internal void SaveQuiz(Quiz quiz)
 {
     if (quiz == null)
     {
         Debug.LogError("Error in saving the answer. Answer is null ");
         return;
     }
 }
Exemple #8
0
 public void AnswerQuestionTest()
 {
     string title = string.Empty; // TODO: Initialize to an appropriate value
     Quiz target = new Quiz(title); // TODO: Initialize to an appropriate value
     Answer a = null; // TODO: Initialize to an appropriate value
     target.AnswerQuestion(a);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
 public void NewQuizSession(int character)
 {
     Sprite[][] docs = new Sprite[][] { CreekDocuments, SeminoleDocuments, ChickasawDocuments, CherokeeDocuments, ChoctawDocuments };
     Quiz[][] quizzes = new Quiz[][] { CreekQuizzes, SeminoleQuizzes, ChickasawQuizzes, CherokeeQuizzes, ChoctawQuizzes };
     level_doc = docs[character];
     level_quiz = quizzes[character];
     currentchar = character;
     correct = new bool[] { false, false, false, false, false };
 }
Exemple #10
0
	public void UpdateOrderNumber (Quiz quiz) {
		SQLiteDB sqliteDB = OpenDatabase ();
		StringBuilder sb = new StringBuilder ();
		sb.Append ("update quiz_list set ");
		sb.Append (ORDER_NUMBER_FIELD + " = " + quiz.OrderNumber + " ");
		sb.Append ("where " + ID_FIELD + " = " + quiz.Id + ";");
		SQLiteQuery sqliteQuery = new SQLiteQuery (sqliteDB, sb.ToString ());
		sqliteQuery.Step ();
		sqliteDB.Close ();
	}
Exemple #11
0
	public void UpdateTitle (Quiz quiz) {
		SQLiteDB sqliteDB = OpenDatabase ();
		StringBuilder sb = new StringBuilder ();
		sb.Append ("update quiz_list set ");
		sb.Append (TITLE_FIELD + " = '" + quiz.Title + "' ");
		sb.Append ("where " + ID_FIELD + " = " + quiz.Id + ";");
		SQLiteQuery sqliteQuery = new SQLiteQuery (sqliteDB, sb.ToString ());
		sqliteQuery.Step ();
		sqliteDB.Close ();
	}
Exemple #12
0
 public void GetNextQuestionTest()
 {
     string title = string.Empty; // TODO: Initialize to an appropriate value
     Quiz target = new Quiz(title); // TODO: Initialize to an appropriate value
     Question expected = null; // TODO: Initialize to an appropriate value
     Question actual;
     actual = target.GetNextQuestion();
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
        public QuizView(Quiz quiz1)
        {
            InitializeComponent();

            quiz = quiz1;
            quizMaster.NewQuestion(currentQuestion,quiz[0]);

            DataContext = currentQuestion;

            PointLabel.DataContext = data;
        }
 private void button_Copy_Click(object sender, RoutedEventArgs e)
 {
     var json = new FileDeserializer();
     var quiz = new Quiz();
     quiz = json.Deserialize(Properties.Settings.Default.FilePath);
     var quizview = new QuizView(quiz);
     quizview.Width = Width;
     quizview.Height = Height;
     Close();
     quizview.Show();
 }
    void Start()
    {
        instructions = GameObject.Find ("Instructions");
        canvas = GameObject.Find ("Canvas");
        quiz = GameObject.Find ("QuizScript").GetComponent<Quiz>();
        gameOverCanvas = GameObject.Find ("GameOverCanvas");
        finalPoints = GameObject.Find ("FinalPoints").GetComponent<Text>();

        pointsText.text = "PONTOS\n" + 0;
        canvas.SetActive(false);
        gameOverCanvas.SetActive(false);
    }
Exemple #16
0
	private void TrimExistQuiz (Quiz quiz, List<SelledProject> categoryList) {
		int count = categoryList.Count;
		for (int i = 0; i < count; i++) {
			SelledProject selledProject = categoryList [i];
			if (selledProject.id == quiz.QuizId) {
				categoryList.Remove (selledProject);
				Debug.Log ("remove " + selledProject.title);
				break;
			}
		}

	}
Exemple #17
0
        public QuizDisplay(Quiz q, SystemDisplay sysDisplay)
        {
            _display = sysDisplay;

            _currentQuiz = q;
            _currentQuestion = _currentQuiz.GetNextQuestion();
            _currentQuestionAnswers = _currentQuestion.GetRandomAnswers();
            _currentQuizScore = new Score("Eric", ActivityType.Quiz, 0, _currentQuiz.GetTitle());
            _menu = new ScreenMenu(_currentQuestionAnswers,_currentQuiz.GetTitle(),_currentQuestion.Title);
            SystemMain.Drawing.DestroyTips();
            SystemMain.Drawing.DrawInstruction(40, 660, " to confirm your answer!", SystemMain.TexturePackage["A"], -1);
        }
Exemple #18
0
 public override void Save(Quiz q)
 {
     FileStream fs = File.OpenWrite(q.Title + ".zip");
     GZipStream gzs = new GZipStream(fs, CompressionMode.Compress, true);
     DES des = DES.Create();
     des.Key = DESKey;
     des.IV = DESKey;
     CryptoStream cs = new CryptoStream(gzs, des.CreateEncryptor(), CryptoStreamMode.Write);
     WalkSave(q, cs);
     cs.Close();
     gzs.Close();
     fs.Close();
 }
Exemple #19
0
 public void CreateQuizAndAddQuestion()
 {
     _target = new Quiz("A Quiz");
     var q = new Question("Test",
                             new List<Answer> { new Answer("Test", false), new Answer("Correct", true), new Answer("Wrong", false) });
     Assert.IsNotNull(_target);
     _target.AddItem(q);
     Assert.IsNotNull(_target);
     _target.GetOpenQuestion();
     Assert.AreEqual(_target.GetNextQuestion(), q);
     Assert.AreEqual(_target.GetOpenQuestion(), null);
     Assert.AreEqual(_target.GetNextQuestion(), null);
 }
 private void AddQuiz()
 {
     try
     {
         Quiz Q = new Quiz();
         Q.Name = _QuizName;
         DbContext.Quizen.Add(Q);
         DbContext.SaveChanges();
         QuizViewModel QVM = new QuizViewModel(Q);
         this.Quizes.Add(QVM);
         RaisePropertyChanged("Quizes");
     }
     catch { }
 }
Exemple #21
0
	public void UpdateRecord(Quiz quiz){
		SQLiteDB sqliteDB = OpenDatabase ();
		StringBuilder sb = new StringBuilder ();
		sb.Append ("update quiz_list set ");
		sb.Append (TITLE_FIELD + " = '" + quiz.Title + "', ");
		sb.Append (QUIZ_URL_FIELD + " = '" + quiz.QuizUrl + "', ");
		sb.Append (CHALLENGE_QUIZ_DATA_FIELD + " = '" + quiz.ChallengeQuizData + "', ");
		sb.Append (CHALLENGE_QUIZ_COUNT + " = " + quiz.ChallengeQuizCount + ", ");
		sb.Append (CHALLENGE_QUIZ_CORRECT + " = " + quiz.ChallengeQuizCount + ", ");
		sb.Append (BOUGHT_DATE_FIELD + " = '" + quiz.BoughtDate + "', ");
		sb.Append (QUIZ_ID_FIELD + " = " + quiz.QuizId+ ", ");
		sb.Append (ORDER_NUMBER_FIELD + " = " + quiz.OrderNumber + " ");
		sb.Append ("where " + ID_FIELD + " = " + quiz.Id + ";");
		SQLiteQuery sqliteQuery = new SQLiteQuery (sqliteDB, sb.ToString ());
		sqliteQuery.Step ();
		sqliteDB.Close ();
	}
        private ActionResult EnsureQuiz(Quiz quiz)
        {
            if (quiz == null)
            {
                return this.HttpNotFound("The specified quiz has disappeared without a trace");
            }

            bool isAdmin = this.User.IsInRole(GlobalConstants.AdministratorRoleName);

            if (!isAdmin && this.UserId != quiz.CreatedById)
            {
                this.TempData["error"] = "You are not allowed to modify this quiz as you are not it's creator";
                return this.RedirectToAction("Index", "Home");
            }

            return null;
        }
Exemple #23
0
        public override Quiz Load(string title)
        {
            FileStream fs = File.OpenRead(title + ".zip");
            GZipStream gzs = new GZipStream(fs, CompressionMode.Decompress, true);
            DES des = DES.Create();
            des.Key = DESKey;
            des.IV = DESKey;
            CryptoStream cs = new CryptoStream(gzs, des.CreateDecryptor(), CryptoStreamMode.Read);

            Quiz q = new Quiz();
            q.Title = title;
            q.Items.AddRange(((QuizItemContainer)WalkLoad(cs)).Items);
            cs.Close();
            gzs.Close();
            fs.Close();

            return q;
        }
Exemple #24
0
    private bool AddQuiz(Quiz quiz)
    {
        if(quiz == null)
        {
            Debug.LogError("Error in adding quiz. Quiz is null");
            return false;
        }

        if(mQuizes.Contains(quiz))
        {
            Debug.Log("Failed to add quiz. Quiz already exists ");
            return false;
        }

        mQuizes.Add(quiz);

        return true;
    }
 public Quiz Deserialize(string filepath)
 {
     string jsonstring = File.ReadAllText(Properties.Settings.Default.FilePath);
     var jsondto = new List<Dto>();
     jsondto = JsonConvert.DeserializeObject<List<Dto>>(jsonstring);
     var quiz = new Quiz();
     foreach (var VARIABLE in jsondto)
     {
         var Question = new QuestionAnswer();
         Question.Question = VARIABLE.Question;
         Question.A = VARIABLE.A;
         Question.B = VARIABLE.B;
         Question.C = VARIABLE.C;
         Question.D = VARIABLE.D;
         Question.RightAnswer = VARIABLE.RightAnswer;
         quiz.Add(Question);
     }
     return quiz;
 }
Exemple #26
0
 public void LetsTryResetingAQuiz()
 {
     _target = new Quiz("A Quiz");
     var q = new Question("Test", new List<Answer> { new Answer("Test", false), new Answer("Correct", true), new Answer("Wrong", false) });
     for (var i = 0; i < 10; i++)
     {
         _target.AddItem(q);
     }
     // Take the Quiz
     Assert.IsNotNull(_target.GetOpenQuestion());
     for (var i = 0; i < 10; i++)
     {
         // We're poping one off each time
         Assert.AreEqual(_target.GetStatus(), Status.InProgress, "The Quiz should be in progress");
         Assert.AreEqual(_target.GetNextQuestion(), q);
     }
     // There are no more questions left, we should have a null return
     Assert.AreEqual(Status.Completed, _target.GetStatus(), "Is it done yet?");
     Assert.AreEqual(_target.GetNextQuestion(), null);
     Assert.AreEqual(Status.Completed, _target.GetStatus(), "The Quiz should be done");
 }
	public void UpdateDatabase () {
		Debug.Log ("update database");
		int databaseVersion = PrefsManager.Instance.DatabaseVersion;
		Debug.Log ("database version = " + databaseVersion);
		switch (databaseVersion) {
		case 0:
			List<Quiz> quizList = QuizListDao.instance.GetQuizList ();
			if(quizList.Count ==0){
				//金魂クイズをインサート
				Quiz kinkonQuiz = new Quiz ();
				kinkonQuiz.Title = "金魂クイズ";
				kinkonQuiz.QuizUrl = "http://ryodb.us/projects/5035e95766e5411652000001/quizzes.json";
				kinkonQuiz.QuizId = 73;
				kinkonQuiz.BoughtDate = DateTime.Now.ToString ("yyyy/MM/dd");
				kinkonQuiz.OrderNumber = 1;
				QuizListDao.instance.Insert (kinkonQuiz);
				PrefsManager.Instance.DatabaseVersion = 3;
			}else {
				//ver0のままアップデートした人なので既存のレコードにquiz id を入れてあげる
				RemakeDatabase ();
				InitOrderNumber ();
				PrefsManager.Instance.DatabaseVersion = 3;
			}
			break;
		case 1:
			//ヒストリーデータを再構築(tweet_flagを削除)ver1.9
			RemakeDatabase ();
			InitOrderNumber ();
			PrefsManager.Instance.DatabaseVersion = 3;
			break;
		case 2:
			//オーダーナンバーを追加 ver2.0
			RemakeDatabase ();
			InitOrderNumber ();
			PrefsManager.Instance.DatabaseVersion = 3;
			break;
		}
		Debug.Log ("finish update");
		updatedDatabaseEvent ();
	}
Exemple #28
0
 public void CreateQuizAndAddQuestions()
 {
     _target = new Booklet("A Booklet");
     var quiz = new Quiz("A Quiz");
     var question = new Question("Test", new List<Answer> { new Answer("Test", false), new Answer("Correct", true), new Answer("Wrong", false) });
     for (var i = 0; i < 10; i++)
     {
         quiz.AddItem(question);
         _target.AddItem(quiz);
     }
     Assert.AreEqual(_target.GetStatus(), Status.NotStarted, "The Quiz should not have started");
     Assert.IsNotNull(_target.GetOpenQuiz());
     for (var i = 0; i < 10; i++)
     {
         // We're poping one off each time
         Assert.AreEqual(_target.GetStatus(), Status.InProgress, "The Quiz should be in progress");
         Assert.AreEqual(_target.GetNextQuiz(), quiz);
     }
     // There are no more questions left, we should have a null return
     Assert.AreEqual(_target.GetStatus(), Status.Completed, "Is it done yet?");
     Assert.AreEqual(_target.GetNextQuiz(), null);
     Assert.AreEqual(_target.GetStatus(), Status.Completed, "The Quiz should be done");
 }
 /// <summary>
 /// Delete a quiz
 /// </summary>
 /// <param name="quiz">quiz to be deleted</param>
 /// <returns>Task of completion</returns>
 public async Task Update(Quiz quiz)
 {
     _context.Entry(quiz).State = EntityState.Modified;
     await _context.SaveChangesAsync();
 }
Exemple #30
0
 public int CreateQuiz(Quiz quiz)
 {
     _quizRepository.Insert(quiz);
     return(quiz.Id);
 }
 private void quizListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     selectedQuiz = quizListBox.SelectedItem as Quiz;
 }
Exemple #32
0
 public IHttpActionResult Post(Quiz quiz)
 {
     _adapter.Create(quiz);
     return(Ok());
 }
        public static Quiz_DTO QuizTo_DTO(Quiz quiz, ref Quiz_DTO quiz_DTO)
        {
            quiz_DTO.Name = quiz.Name;

            quiz_DTO.Description = quiz.Description;

            List <Question_DTO> questionsWithAns = new List <Question_DTO>();

            if (quiz.Diff == Quiz.Difficulty.easy)
            {
                quiz_DTO.Difficulty = "easy";
            }

            else if (quiz.Diff == Quiz.Difficulty.medium)
            {
                quiz_DTO.Difficulty = "medium";
            }

            else if (quiz.Diff == Quiz.Difficulty.hard)
            {
                quiz_DTO.Difficulty = "hard";
            }

            foreach (var qstn in quiz.Questions)
            {
                Question_DTO question_DTO = new Question_DTO();

                question_DTO.QuestionSelf = qstn.QuestionSelf;
                question_DTO.ImgUrl       = qstn.ImgUrl;

                if (qstn.Type == Question.QType.Text)
                {
                    question_DTO.Type = "Text";
                }
                else if (qstn.Type == Question.QType.Yesno)
                {
                    question_DTO.Type = "Yesno";
                }

                List <Answer_DTO> anslist = new List <Answer_DTO>();
                foreach (var answer in qstn.Answers)
                {
                    Answer_DTO answer_DTO = new Answer_DTO();

                    answer_DTO.Answer_Text = answer.Answer_Text;
                    answer_DTO.IsCorrect   = answer.IsCorrect;

                    if (answer.YesNo == Answer.Yesno.yes)
                    {
                        answer_DTO.YesNo = "yes";
                    }

                    else if (answer.YesNo == Answer.Yesno.no)
                    {
                        answer_DTO.YesNo = "no";
                    }

                    anslist.Add(answer_DTO);
                }

                question_DTO.Answers = anslist;

                questionsWithAns.Add(question_DTO);
            }

            quiz_DTO.questions = questionsWithAns;

            return(quiz_DTO);
        }
    private void Start()
    {
        _quiz = FindObjectOfType <Quiz> ();

        GetComponent <Button> ().onClick.AddListener(CheckAnswers);
    }
Exemple #35
0
 public int AddQuiz(Quiz quiz)
 {
     _context.Quizes.Add(quiz);
     _context.SaveChanges();
     return(quiz.QuizId);
 }
Exemple #36
0
        /// <summary>
        /// Creates a sample quiz and add it to the Database
        /// together with a sample set of questions, answers & results.
        /// </summary>
        /// <param name="userId">the author ID</param>
        /// <param name="id">the quiz ID</param>
        /// <param name="createdDate">the quiz CreatedDate</param>
        private static void CreateSampleQuiz(
            ApplicationDbContext dbContext,
            int num,
            string authorId,
            int viewCount,
            int numberOfQuestions,
            int numberOfAnswersPerQuestion,
            int numberOfResults,
            DateTime createdDate)
        {
            var quiz = new Quiz()
            {
                UserId      = authorId,
                Title       = String.Format("Quiz {0} Title", num),
                Description = String.Format("This is a sample description for quiz {0}.", num),
                Text        = "This is a sample quiz created by the DbSeeder class for testing purposes. " +
                              "All the questions, answers & results are auto-generated as well.",
                ViewCount        = viewCount,
                CreatedDate      = createdDate,
                LastModifiedDate = createdDate
            };

            dbContext.Quizzes.Add(quiz);
            dbContext.SaveChanges();

            for (int i = 0; i < numberOfQuestions; i++)
            {
                var question = new Question()
                {
                    QuizId = quiz.Id,
                    Text   = "This is a sample question created by the DbSeeder class for testing purposes. " +
                             "All the child answers are auto-generated as well.",
                    CreatedDate      = createdDate,
                    LastModifiedDate = createdDate
                };
                dbContext.Questions.Add(question);
                dbContext.SaveChanges();

                for (int i2 = 0; i2 < numberOfAnswersPerQuestion; i2++)
                {
                    var e2 = dbContext.Answers.Add(new Answer()
                    {
                        QuestionId       = question.Id,
                        Text             = "This is a sample answer created by the DbSeeder class for testing purposes. ",
                        Value            = i2,
                        CreatedDate      = createdDate,
                        LastModifiedDate = createdDate
                    });
                }
            }

            for (int i = 0; i < numberOfResults; i++)
            {
                dbContext.Results.Add(new Result()
                {
                    QuizId   = quiz.Id,
                    Text     = "This is a sample result created by the DbSeeder class for testing purposes. ",
                    MinValue = 0,
                    // max value should be equal to answers number * max answer value
                    MaxValue         = numberOfAnswersPerQuestion * 2,
                    CreatedDate      = createdDate,
                    LastModifiedDate = createdDate
                });
            }
            dbContext.SaveChanges();
        }
 public void Remove(Quiz quiz)
 {
     _DbContext.Quizzes.Remove(quiz);
     _DbContext.SaveChanges();
 }
 public Quiz Add(Quiz quiz)
 {
     _DbContext.Quizzes.Add(quiz);
     _DbContext.SaveChanges();
     return(quiz);
 }
 public void SetActiveQuiz(Quiz quiz)
 {
     this.ActiveQuiz = quiz;
 }
        public async Task <ActionResult> NextQuestion(string quizName, Guid quizId, int qstnIndex, DateTime date, bool correct, int score)
        {
            try
            {
                var qstnList = await _questionRepo.GetQuestionsQuiz(quizId);

                if (correct)
                {
                    TimeSpan timeDiff = DateTime.Now.Subtract(date);
                    if (timeDiff.TotalSeconds > 30 && timeDiff.TotalSeconds < 0)
                    {
                    }
                    else
                    {
                        if (score >= (qstnList.Count() * 300))
                        {
                            score = 0;
                        }
                        else
                        {
                            int stp1 = 30 - Convert.ToInt32(timeDiff.TotalSeconds);
                            score = score + (stp1 * 10);
                        }
                    }
                }
                else
                {
                }

                fullQuiz fq = new fullQuiz()
                {
                    quizName = quizName, quizId = quizId, QuestionIndex = qstnIndex
                };
                fq.QuestionIndex += 1;

                if (fq.QuestionIndex >= qstnList.Count())
                {
                    // add score to database
                    Scores newscore = new Scores()
                    {
                        AppUserId = _userManager.GetUserId(User),
                        QuizId    = fq.quizId,
                        Date      = DateTime.Now
                    };
                    Quiz qz = await _quizRepo.GetQuizById(fq.quizId);

                    QuizScore qzsc = new QuizScore()
                    {
                        score = newscore, quiz = qz
                    };

                    ViewBag.score = score;

                    return(View("EndQuiz", qzsc));
                }
                else
                {
                    var qstnSelf = qstnList.ToList()[fq.QuestionIndex];

                    var ansListIe = await _answerRepo.GetAnswersForQuestion(qstnSelf.Id);

                    var ansList = ansListIe.ToList();

                    fq.quizQuestion = qstnSelf;
                    fq.answers      = ansList;

                    ViewBag.score = score;

                    return(View("PlayQuiz", fq));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #41
0
        private void NavigateBackward()
        {
            Quiz.NavigateBackward();

            OnPropertyChanged();
        }
Exemple #42
0
 public QuizVM(Quiz _quiz)
 {
     this._quiz = _quiz;
 }
Exemple #43
0
        public IActionResult SaveQuestion([FromForm] Question question, [FromForm] Theme theme, [FromForm] Quiz quiz)
        {
            if (quiz == null || question == null || theme == null)
            {
                BadRequest();
            }

            _questionManager.AddQuestion(question, theme, quiz);

            return(View("Answers", question));
        }
Exemple #44
0
        /// <summary>
        /// Creates a sample quiz together with a set of questions, answers and results
        /// </summary>
        /// <param name="dbContext">The db context</param>
        /// <param name="num">The quiz id</param>
        /// <param name="authorId">The author id</param>
        /// <param name="viewCount">The view count</param>
        /// <param name="numberOfQuestions">The number of questions</param>
        /// <param name="numberOfAnswersPerQuestion">The number of answers per questions</param>
        /// <param name="numberOfResults">The number of results</param>
        /// <param name="createdDate">The created date</param>
        private static void CreateSampleQuiz(ApplicationDbContext dbContext,
                                             int num,
                                             string authorId,
                                             int viewCount,
                                             int numberOfQuestions,
                                             int numberOfAnswersPerQuestion,
                                             int numberOfResults,
                                             DateTime createdDate)
        {
            var quiz = new Quiz
            {
                UserId           = authorId,
                Title            = string.Format("Quiz {0} Title", num),
                Description      = string.Format("This is a sample description for quiz {0}", num),
                Text             = "This is a sample quiz created by the DbSeeder class for testing purposes",
                ViewCount        = viewCount,
                CreatedDate      = createdDate,
                LastModifiedDate = createdDate
            };

            dbContext.Quizzes.Add(quiz);
            dbContext.SaveChanges();

            for (int i = 0; i < numberOfQuestions; i++)
            {
                var question = new Question
                {
                    QuizId           = quiz.Id,
                    Text             = "This is a sample question created by the DbSeeder class for testing purposes",
                    CreatedDate      = createdDate,
                    LastModifiedDate = createdDate
                };

                dbContext.Questions.Add(question);
                dbContext.SaveChanges();

                for (int j = 0; j < numberOfAnswersPerQuestion; j++)
                {
                    dbContext.Answers.Add(new Answer
                    {
                        QuestionId       = question.Id,
                        Text             = "This is a sample answer created by the DbSeeder class for testing purposes",
                        CreatedDate      = createdDate,
                        LastModifiedDate = createdDate
                    });
                }
            }

            for (int i = 0; i < numberOfResults; i++)
            {
                dbContext.Results.Add(new Result
                {
                    QuizId           = quiz.Id,
                    Text             = "This is a sample result created by the DbSeeder class for testing purposes",
                    MinValue         = default(int),
                    MaxValue         = numberOfAnswersPerQuestion + 2,
                    CreatedDate      = createdDate,
                    LastModifiedDate = createdDate
                });
            }

            dbContext.SaveChanges();
        }
Exemple #45
0
        public List <RealetedTask> getSTasks(string userEmail, string teamId)
        {
            SqlConnection con = null;

            List <RealetedTask> rtList = new List <RealetedTask>();

            try
            {
                con = connect("DBConnectionString"); // create a connection to the database using the connection String defined in the web config file

                String part1     = " select  tbl.taskId,tbl.Title,tbl.SubjectName,tbl.Date_Assignment,tbl.ForDate,tbl.OpenTill,tbl.YearOfStudy,tbl.IntelligenceName,tbl.[Name],tbl.creationTime,tbl.QuestionnaireId";
                String part2     = " ,pio.points,pio.Spoints,quest.QuestionId,quest.Content,quest.[Type],quest.OrderNum,quest.ImgLink,quest.VideoLink,a.Content AS ans_content,a.IsRight,a.AnswerId ,ac.[AnswerId] as picked,ao.[FileLink],ao.[Answer],pq.[Note],pq.Ptime,pq.Grade, ";
                String part3     = " case when pq.[StudentId]='" + userEmail + "' then 1 else 0 END as IsChoose ";
                String part4     = "  from (select t.taskId,t.Title,t.SubjectName,rt.Date_Assignment,rt.ForDate,rt.OpenTill,rt.YearOfStudy,q.IntelligenceName,i.[Name],max(q.creationTime)as creationTime,max(q.QuestionnaireId) as QuestionnaireId ";
                String part5     = " from task as t inner join RealatedTo rt on rt.TaskId=t.TaskId and rt.TeamId='" + teamId + "' inner join Questionnaire as q on q.TaskId=rt.TaskId and rt.Date_Assignment>q.creationTime ";
                String part6     = "  inner join  Intelligence as i on q.IntelligenceName=i.[EnglishName] group by t.taskId,t.Title,t.SubjectName,q.IntelligenceName,i.[Name],rt.Date_Assignment,rt.ForDate,rt.OpenTill,rt.YearOfStudy)as tbl  ";
                String part7     = "  inner join Question as quest on quest.QuestionnaireId=tbl.QuestionnaireId inner join PointsInIntelligence as pio on pio.IntelligenceName=tbl.IntelligenceName and pio.StudentEmail='" + userEmail + "' ";
                String part8     = "  left join Answer as a on a.QuestionId=quest.QuestionId left join [dbo].[PerformQuestionnaire] as pq on pq.[QuestionnaireId]=tbl.[QuestionnaireId] and pq.[StudentId]='" + userEmail + "' and  pq.TeamId='" + teamId + "' ";
                String part9     = " left join [dbo].[AnsClose] as ac on ac.[AnswerId]=a.[AnswerId] and ac.StudentEmail='" + userEmail + "' left join [dbo].[AnsOpen] as ao on ao.[QuestionId]=quest.[QuestionId] and ao.StudentEmail='" + userEmail + "' order by tbl.ForDate,tbl.TaskId,tbl.IntelligenceName,points ";
                String selectSTR = part1 + part2 + part3 + part4 + part5 + part6 + part7 + part8 + part9;

                SqlCommand cmd = new SqlCommand(selectSTR, con);

                // get a reader
                SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); // CommandBehavior.CloseConnection: the connection will be closed after reading has reached the end
                RealetedTask  rt = new RealetedTask();
                rt.Task          = new Task();
                rt.Task.QuizList = new List <Quiz>();
                Quiz     q   = new Quiz();
                Question que = new Question();
                while (dr.Read())
                {   // Read till the end of the data into a row
                    if (dr["TaskId"].ToString() != rt.Task.TaskId)
                    {
                        if (rt.Task.TaskId != null)
                        {
                            rt.Task.QuizList.Add(q);
                            rtList.Add(rt);
                        }
                        rt               = new RealetedTask();
                        q                = new Quiz();
                        rt.Task          = new Task();
                        rt.Task.QuizList = new List <Quiz>();
                        rt.Task.Grade    = Convert.ToInt32(dr["IsChoose"]);
                        rt.Task.TaskId   = dr["TaskId"].ToString();

                        rt.Task.Title = dr["Title"].ToString();
                        rt.Task.Grade = 0;

                        rt.Task.Sub      = new Subject(dr["SubjectName"].ToString(), "");
                        rt.YearOfStudy   = dr["YearOfStudy"].ToString();
                        rt.ForDate       = Convert.ToDateTime(dr["ForDate"]);
                        rt.TillDate      = Convert.ToDateTime(dr["OpenTill"]);
                        rt.AssigmentDate = Convert.ToDateTime(dr["Date_Assignment"]);
                    }
                    if (dr["Note"] != DBNull.Value)
                    {
                        rt.Note = dr["Note"].ToString();
                    }
                    if (dr["Grade"] != DBNull.Value)
                    {
                        rt.Score = Convert.ToInt32(dr["Grade"]);
                    }
                    if (dr["QuestionnaireId"].ToString() != q.QuizID)
                    {
                        if (q.QuizID != null)
                        {
                            rt.Task.QuizList.Add(q);
                        }

                        q          = new Quiz();
                        q.Question = new List <Question>();
                        q.QuizID   = dr["QuestionnaireId"].ToString();
                        q.TaskId   = dr["IsChoose"].ToString();
                        if (q.TaskId == "1")
                        {
                            if (dr["Ptime"] != DBNull.Value)
                            {
                                rt.STime = Convert.ToDateTime(dr["Ptime"]);
                            }
                            rt.Task.Grade = 1;
                        }
                        q.Inteligence = new Inteligence(Convert.ToInt32(dr["points"]), dr["Name"].ToString(), dr["IntelligenceName"].ToString(), 0);
                        if (dr["Spoints"] != DBNull.Value)
                        {
                            q.Inteligence.Spoints = Convert.ToInt32(dr["Spoints"]);
                        }
                    }

                    if (dr["QuestionId"].ToString() != que.QuestionId)
                    {
                        que        = new Question(dr["Type"].ToString(), dr["Content"].ToString(), new List <Answer>(), dr["ImgLink"].ToString(), dr["VideoLink"].ToString(), Convert.ToInt32(dr["OrderNum"]), dr["QuestionId"].ToString());
                        que.Answer = new List <Answer>();
                        q.Question.Add(que);
                    }

                    if (dr["ans_content"] != DBNull.Value)
                    {
                        que.Answer.Add(new Answer(dr["ans_content"].ToString(), Convert.ToBoolean(dr["IsRight"]), Convert.ToInt32(dr["AnswerId"])));

                        if (dr["picked"] != DBNull.Value)
                        {
                            que.Answer[que.Answer.Count - 1].IsPicked = true;
                        }
                        else
                        {
                            que.Answer[que.Answer.Count - 1].IsPicked = false;
                        }
                    }
                    else if (dr["Answer"] != DBNull.Value || dr["FileLink"] != DBNull.Value)
                    {
                        if (dr["FileLink"] != DBNull.Value)
                        {
                            que.AnsContent = dr["FileLink"].ToString();
                        }
                        else
                        {
                            que.AnsContent = dr["Answer"].ToString();
                        }
                    }
                }
                if (rt.Task.TaskId != null)
                {
                    rt.Task.QuizList.Add(q);
                    rtList.Add(rt);
                }
            }
            catch (Exception ex)
            {
                // write to log
                throw (ex);
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }



            return(rtList);
        }
 public async Task UpdateQuiz([FromBody] Quiz quiz) => await _quizWriteService.UpdateQuiz(quiz);
 public QuizBuilder(Quiz quiz)
 {
     Entity = quiz;
 }
 public ActionResult Details(Quiz quiz)
 {
     _quizId = Request.Url.Segments.Last();
     return(RedirectToAction("Quiz", new { id = _quizId }));
 }
Exemple #49
0
        public Quiz getQuizByID(int quizID)
        {
            SqlConnection conn     = new SqlConnection();
            Quiz          toReturn = null;

            try
            {
                conn = new SqlConnection();
                string connstr = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();
                conn.ConnectionString = connstr;
                conn.Open();
                SqlCommand comm = new SqlCommand();
                comm.Connection  = conn;
                comm.CommandText = "select * from [Quiz] q inner join [Elearn_course] ec on q.elearn_courseID = ec.elearn_courseID where q.quizID=@quizID";
                comm.Parameters.AddWithValue("@quizID", quizID);
                SqlDataReader dr = comm.ExecuteReader();
                while (dr.Read())
                {
                    toReturn = new Quiz();
                    toReturn.setQuizID((int)dr["quizID"]);
                    toReturn.setTitle((string)dr["title"]);
                    toReturn.setDescription((string)dr["description"]);
                    toReturn.setPassingGrade((int)dr["passingGrade"]);
                    toReturn.setRandomOrder((string)dr["randomOrder"]);
                    toReturn.setStatus((string)dr["status"]);
                    toReturn.setTimeLimit((int)dr["timeLimit"]);
                    toReturn.setMultipleAttempts((string)dr["multipleAttempts"]);
                    toReturn.setNumberOfAttempts((int)dr["numberOfAttempts"]);
                    toReturn.setDisplayAnswer((string)dr["displayAnswer"]);
                    Course_elearnDAO ceDAO = new Course_elearnDAO();
                    //toReturn.setMainCourse(ceDAO.get_course_by_id((int)dr["elearn_courseID"]));

                    Course_elearn course  = new Course_elearn();
                    UserDAO       userDAO = new UserDAO();
                    int           cid     = (int)dr["elearn_courseID"];    //1
                    course.setCourseID(cid);
                    course.setCourseName((string)dr["elearn_courseName"]); //2
                    if (!dr.IsDBNull(4))
                    {
                        course.setCourseProvider((string)dr["elearn_courseProvider"]);
                    }
                    ;
                    course.setStartDate((DateTime)dr["start_date"]);//3
                    if (!dr.IsDBNull(4))
                    {
                        course.setExpiryDate((DateTime)dr["expiry_date"]);
                    }
                    course.setStatus((string)dr["status"]);           //4
                    //get the prereq
                    course.setDescription((string)dr["description"]); //6
                    course.setEntryDate((DateTime)dr["entry_date"]);
                    ArrayList list = ceDAO.getPrereqOfCourse(cid);    //5
                    if (list != null)
                    {
                        course.setPrerequisite(list);            //retrieve arraylist of all prereq course_elearn objects
                    }
                    course.setCategoryID((int)dr["categoryID"]); //7
                    course.setCourseCreator(userDAO.getUserByID((string)dr["courseCreator"]));
                    course.setHoursAwarded((double)dr["hoursAwarded"]);
                    if (!dr.IsDBNull(11))
                    {
                        course.setTargetAudience((string)dr["targetAudience"]);
                    }

                    toReturn.setMainCourse(course);
                }
                dr.Close();
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
            return(toReturn);
        }
        protected void btnConfirmSubmit_Click(object sender, EventArgs e)
        {
            //to do validation
            Page.Validate("ValidateFormTwo");
            if (!Page.IsValid)
            {
            }
            else
            {
                //add the last question
                List <QuizQuestion> allQuestions = (List <QuizQuestion>)Session["allQuestions"];
                QuizQuestion        newQuestion  = new QuizQuestion();
                newQuestion.setQuestion(txtQuizQuestion.Text);

                QuizAnswer answer1 = new QuizAnswer();
                answer1.setAnswer(txtOptionOne.Text);

                QuizAnswer answer2 = new QuizAnswer();
                answer2.setAnswer(txtOptionTwo.Text);

                QuizAnswer answer3 = new QuizAnswer();
                answer3.setAnswer(txtOptionThree.Text);

                QuizAnswer answer4 = new QuizAnswer();
                answer4.setAnswer(txtOptionFour.Text);

                List <QuizAnswer> allAnswersForLastQn = new List <QuizAnswer>();
                allAnswersForLastQn.Add(answer1);
                allAnswersForLastQn.Add(answer2);
                allAnswersForLastQn.Add(answer3);
                allAnswersForLastQn.Add(answer4);

                newQuestion.setAllAnswers(allAnswersForLastQn);

                if (ddlCorrectAns.SelectedValue.Equals("1"))
                {
                    newQuestion.setQuizAnswer(answer1);
                }
                else if (ddlCorrectAns.SelectedValue.Equals("2"))
                {
                    newQuestion.setQuizAnswer(answer2);
                }
                else if (ddlCorrectAns.SelectedValue.Equals("3"))
                {
                    newQuestion.setQuizAnswer(answer3);
                }
                else
                {
                    newQuestion.setQuizAnswer(answer4);
                }

                allQuestions.Add(newQuestion);

                QuizDAO          quizDAO = new QuizDAO();
                QuizAnswerDAO    qaDAO   = new QuizAnswerDAO();
                QuizQuestionDAO  qqDAO   = new QuizQuestionDAO();
                Course_elearnDAO ceDAO   = new Course_elearnDAO();

                Course_elearn currentCourse = ceDAO.get_course_by_id(Convert.ToInt32(Request.QueryString["id"]));

                //create quiz
                List <string> part1   = (List <string>)Session["createQuiz1"];
                Quiz          newQuiz = new Quiz();
                newQuiz.setTitle(part1[0]);
                newQuiz.setDescription(part1[1]);
                newQuiz.setMainCourse(currentCourse);
                newQuiz.setPassingGrade(Convert.ToInt32(txtNumCorrectAns.Text));
                newQuiz.setStatus("active");
                if (ddlRandomize.SelectedValue.Equals("y"))
                {
                    newQuiz.setRandomOrder("y");
                }
                else
                {
                    newQuiz.setRandomOrder("n");
                }
                newQuiz.setTimeLimit(Convert.ToInt32(txtTimeLimit.Text));
                if (rdlAttempt.SelectedValue.Equals("unlimited"))
                {
                    newQuiz.setMultipleAttempts("y");
                    newQuiz.setNumberOfAttempts(0);
                }
                else
                {
                    newQuiz.setMultipleAttempts("n");
                    newQuiz.setNumberOfAttempts(Convert.ToInt32(txtNoOfAttempt.Text));
                }
                newQuiz.setDisplayAnswer(ddlDisplayAnswer.SelectedValue);

                int quizID = quizDAO.createQuiz(newQuiz);

                //add prerequisites
                List <int> prereqIDlist = (List <int>)Session["selectedPrereq"];
                foreach (int prereqID in prereqIDlist)
                {
                    quizDAO.insertPrerequisite(quizID, prereqID);
                }

                //create question and answer
                foreach (QuizQuestion question in allQuestions)
                {
                    question.setQuiz(quizDAO.getQuizByID(quizID));
                    int               questionID      = qqDAO.createQuizQuestion(question);
                    QuizQuestion      currentQuestion = qqDAO.getQuizQuestionByID(questionID);
                    List <QuizAnswer> allAnswers      = question.getAllAnswers();
                    foreach (QuizAnswer answer in allAnswers)
                    {
                        answer.setQuizQuestion(currentQuestion);
                        int answerID = qaDAO.createQuizAnswer(answer);
                        if (question.getQuizAnswer().getAnswer().Equals(answer.getAnswer()))
                        {
                            qqDAO.updateCorrectAnswerID(questionID, answerID);
                        }
                    }
                }

                //set audit
                User currentUser = (User)Session["currentUser"];
                setAudit(currentUser, "quiz", "create", quizID.ToString(), "quiz title: " + newQuiz.getTitle());

                Response.Redirect($"quizSummary.aspx?id={quizID}");
            }
        }
        public async Task <IHttpActionResult> PutQuiz(int id, Quiz quiz)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != quiz.Id)
            {
                return(BadRequest());
            }
            db.Entry(quiz).State = EntityState.Modified;
            switch (quiz.QType)
            {
            case "True or False":
                foreach (var item in quiz.TrueFalses)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;

            case "Matching":
                foreach (var item in quiz.Matchings)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;

            case "Short Answer":
                foreach (var item in quiz.ShortAnswers)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;

            case "Multiple Choice":
                foreach (var item in quiz.MultipleChoices)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;

            case "Multiple Response":
                foreach (var item in quiz.MultipleResponses)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;

            case "Fill in the Blanks":
                foreach (var item in quiz.FillinBlanks)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;

            case "Drag and Drop":
                foreach (var item in quiz.DragDrops)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;

            case "Sequence":
                foreach (var item in quiz.Sequences)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;

            case "Select from List":
                foreach (var item in quiz.SelectFromLists)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;

            case "Numeric":
                foreach (var item in quiz.Numerics)
                {
                    db.Entry(item).State = EntityState.Modified;
                }
                break;
            }


            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!QuizExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemple #52
0
 public Task AddQuiz(Quiz quiz, Guid lessonId)
 {
     throw new NotImplementedException();
 }
        public ActionResult Index()
        {
            Quiz answers = (Quiz)Session["quizAnswers"];

            return(Match(answers));
        }
 public void ShowQuiz(Quiz quiz)
 {
     quizShowUI.quiz = quiz;
     quizShowUI.gameObject.SetActive(true);
     quizShowUI.ShowQuiz();
 }
Exemple #55
0
 public void Post([FromBody] Quiz quiz)
 {
     _context.Quiz.Add(quiz);
     _context.SaveChanges();
 }
Exemple #56
0
 public QuizVM()
 {
     this._quiz = new Quiz();
 }
Exemple #57
0
    private void gotQuiz(object dataObj)
    {
        Dictionary<string, object> loginReturn = (Dictionary<string, object>)dataObj;

        if(loginReturn.ContainsKey("success") && loginReturn.ContainsKey("data"))
        {
            quizObj = new Quiz();

            Dictionary<string, object> data = loginReturn["data"] as Dictionary<string, object>;

            foreach(KeyValuePair<string,object> quizValues in data["quiz"] as Dictionary<string,object>)
            {
        //				Debug.Log("QUIZ["+quizValues.Key+"]="+quizValues.Value);
                if(quizValues.Key == "questions")
                {
                    foreach(object questionObj in quizValues.Value as List<object>)
                    {
                        Question parseQuestion = new Question();
                        foreach(KeyValuePair<string,object> question in questionObj as Dictionary<string,object>)
                        {
                            switch(question.Key)
                            {
                                case "id": parseQuestion.id = int.Parse(question.Value.ToString()); break;
                                case "question": parseQuestion.question = WWW.UnEscapeURL(question.Value.ToString()); break;
                                case "isImage": parseQuestion.isImage = ((question.Value.ToString() == "1") ? true : false); break;
                                case "sort": parseQuestion.sort = int.Parse(question.Value.ToString()); break;
                                case "value": parseQuestion.value = int.Parse(question.Value.ToString()); break;
                            }

        //							Debug.Log("QUESTION[" + question.Key + "]=" + question.Value);
                            if(question.Key == "answers")
                            {
                                foreach(object answerObj in question.Value as List<object>)
                                {
                                    Answer parseAnswer = new Answer();
                                    foreach(KeyValuePair<string,object> answer in answerObj as Dictionary<string,object>)
                                    {
                                        switch(answer.Key)
                                        {
                                            case "id": parseAnswer.id = int.Parse(answer.Value.ToString()); break;
                                            case "questionId": parseAnswer.questionId = int.Parse(answer.Value.ToString()); break;
                                            case "answer": parseAnswer.answer = WWW.UnEscapeURL(answer.Value.ToString()); break;
                                            case "sort": parseAnswer.sort = int.Parse(answer.Value.ToString()); break;
                                            case "isCorrect": parseAnswer.isCorrect = ((answer.Value.ToString()=="1") ? true : false); break;
                                        };
                                    }

                                    parseQuestion.answers.Add(parseAnswer);
                                }
                            }
                        }
                        quizObj.questions.Add(parseQuestion);
                    }
                }
            }

            Debug.Log("OMG WE HAVE A QUIZ : "+quizObj.questions.Count+" : ");
            questionNumber = 0;
            _secondsLeft = "120";
            CountDownTimer.instance.startTimer(120, tick);
        //			_secondsLeft = "10";
        //			CountDownTimer.instance.startTimer(10, tick);
            showNextQuestion();
        }
        else
        {
            Debug.LogError("SAD A");
        }
    }
 public ActionResult <bool> InsertQuiz([FromBody] Quiz entry)
 {
     return(_main.InsertQuiz(entry));
 }
Exemple #59
0
        public Event(DateTime ClockStart, DateTime ClockEnd, int ClockRunTime, System.Xml.Linq.XDocument XMLEvents, ref CrashHandler Crash)
        {
            ch = Crash;
            events = new Dictionary<string, List<EventItem>>();
            clock = new PartyClock(ClockStart, ClockEnd, ClockRunTime);
            Util.ShowClock = true;
            sound = new Sound(true);
            text = new Text2D();
            chess = new Chess();
            sf = new Starfield(150);

            intro = new Intro(ref sound, ref text);
            outro = new Outro(ref sound);

            advent = new Advent(ref sound);
            birthday = new Birthday(ref sound, ref text, ref chess);
            xmas = new Christmas(ref sound);
            smurf = new Datasmurf(ref sound, ref text); // random
            dif = new Dif(ref chess, ref sound); // random
            fbk = new Fbk(ref sound); // random
            hw = new Halloween(ref chess, ref sound, 25);
            lucia = new Lucia(ref chess, ref sound);
            newyear = new NewYear();
            richard = new RMS(ref sound, ref text); // random
            scroller = new Scroller(ref chess, ref sf, ref text); // random
            semla = new Semla();
            sune = new SuneAnimation(ref sound, ref text);
            tl = new TurboLogo(ref sound, ref chess, (OpenGL.Util.SpringOrFall.Equals("Spring")? true:false)/*((ClockStart.Month >= 1 && ClockStart.Month <= 8)? false:true)*/ ); // vilken termin är det? jan till början av augusti VT, resten HT... random
            valentine = new Valentine(ref sound);
            wl = new WinLinux(ref chess); //random
            creators = new Self(ref sound); // random
            bb = new BB(ref sound); // random
            GM = new GummiBears(ref sound);
            NDay = new National(ref chess, ref sound);
            easter = new Easter(ref sound);
            hajk = new Hajk(ref sound);
            mid = new Midsummer(ref sound);
            vaf = new Vaffla();
            wp = new Walpurgis();
            crayfish = new CrayFish();

            ts = new TeknatStyle(ref chess, ref sound, ref text);
            m = new Matrix(ref text);
            q = new Quiz(ref text, false, ref sound);
            talepsin = new Talespin(ref sound);
            cd = new ChipAndDale(ref sound, ref chess);
            nerd = new Nerdy(ref chess, ref sound);
            trex = new Trex(ref sound);
            sailormoon = new Sailormoon(ref sound,ref chess);
            gb = new GhostBusters(ref sound);
            zelda = new Zelda(ref sound, ref chess);
            tardis = new Tardis(ref sound);
            f**k = new F**k(ref sound, ref chess);

            silverFang = new SilverFang(ref sound);
            mt = new MoraT(ref sound);

            swine = new Swine(ref chess, ref text);
            tjall = new Tjall(ref chess, ref text);

            ronja = new Ronja(ref sound);
            emil = new Emil(ref sound);
            djungelboken = new Djungelboken(ref sound);
            fabbe = new Fabbe(ref sound);
            drink = new Drink(ref sound);
            frozen = new Frozen(ref sound);

            eventCurrent = null; // event item for events to be triggerd in clock_NewDate
            //randomEvent = new List<string>(new string[] { "starfield", "SuneAnimation", "TurboLogo", "Datasmurf", "WinLinux", "Scroller", "BB", "GummiBears", "TeknatStyle", "Matrix"});
            randomEvent = new List<string>(new string[] { "starfield", "Nerdy", "Talespin", "Sailormoon", "GhostBusters", "Zelda", "Tardis", "F**k", "SilverFang", "MoraT" });
            //new stuff
             List<UtilXML.EventData> ed = UtilXML.Loadeffectdata();

            // TODO: Make a clean list with all events allowed to be used implement so that it is actaully usable instead of a switch at the bottom of this file.
            Dictionary<string, Effect> effects = new Dictionary<string, Effect>()
            {
                {"SuneAnimation", new Effect(sune, ed.Find(e => e.Name == "SuneAnimation"))},
                {"Dif",new Effect(dif, ed.Find(e => e.Name == "Dif"))},
                {"Fbk",new Effect(fbk, ed.Find(e => e.Name == "Fbk"))},
                {"TurboLogo",new Effect(tl, ed.Find(e => e.Name == "TurboLogo"))},
                {"Datasmurf", new Effect(smurf, ed.Find(e => e.Name == "Datasmurf"))},
                {"RMS",new Effect(richard, ed.Find(e => e.Name == "RMS"))},
                {"WinLinux",new Effect(wl, ed.Find(e => e.Name == "WinLinux"))},
                {"Scroller",new Effect(scroller, ed.Find(e => e.Name == "Scroller"))},
                {"Self",new Effect(creators, ed.Find(e => e.Name == "Self"))},
                {"BB",new Effect(bb, ed.Find(e => e.Name == "BB"))},
                {"GummiBears",new Effect(GM, ed.Find(e => e.Name == "GummiBears"))},
                {"Hajk",new Effect(hajk, ed.Find(e => e.Name == "Hajk"))},
                {"TeknatStyle",new Effect(ts, ed.Find(e => e.Name == "TeknatStyle"))},
                {"Matrix",new Effect(m, ed.Find(e => e.Name == "Matrix"))},
                {"Quiz",new Effect(q, ed.Find(e => e.Name == "Quiz"))},
                {"Talespin",new Effect(talepsin, ed.Find(e => e.Name == "Talespin"))},
                {"ChipDale",new Effect(cd, ed.Find(e => e.Name == "ChipDale"))},
                {"Nerdy",new Effect(nerd, ed.Find(e => e.Name == "Nerdy"))},
              /*  {"Trex",new Effect(trex, ed.Find(e => e.Name == "Trex"))},*/
                {"Sailormoon",new Effect(sailormoon, ed.Find(e => e.Name == "Sailormoon"))},
                {"GhostBusters",new Effect(gb, ed.Find(e => e.Name == "GhostBusters"))},
                {"Zelda",new Effect(zelda, ed.Find(e => e.Name == "Zelda"))},
                {"Tardis",new Effect(tardis, ed.Find(e => e.Name == "Tardis"))},
                {"F**k",new Effect(f**k, ed.Find(e => e.Name == "F**k"))},
                {"SilverFang",new Effect(silverFang, ed.Find(e => e.Name == "SilverFang"))},
                {"MoraT",new Effect(mt, ed.Find(e => e.Name == "MoraT"))},
                {"Ronja",new Effect(ronja, ed.Find(e => e.Name == "Ronja"))},
                {"Emil",new Effect(emil, ed.Find(e => e.Name == "Emil"))},
                {"Djungelboken",new Effect(djungelboken, ed.Find(e => e.Name == "Djungelboken"))},
                {"Fabbe",new Effect(fabbe, ed.Find(e => e.Name == "Fabbe"))},
                {"Drink",new Effect(drink, ed.Find(e => e.Name == "Drink"))},
                {"Frozen",new Effect(drink, ed.Find(e => e.Name == "Frozen"))}
            };

            runEffectInMonth = new Dictionary<string, List<objdata>>();

            string[] months = Util.monthlist();
            int counter;
            foreach (KeyValuePair<string, Effect> pair in effects)
            {
                counter = 0;
                foreach (bool b in pair.Value.RunAllowedlist)
                {
                    if (b == true)
                    {
                        if (!runEffectInMonth.ContainsKey(months[counter]))
                        {
                            runEffectInMonth.Add(months[counter], new List<objdata>());
                        }

                        runEffectInMonth[months[counter]].Add(new objdata(pair.Key, pair.Value.Vetolist[counter], pair.Value.Priolist[counter], pair.Value.Runslist[counter]));
                    }
                    counter++;
                }
            }

            clock.NewDate += clock_NewDate; // Event listener

            if (ch.CrashDialogResult == System.Windows.Forms.DialogResult.Yes)
            {
                clock.clock = ch.CrashClock;
            }

            string name, date, type;
            // Event dates setup
            foreach (var item in XMLEvents.Descendants("event"))
            {
                name = item.Element("name").Value;
                date = item.Element("date").Value;
                type = item.Element("type").Value.ToLower();
                EventItem ei = new EventItem(name, type, date);
                if (!events.ContainsKey(date))
                {
                    List<EventItem> list = new List<EventItem>(); // seems most bad in my eyes...
                    events.Add(date, list);
                }

                for (int i = 0; i < events[date].Count; i++)
                {
                    EventItem e = events[date][i];
                    if ("birthday".Equals(e.Type) && "birthday".Equals(ei.Type))
                    {
                        e.Name += "\n\n" + ei.Name;
                        events[date][i] = e;
                    }
                }
                events[date].Add(ei);
                name = date = type = string.Empty;
            }

            // this needs to be fixed nicer...
            if (events.ContainsKey(ClockEnd.ToShortDateString()))
            {
                events[ClockEnd.ToShortDateString()].Clear(); // force this to be top..
                events[ClockEnd.ToShortDateString()].Add( new EventItem("outro", "outro", ClockEnd.ToShortDateString()) );
            }
            else
            {
                events.Add(ClockEnd.ToShortDateString(), new List<EventItem>() { new EventItem("outro", "outro", ClockEnd.ToShortDateString()) });
            }

            // Random effects on dates with no effects and check against new list of allowed things for them...
            DateTime dt = ClockStart;
            bool star = (Util.Rnd.Next(0, 1000) < 500 ? true:false); // make this random at the start too?
            int num = 0;

            while (dt <= ClockEnd)
            {
                date = dt.ToShortDateString();
                if (!events.ContainsKey(date))
                {
                    EventItem ei;

                    if (num == 0 || num == 1)
                    {
                        ei = new EventItem("starfield", "random", date);
                    }
                    else
                    {
                        //ei = new EventItem(randomEvent[Util.Rnd.Next(1, randomEvent.Count)], "random", date);

                        string month = "";
                        if (dt != null)
                            month = dt.Month.ToString();

                        switch (month)
                        {
                            case "1": month = "jan"; break;
                            case "2": month = "feb"; break;
                            case "3": month = "mar"; break;
                            case "4": month = "apr"; break;
                            case "5": month = "maj"; break;
                            case "6": month = "jun"; break;
                            case "7": month = "jul"; break;
                            case "8": month = "aug"; break;
                            case "9": month = "sep"; break;
                            case "10": month = "okt"; break;
                            case "11": month = "nov"; break;
                            case "12": month = "dec"; break;
                        }//switch

                        if (runEffectInMonth.ContainsKey(month))
                        {
                            List<objdata> mobj = runEffectInMonth[month];

                            List<objdata> vetolist = new List<objdata>();
                            List<objdata> novetolist = new List<objdata>();

                            foreach (objdata n in mobj)
                            {

                                if ("Quiz".Equals(n.Name) && eventnum == 4)
                                {
                                    n.vetoAgain();
                                    eventnum = 0;
                                }

                                if (n.Veto == true)
                                {
                                    if (n.Runs > 0)
                                        vetolist.Add(n);
                                }
                                else
                                {
                                    if (n.Runs > 0)
                                        novetolist.Add(n);
                                }
                            }

                            vetolist.Sort();
                            novetolist.Sort();

                            if (vetolist.Count > 0)
                            {
                                ei = new EventItem(vetolist[0].Name, "random", date);
                                vetolist[0].noMoreVeto();
                            }
                            else if (novetolist.Count > 0)
                            {
                                ei = new EventItem(novetolist[0].Name, "random", date);
                                novetolist[0].decRuns();
                                if (eventnum < 4)
                                    eventnum++;
                            }
                            else
                            {
                                ei = new EventItem(randomEvent[Util.Rnd.Next(1, randomEvent.Count)], "random", date);
                            }
                        }
                        else
                        {
                            ei = new EventItem(randomEvent[Util.Rnd.Next(1, randomEvent.Count)], "random", date);
                        }
                    }

                    num++;
                    if (num == 3)
                    {
                        num = 0;
                    }
                    ei = new EventItem("Self", "random", date); // this is for debuging new events
                    events.Add(date, new List<EventItem>());
                    events[date].Add(ei);
                }

                dt = dt.AddDays(1);
                date = string.Empty;
            }
        }
Exemple #60
0
 public override XmlDocument Serialize(Quiz q)
 {
     doc = new XmlDocument();
     doc.AppendChild(WalkSave(q));
     return(doc);
 }