/// <summary> /// /// </summary> /// <param name="triviaPlayer">The player (only ID field required).</param> /// <returns></returns> public async Task <TriviaQuestion> GetQuestionAsync(TriviaPlayer triviaPlayer) { TriviaQuestion triviaQuestion = null; HttpContent httpContent = new StringContent( "{ \"id\": \"" + triviaPlayer.Id + "\" }", Encoding.UTF8, RestApiHelper.ContentTypeJson); string response = null; try { response = await RestApiHelper.ExecuteHttpPostAsync( TriviaQuestionUri, httpContent, RestApiHelper.ContentTypeJson); System.Diagnostics.Debug.WriteLine($"Received response: {response}"); triviaQuestion = JsonConvert.DeserializeObject <TriviaQuestion>(response); } catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Failed to get question: {e.Message}"); } return(triviaQuestion); }
void set_cur_question() { invoked = false; question += 1; answers = 0; score = 1000; readTime = 20; question_text.text = questions[question].question; answer_a.text = questions[question].choices[0]; answer_b.text = questions[question].choices[1]; answer_x.text = questions[question].choices[2]; answer_y.text = questions[question].choices[3]; char[] ops = { 'a', 'b', 'x', 'y' }; for (int i = 0; i < 4; i++) { if (questions[question].choices[i] == questions[question].answer) { correct_answer = ops[i]; } } foreach (GameObject player in players) { TriviaPlayer a = player.GetComponent <TriviaPlayer>(); a.restart(); } }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var activity = await result as Activity; string messageText = CleanMessage(activity); if (!string.IsNullOrEmpty(messageText)) { TriviaApiClient triviaApiClient = WebApiConfig.TriviaApiClient; InMemoryTriviaDatastore triviaDatastore = WebApiConfig.TriviaDatastore; if (messageText.Equals(CommandHelp)) { await context.PostAsync(HelpMessage); } else if (messageText.Equals(CommandQuestion)) { TriviaPlayer triviaPlayer = await GetPlayer(activity); if (triviaPlayer != null) { TriviaQuestion triviaQuestion = await triviaApiClient.GetQuestionAsync(triviaPlayer); if (triviaQuestion != null && !string.IsNullOrEmpty(triviaQuestion.Text) && triviaQuestion.QuestionOptions != null && triviaQuestion.QuestionOptions.Count > 0) { if (triviaDatastore.PendingTriviaQuestions.ContainsKey(triviaPlayer.Id)) { triviaDatastore.PendingTriviaQuestions[triviaPlayer.Id] = triviaQuestion.Id; } else { triviaDatastore.PendingTriviaQuestions.Add(triviaPlayer.Id, triviaQuestion.Id); } await context.PostAsync($"{GetFirstName(triviaPlayer)}, your question is:"); HeroCard questionCard = CardFactory.CreateQuestionCard(triviaQuestion); Activity replyActivity = activity.CreateReply(); replyActivity.Attachments = new List <Attachment>() { questionCard.ToAttachment() }; await context.PostAsync(replyActivity); } else { await context.PostAsync("I'm sorry, I couldn't find a trivia question. Please try again later"); } } else { await context.PostAsync("I'm sorry, I couldn't find your player profile. Are you sure you have registered?"); } } else if (messageText.StartsWith(CommandRegister)) { string serviceUrl = activity.ServiceUrl; var memebers = await TeamsApiClient.GetTeamsMembers(activity, serviceUrl, HavocTeamId); if (memebers?.Count > 0) { var triviaRoster = new TriviaRoster { TeamId = HavocTeamId, Members = memebers }; TriviaRegister registerResponse = await triviaApiClient.RegisterAsync(triviaRoster); if (registerResponse != null) { if (registerResponse.Success) { await context.PostAsync("Team registered successfully!"); } else { await context.PostAsync($"Failed to register the team: {registerResponse.Message}"); } } else { await context.PostAsync($"Failed to register the team, please try again later"); } } } else { // Check for answer int answerId = -1; bool numberParsedSuccessfully = int.TryParse(messageText, out answerId); if (numberParsedSuccessfully && answerId >= 0) { TriviaPlayer triviaPlayer = await GetPlayer(activity); if (triviaPlayer != null) { if (triviaDatastore.PendingTriviaQuestions.ContainsKey(triviaPlayer.Id)) { TriviaAnswer triviaAnswer = new TriviaAnswer() { UserId = triviaPlayer.Id, QuestionId = triviaDatastore.PendingTriviaQuestions[triviaPlayer.Id], AnswerId = answerId }; TriviaAnswerResponse triviaAnswerResponse = await triviaApiClient.PostAnswerAsync(triviaAnswer); if (triviaAnswerResponse != null) { triviaDatastore.PendingTriviaQuestions.Remove(triviaPlayer.Id); if (triviaAnswerResponse.Correct) { await context.PostAsync($"{GetFirstName(triviaPlayer)}: That is correct!"); } else { await context.PostAsync($"{GetFirstName(triviaPlayer)}: I'm afraid that is not the correct answer. Better luck next time!"); } } else { await context.PostAsync("Sorry, something went wrong. Try again later"); } } else { await context.PostAsync("I haven't asked you a question yet."); await context.PostAsync(HelpMessage); } } else { await context.PostAsync("I'm sorry, I couldn't find your player profile. Are you sure you have registered?"); } } else { await context.PostAsync(HelpMessage); } } } context.Wait(MessageReceivedAsync); }
/// <summary> /// /// </summary> /// <param name="triviaPlayer"></param> /// <returns></returns> private string GetFirstName(TriviaPlayer triviaPlayer) { return(GetFirstElement(triviaPlayer?.Name)); }
public async Task SingleTriviaCommandAsync(CommandContext ctx, [Description("How many questions to ask. Leave blank for a single question.")] int questions = 1, [Description("The category to pick questions from. If you want this random, leave it blank or use an id of 0.")] QuestionCategory questionCategory = QuestionCategory.All) { var cfg = this._model.Configs.Find(ctx.Guild.Id); if (cfg is null) { cfg = new GuildConfig(ctx.Guild.Id); this._model.Configs.Add(cfg); await this._model.SaveChangesAsync(); } if (cfg.TriviaQuestionLimit <= 0) { cfg.TriviaQuestionLimit = 1; } int qNumber = questions; if (qNumber > cfg.TriviaQuestionLimit) { qNumber = cfg.TriviaQuestionLimit; await ctx.RespondAsync($"Set the question number to this server's question limit: {qNumber}"); } if (qNumber <= 0) { qNumber = 1; } var game = await TriviaController.StartGame(ctx.Channel.Id, qNumber, questionCategory); if (game is null) { await ctx.RespondAsync("Failed to start a new game - A game is already in progress!"); return; } try { var interact = ctx.Client.GetInteractivity(); await ctx.RespondAsync($"Starting a new game of trivia with {qNumber} questions!"); while (await game.PopNextQuestion(out TriviaQuestion? question)) { #pragma warning disable CS8602 // Dereference of a possibly null reference. // False positive. var mapped = question.GetMappedAnswers(); #pragma warning restore CS8602 // Dereference of a possibly null reference. var embed = new DiscordEmbedBuilder() .WithColor(DiscordColor.Purple) .WithTitle("Trivia!") .WithDescription("You have 20 seconds to answer this question! Type the number of the answer that is correct to win!") .AddField(question.QuestionString, mapped.Item1) .AddField("Difficulty", $"`{question.DifficultyString}`", true) .AddField("Category", question.CategoryString); await ctx.RespondAsync(embed: embed); var response = await interact.WaitForMessageAsync(x => x.ChannelId == ctx.Channel.Id && x.Author.Id == ctx.Member.Id, TimeSpan.FromSeconds(20)); if (response.TimedOut) { await ctx.RespondAsync($"The question wans't answered in time! The correct answer was: {question.PossibleAnswers[question.CorrectAnswerKey]}"); break; // Goto finally block } var trivia = this._model.TriviaPlayers.Find(response.Result.Author.Id); if (trivia is null) { trivia = new TriviaPlayer(response.Result.Author.Id); this._model.Add(trivia); } var answerString = response.Result.Content.ToLowerInvariant().Trim(); if (answerString == mapped.Item2.ToString() || answerString == mapped.Item3) { // Response is correct await ctx.RespondAsync($"Thats the correct answer! You earned {question.Worth.ToMoney()}"); var wallet = this._model.Wallets.Find(response.Result.Author.Id); if (wallet is null) { wallet = new Wallet(response.Result.Author.Id); await this._model.AddAsync(wallet); } wallet.Add(question.Worth); trivia.Points += question.Worth / 10; trivia.QuestionsCorrect++; } else { // Response is incorrect await ctx.RespondAsync($"Thats not the right answer! The correct answer was: {question.PossibleAnswers[question.CorrectAnswerKey]}"); trivia.Points--; trivia.QuestionsIncorrect++; } if (trivia.Username != ctx.Member.Username) { trivia.Username = ctx.Member.Username; } await this._model.SaveChangesAsync(); } } finally { TriviaController.EndGame(ctx.Channel.Id); await ctx.RespondAsync("Trivia Game Complete!"); } }