public async Task <GameQuestion> AddQuestionToGameAsync(Guid gameId, Guid questionId, Guid correctQuestionId) { try { GameQuestion gameQuestion = new GameQuestion() { QuestionId = questionId, GameId = gameId, CorrectQuestionId = correctQuestionId }; var controle = await context.GameQuestions.SingleOrDefaultAsync <GameQuestion>(e => e.GameId == gameId && e.QuestionId == questionId); if (controle != null) { Console.WriteLine("already in quiz"); return(null); } var result = await context.GameQuestions.AddAsync(gameQuestion); await context.SaveChangesAsync(); return(gameQuestion); } catch (Exception exception) { Console.WriteLine(exception.Message); return(null); } }
public JsonResult Delete([DataSourceRequest] DataSourceRequest request, GameQuestionDTO gameQuestionDTO) { try { //check to ensure the user owns the resources she is trying to access. if not; we get out of here. //Somebody is trying to do bad stuff. if (!ProbeValidate.IsGameQuestionForLoggedInUser(gameQuestionDTO.Id)) { ModelState.AddModelError("", "The attempt to remove a game question was not successful"); return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult())); } GameQuestion gameQuestion = db.GameQuestion.Find(gameQuestionDTO.Id); db.GameQuestion.Remove(gameQuestion); db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null); //Now that the gamequestion record is gone, get rid of the "UsedInGame" question/choice records ProbeQuestion.DeleteQuestion(this, db, gameQuestion.QuestionId); return(Json(new[] { gameQuestionDTO }.ToDataSourceResult(request, ModelState))); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR); return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult())); } }//public JsonResult DeleteGameQuestion([DataSourceRequest] DataSourceRequest request, GameQuestionDTO gameQuestionDTO)
public Game CreateGame(Guid userId) { var newGame = new Models.Game() { ID = Guid.NewGuid(), UserID = userId }; using (var triviaContext = new Entities()) { var questions = triviaContext.Questions.Take(20); foreach (var q in questions) { var newGameQuestion = new GameQuestion { ID = Guid.NewGuid(), GameID = newGame.ID, QuestionID = q.ID }; newGame.GameQuestions.Add(newGameQuestion); } triviaContext.AddToGames(newGame); triviaContext.SaveChanges(); } using (var triviaContext = new Entities()) { var game = triviaContext.Games .Include("GameQuestions") .Include("GameQuestions.Question") .Include("GameQuestions.Question.Answers") .FirstOrDefault(g => g.ID == newGame.ID); return game; } }
public DataModule(GameData gameData, DbRepository context) { _gameData = gameData; _gameState = GameState.Initialized; _currentGameQuestion = null; _context = context; GuessedGamePerson = null; }
public QuestionViewModel(GameQuestion question, bool showCorrect = false) { GameQuestionId = question.Id; QuestionId = question.Question.Id; Text = question.Question.Text; QuestionStartTime = question.StartTime.Value; Answers = question.Question.Answers.Select(x => new Answer { Id = x.Id, Text = x.Text, UserIdsSelected = question.UserSelectedAnswers.Where(u => u.AnswerId == x.Id).ToDictionary(u => u.UserGameSession.UserId, u => u.AnswerTime) }); if (showCorrect) { CorrectAnswerId = question.Question.Answers.First(x => x.IsCorrect).Id; } }
public void TestAskQuestion() { var quizQuestion = _questionRepository.List.First(); var answerSpecification = new QuizAnswerSpecification(questionId: quizQuestion.QuestionId); var quizAnswers = _answerRepository.Query(answerSpecification); quizQuestion.Answers = quizAnswers; var question = new GameQuestion(quizQuestion, 0, 0); var game = new RunningGame(0, new[] { 0 }); game.AskQuestion(question); Assert.Equal(question, game.CurrentQuestion); }
public JsonResult Create([DataSourceRequest] DataSourceRequest request, GameQuestionDTO gameQuestionDTO) { try { //check to ensure the user owns the resources she is trying to access. if not; we get out of here. //Somebody is trying to do bad stuff. if (!ProbeValidate.IsGameForLoggedInUser((long)gameQuestionDTO.GameId)) { ModelState.AddModelError("", "The attempt to add a game question was not successful"); return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult())); } if (!ProbeValidate.IsQuestionForLoggedInUser((long)gameQuestionDTO.QuestionId)) { ModelState.AddModelError("", "The attempt to add a game question was not successful"); return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult())); } //transform DTO to business object (GameQuestion) GameQuestion gameQuestion = new GameQuestion { Id = 0, GameId = gameQuestionDTO.GameId, QuestionId = gameQuestionDTO.QuestionId, OrderNbr = gameQuestionDTO.OrderNbr, Weight = gameQuestionDTO.Weight }; //We need to clone the question and set the UsedInGame field to true. The cloned questions //is what will be associated with the game ChoiceQuestion clonedQuestion = ProbeQuestion.CloneQuestion(this, ref db, true, gameQuestion.QuestionId); gameQuestion.Question = clonedQuestion; //we do a switch to the cloned question db.GameQuestion.Add(gameQuestion); db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null); gameQuestionDTO.Id = gameQuestion.Id; //pass back the new Id to the client return(Json(new[] { gameQuestionDTO }.ToDataSourceResult(request, ModelState))); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR); return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult())); } }
/// <summary> /// Dequeue new question. /// </summary> /// <returns>True if questions have ended.</returns> private bool NextQuestion() { if (_currentQuestion != null) { _imagesDone.Enqueue(_currentQuestion); } if (_imagesInQueue.Count == 0) { Logger.Info("All questions done."); return(true); } Logger.Info("New question."); _currentQuestion = _imagesInQueue.Dequeue(); return(false); }
public void TestUseJoker() { var quizQuestion = _questionRepository.List.First(); var answerSpecification = new QuizAnswerSpecification(questionId: quizQuestion.QuestionId); var quizAnswers = _answerRepository.Query(answerSpecification); quizQuestion.Answers = quizAnswers; var question = new GameQuestion(quizQuestion, 0, 0); var game = new RunningGame(0, new[] { 0 }); game.AskQuestion(question); game.UseJoker(); Assert.True(game.JokerUsed); }
public void TestAnswerQuestionIncorrect() { var quizQuestion = _questionRepository.List.First(); var answerSpecification = new QuizAnswerSpecification(questionId: quizQuestion.QuestionId); var quizAnswers = _answerRepository.Query(answerSpecification); quizQuestion.Answers = quizAnswers; var question = new GameQuestion(quizQuestion, 0, 0); var game = new RunningGame(0, new[] { 0 }); game.AskQuestion(question); var answer = quizAnswers.First(a => !a.Correct); var result = game.AnswerQuestion(answer); Assert.True(!result.Correct); }
//operate on database - get proper question in PeopleSet and QuestionSet context //update peopleset currentanswer field private GameQuestion retrieveRegularQuestion() { var bestQuestion = getDivideQuestion(); if (bestQuestion == null) { throw new Exception("partitioning error"); } var gameQuestion = new GameQuestion() { QuestionId = bestQuestion.QuestionId, SystemAnswer = AnswerType.Unknown, QuestionText = bestQuestion.Text, UserAnswer = AnswerType.Unknown, Unforgiveable = bestQuestion.Unforgiveable }; _currentGameQuestion = gameQuestion; return(gameQuestion); }
public ActionResult Update([DataSourceRequest] DataSourceRequest dsRequest, GameQuestionDTO gameQuestionDTO) { try { //we are only updating the Game Question order number and weight GameQuestion gameQuestion = db.GameQuestion.Find(gameQuestionDTO.Id); gameQuestion.OrderNbr = gameQuestionDTO.OrderNbr; gameQuestion.Weight = gameQuestionDTO.Weight; db.Entry(gameQuestion).State = EntityState.Modified; db.SaveChanges(Request != null ? Request.LogonUserIdentity.Name : null); return(Json(new[] { gameQuestionDTO }.ToDataSourceResult(dsRequest, ModelState))); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR); return(Json(ModelState.ToDataSourceResult())); } }
public void TestEndGame() { var quizQuestion = _questionRepository.List.First(); var answerSpecification = new QuizAnswerSpecification(questionId: quizQuestion.QuestionId); var quizAnswers = _answerRepository.Query(answerSpecification); quizQuestion.Answers = quizAnswers; var question = new GameQuestion(quizQuestion, 0, 0); var game = new RunningGame(0, new[] { 0 }); game.AskQuestion(question); var answer = quizAnswers.First(a => a.Correct); var answerResult = game.AnswerQuestion(answer); var result = game.End(answerResult.Correct && !answerResult.TimeOver, answerResult.TimeOver); Assert.Equal(30, result.Points); }
//operate on database - get proper question //update peopleset currentanswer field private GameQuestion retrieveFirstQuestion() { var unforgiveableQuestions = _context.GetQuestions(x => x.Unforgiveable); if (unforgiveableQuestions == null || unforgiveableQuestions?.Count == 0) { unforgiveableQuestions = _context.GetAllQuestions(); } var bestQuestion = getInitialPartition(unforgiveableQuestions); var gameQuestion = new GameQuestion() { QuestionId = bestQuestion.QuestionId, SystemAnswer = AnswerType.Unknown, QuestionText = bestQuestion.Text, UserAnswer = AnswerType.Unknown, Unforgiveable = true }; _currentGameQuestion = gameQuestion; return(gameQuestion); }
private QuestionViewModel CreateQuestionViewModel() { var settingMock = Helper.SetupConfigMock(Operator.Division, 0, 12); _question = new GameQuestion { Pair = new NumberPair { Number1 = 1, Number2 = 1 }, OpCtx = settingMock.Object.Operators[0] }; _eaMock.Setup(ea => ea.GetEvent <GameControlEvent>()).Returns(_gameControlEventMock.Object); _eaMock.Setup(ea => ea.GetEvent <UpdateScoreEvent>()).Returns(_updateScoreEvent.Object); _eaMock.Setup(ea => ea.GetEvent <SendAnswerResultEvent>()).Returns(_sendAnswerResultEvent.Object); _qGenMock.Setup(q => q.GenerateQuestion()).Returns(_question); var sut = new QuestionViewModel(_qGenMock.Object, _eaMock.Object); return(sut); }
public void TestUseJoker() { var quizQuestion = _questionRepository.List.First(); var answerSpecification = new QuizAnswerSpecification(questionId: quizQuestion.QuestionId); var quizAnswers = _answerRepository.Query(answerSpecification); quizQuestion.Answers = quizAnswers; // Would be much better: /* * var question = new GameQuestion(quizQuestion, quizAnswers, 0, 0); */ var question = new GameQuestion(quizQuestion, 0, 0); question.UseJoker(); var hiddenAnswers = question.Answers.Where(a => a.HiddenAnswer); Assert.Equal(2, hiddenAnswers.Count()); }
public void ProcessAnswer(AnswerType answer) { try { if (_gameState == GameState.Initialized) { throw new Exception("UI error - processing answer with no questions asked"); } if (_gameState == GameState.UninitializedPeopleSet) { //there was first question, now its time to prepare initial sets var answers = _context.GetAnswers(x => x.QuestionId == _currentGameQuestion.QuestionId); var personsToAdd = _context.GetPersons(x => answers.Any(y => y.PersonId == x.PersonId)); _currentGameQuestion.UserAnswer = answer; _gameData.QuestionSet.Add(_currentGameQuestion); _currentGameQuestion = null; _gameData.QuestionsAsked++; //fill people set foreach (var person in personsToAdd) { var a = answers.Single(x => x.PersonId == person.PersonId); var dataAnswer = calculateDominatingAnswer(a.YesCount, a.NoCount); if (dataAnswer == answer || answer == AnswerType.Unknown) { //unforgiveable question, add to set only in this case _gameData.PeopleSet.Add(new GamePerson() { CorrectAnswers = 1, CurrentAnswer = dataAnswer, Name = person.Name, OccurenceCount = person.Count, PersonId = person.PersonId }); } } _gameState = GameState.InProgress; } else if (_gameState == GameState.InProgress) { //regular case, there was an answer for regular question, update datasets _currentGameQuestion.UserAnswer = answer; _gameData.QuestionSet.Add(_currentGameQuestion); //unforgiveable - remove some persons if (_currentGameQuestion.Unforgiveable) { _gameData.PeopleSet = _gameData.PeopleSet.Where(x => x.CurrentAnswer == answer || x.CurrentAnswer == AnswerType.Unknown).ToList(); } _currentGameQuestion = null; _gameData.QuestionsAsked++; if (_gameData.PeopleSet.Count == 0) { _gameState = GameState.Defeated; } else { //update data sets foreach (var person in _gameData.PeopleSet) { if (person.CurrentAnswer == AnswerType.Unknown) { person.DontKnowAnswers++; } if (person.CurrentAnswer == AnswerType.Unknown || answer == AnswerType.Unknown) { continue; } if (person.CurrentAnswer == answer) { person.CorrectAnswers++; } } } } else if (_gameState == GameState.Guessing) { //guessing, can only be two options - yes or no if (answer == AnswerType.No) { _gameData.QuestionsAsked++; } else if (answer == AnswerType.Yes) { _gameState = GameState.Finished; } } } catch (Exception) { _gameState = GameState.Defeated; throw; } }
/// <summary> /// Start game loop. /// </summary> public void Process() { Boolean running = true; GameState _currentState = GameState.NotStarted; GameQuestion currentQuestion = null; while (running) { CancellationTokenSource cts = new CancellationTokenSource(); if (_timeoutDelay.HasValue) { timeoutTask = Timeout(cts.Token); } // Wait for a signal _eventSignal.WaitOne(); if (_exited) { break; } // Update state with input GameQuestion previousQuestion = currentQuestion; (_currentState, currentQuestion) = _gameInstance.GetNext(_currentState, _lastArgument); _lastArgument = null; // Cancel timeout if (_timeoutDelay.HasValue && !timeoutTask.IsCompleted) { cts.Cancel(); } if (previousQuestion != null) { if (previousQuestion.Done) { // Call UI to inform the user about answer correctness. if (previousQuestion.Correct) { AnswerCorrect(); } else { AnswerWrong( previousQuestion.CorrectAnswer , previousQuestion.Hints); } } else { throw new InvalidOperationException("Previous question was not marked as done."); } } // Handle new state switch (_currentState) { case GameState.Unkown: throw new InvalidOperationException("Unkown state."); case GameState.NotStarted: throw new InvalidOperationException("Game was unable to start."); case GameState.InGame: _frontEnd.OnNewQuestion( currentQuestion.ImageData.Value , currentQuestion.AlternativeAnswers.ToArray() , currentQuestion.CorrectAnswer); break; case GameState.Finished: Logger.Info("Game finished."); running = false; GameResult result = _gameInstance.GetFinalResult(); _frontEnd.OnEnd(result); break; default: throw new ArgumentOutOfRangeException(nameof(_currentState)); } _lastArgument = null; } }
public void SendAnswer(GameQuestion question) { string sql = "UPDATE GameQuestions SET UserAnswerId = @answerId WHERE Id = @qId"; _sqlDataAccess.SaveData(sql, new { answerId = question.Answer.Id, qId = question.Id }); }
/* * Will clone the game and all artifacts associated with that game. gameconfiguration, gamequestion, question/choicequestion, * choice and game records. The game to clone is defined by the sourceGameId. Where the game is clone to (what user) is * determined by the destAspNetUsersId */ public static Game CloneGame(Controller controller, ProbeDataContext db, long sourceGameId , string destAspNetUsersId, bool cloneCrossUsers, bool gamePlayInd) { //clone game - always in suspend mode so its not playable yet and it's editable Game gSource = db.Game.Find(sourceGameId); string newName = GetClonedGameName(gSource.Name, destAspNetUsersId); string newCode = GetClonedCode(gSource.Code); Game gNew = new Game { AspNetUsersId = destAspNetUsersId, GameTypeId = gSource.GameTypeId, Name = newName, Description = gSource.Description, Code = newCode, TestMode = gSource.TestMode, Published = (cloneCrossUsers) ? gSource.Published : false, SuspendMode = (cloneCrossUsers) ? gSource.SuspendMode : false, ClientReportAccess = gSource.ClientReportAccess, StartDate = gSource.StartDate, EndDate = gSource.EndDate, GameUrl = gSource.GameUrl, ACLId = gSource.ACLId }; db.Game.Add(gNew); //clone all gameconfigurations. should only pull the gameconfiguration records that exist. Any configuration that is still //using the default ConfigurationG record will not be pulled here. No need to clone this record. IList <GameConfigurationDTO> gameConfigurations = db.ConfigurationG .Where(c => c.ConfigurationType != ConfigurationG.ProbeConfigurationType.GLOBAL) .SelectMany(c => c.GameConfigurations.Where(gc => gc.Game.Id == sourceGameId), (c, gc) => new GameConfigurationDTO { ConfigurationGId = gc.ConfigurationGId, Value = gc.Value } ).ToList(); foreach (GameConfigurationDTO gameConfiguration in gameConfigurations) { GameConfiguration clonedGameConfiguration = new GameConfiguration { Game = gNew, ConfigurationGId = gameConfiguration.ConfigurationGId, Value = gameConfiguration.Value }; db.GameConfiguration.Add(clonedGameConfiguration); }//foreach (GameConfiguration gameConfiguration in gameConfigurations) //clone gamequestions and question/choices for each gamequestion IList <GameQuestion> gameQuestions = db.GameQuestion.Where(gq => gq.GameId == sourceGameId).ToList(); Dictionary <long, Dictionary <long, Choice> > questionXreference = new Dictionary <long, Dictionary <long, Choice> >(); foreach (GameQuestion gameQuestion in gameQuestions) { //attach questions to game long sourceQuestionId = gameQuestion.QuestionId; ChoiceQuestion clonedQuestion = ProbeQuestion.CloneQuestion(controller, ref db, true, sourceQuestionId); GameQuestion clonedGameQuestion = new GameQuestion { Game = gNew, Question = clonedQuestion, OrderNbr = gameQuestion.OrderNbr, Weight = gameQuestion.Weight }; db.GameQuestion.Add(clonedGameQuestion); //We are building a question - choice cross reference table for down the road. old question id -> (old choice id -> new choice) ChoiceQuestion cqOrg = db.ChoiceQuestion.Find(sourceQuestionId); Dictionary <long, Choice> choiceXreference = new Dictionary <long, Choice>(); //Here we populate the choice X reference table. Associate the old choice with the new choice. Somebody might need this down the road. for (int i = 0; i < cqOrg.Choices.Count(); i++) { //NEED A DATASTRUCTURE THAT ASSOCIATES ONE CHOICE WITH ANOTHER CHOICE choiceXreference.Add(cqOrg.Choices.ElementAt(i).Id, clonedQuestion.Choices.ElementAt(i)); } //DATASTRUCTURE that does hold old question id -> (old choice id -> new choice). This is to record the choices for the //new questions of the game associated with the new gamequestions questionXreference.Add(gameQuestion.QuestionId, choiceXreference); }//foreach (GameQuestion gameQuestion in gameQuestions) //if directed, then the game that is played will be cloned. Players, GameAnswers if (gamePlayInd) { //Get all the players for the game played IList <Player> players = db.Player.Where(p => p.GameId == sourceGameId).ToList(); foreach (Player player in players) { Player clonedPlayer = new Player { LastName = player.LastName, FirstName = player.FirstName, MiddleName = player.MiddleName, NickName = player.NickName, EmailAddr = player.EmailAddr, MobileNbr = player.MobileNbr, Sex = player.Sex, SubmitDate = player.SubmitDate, SubmitTime = player.SubmitTime, GameId = gNew.Id, Active = player.Active, PlayerGameReason = player.PlayerGameReason }; db.Player.Add(clonedPlayer); //Get all the OLD answers for the player in this iteration IList <GameAnswer> gameanswers = db.GameAnswer.Where(ga => ga.PlayerId == player.Id).ToList(); foreach (GameAnswer gameAnswer in gameanswers) { GameAnswer clonedGameAnswer = new GameAnswer { Player = clonedPlayer, Choice = questionXreference[gameAnswer.Choice.ChoiceQuestionId][gameAnswer.ChoiceId] }; db.GameAnswer.Add(clonedGameAnswer); } //foreach (GameAnswer gameAnswer in gameanswers) } //foreach (Player player in players) } //if (gamePlayInd) //THIS WILL RECORD NEW Game, GameConfiguration, GameQuestions, ChoiceQuestion/Question, Choice db.SaveChanges(controller.Request != null ? controller.Request.LogonUserIdentity.Name : null); //record all gameanswers for the new player return(gNew); }//CloneGame