public async Task Start(Guid sessionId) { var playerIds = (await _sessionPlayerService.GetPlayersInSession(sessionId)).OrderBy(x => x).ToList(); var questions = (await _questionService.GetQuestionsInSession(sessionId)).OrderBy(x => x.CreatedBy).ToList(); var answers = (await _answerService.GetAnswersInSession(sessionId)).OrderBy(x => x.CreatedBy).ToList(); var options = await _whatIfOptionService.Get(sessionId); var turns = new List <Turn>(); var assignedQuestions = new List <Guid>(); for (var n = 0; n < playerIds.Count; n++) { var playerId = playerIds[n]; var nextPlayer = playerIds[(n % playerIds.Count + 1 % playerIds.Count) == playerIds.Count ? 0 : (n % playerIds.Count + 1 % playerIds.Count)]; var questionsByNextPlayer = questions.Where(x => x.CreatedBy == nextPlayer).ToList(); var answersByNextPlayer = answers.Where(x => x.CreatedBy == nextPlayer).ToList(); for (var i = 0; i < options.NumberOfCards; i++) { var question = questionsByNextPlayer[i]; var answer = answersByNextPlayer[i]; var turn = new Turn { Id = Guid.NewGuid(), QuestionId = question.Id, PlayerQuestionId = playerId, AnswerId = answer.Id, PlayerAnswerId = playerIds.Count == 2 ? nextPlayer : playerIds.Where(x => turns.Count(y => y.PlayerAnswerId == x) < options.NumberOfCards).FirstOrDefault(x => x != playerId && x != nextPlayer) }; assignedQuestions.Add(question.Id); turns.Add(turn); } } var rng = new Random(DateTime.Now.Millisecond); void Shuffle <T>(IList <T> list) { var n = list.Count; while (n > 1) { n--; var k = rng.Next(n + 1); var value = list[k]; list[k] = list[n]; list[n] = value; } } Shuffle(turns); var game = new Game { Turns = turns }; _games.TryAdd(sessionId, game); }
public async Task <IEnumerable <Question> > GenerateQuestionsForSession(Guid sessionId) { var options = await _whatIfOptionService.Get(sessionId); var playerIds = (await _sessionPlayerService.GetPlayersInSession(sessionId)).ToList(); var questions = new List <Question>(); for (int i = 1; i <= options.NumberOfCards; i++) { var questionsThisRound = new List <Question>(); foreach (var playerId in playerIds) { var playersAssignedQuestions = questions.GroupBy(x => x.AssignedToPlayer); var playersAssignedQuestionThisRound = questionsThisRound.Select(x => x.AssignedToPlayer); var validPlayersToAssignTo = playerIds.Where(x => x != playerId && playersAssignedQuestionThisRound?.Contains(x) != true); var assignToPlayer = validPlayersToAssignTo.FirstOrDefault(); if (assignToPlayer == Guid.Empty) { if (playerIds.Count == 2) { assignToPlayer = playerIds.FirstOrDefault(x => x != playerId); } else { var questionToSwap = questionsThisRound.FirstOrDefault(); assignToPlayer = questionToSwap.AssignedToPlayer; questionToSwap.AssignedToPlayer = playerId; } } var question = new Question { Id = Guid.NewGuid(), CreatedBy = playerId, SessionId = sessionId, AssignedToPlayer = assignToPlayer }; questions.Add(question); questionsThisRound.Add(question); } } _questions.TryAdd(sessionId, questions); return(questions); }