Create a dummy Jeopardy! Game With ChatGPT

Chee Hou
5 min readNov 28, 2023

--

I developed a simulated Jeopardy! game using .NET Core Web App and ChatGPT, which look like this:

The game presents a question along with four possible answers. The player selects one answer, clicks ‘confirm’, and the webpage then indicates whether the selected answer is correct or not. Below is the code that powers this functionality.”

This is the code behind.

 public class JeopardyQuestionsAndAnswer
{

public string? QuestionText { get; set; } = "";
public IDictionary<char, string> QuestionsOptions { get; set; } = new Dictionary<char, string>();

public char? Answer { get; set; }
public string? AnswerText { get; set; }

public char UserSelectedAnswer { get; set; }
public string? UserSelectedAnswerText { get; set; }
public bool UserAnswerIsCorrect { get; set; }

}

This is the JeopardyQuestionAndAnswerclass that will store the question, answer options, user selected answer and correct answer info.

  private const string OPENAI_ENDPOINT = "https://api.openai.com/v1/chat/completions"; //endpoint

This is the end point of the openAI we will call.

  var client = _clientFactory.CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", OPENAI_API_KEY);

var requestData = new
{
model = "gpt-3.5-turbo",
messages = new[]
{

new
{
role = "system",
content = "Create a trivia question with four multiple-choice answers labeled [A], [B], [C], and [D]. " +
"Follow the following format to provide question and answer: " +
"What is the capital of USA? \n\n [A] Washington DC, [B] New York, [C] Los Angeles, [D] Chicago. Correct Answer: [A],Washington DC."
}

}
};



var content = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");


var response = await client.PostAsync(OPENAI_ENDPOINT, content);

This is how I called the chatGPT API and get the response.

As you can see, I utilized ChatGPT to generate trivia questions, enforcing a specific format for both questions and answers. This approach simplifies the parsing of the JSON response, allowing for seamless integration into my object structure.

{
"id": "chatcmpl-8PsthuczTiFU9JrWN1DQeYaQtTsyy",
"object": "chat.completion",
"created": 1701179917,
"model": "gpt-3.5-turbo-0613",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Who was the first person to set foot on the moon?\n\n[A] Neil Armstrong\n[B] Buzz Aldrin\n[C] John Glenn\n[D] Alan Shepard\nCorrect Answer: [A] Neil Armstrong"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 80,
"completion_tokens": 41,
"total_tokens": 121
}
}

This is the JSON response from openAI. We only want the text from ‘content’ node.

  private void ParseQuestion(string json, JeopardyQuestionsAndAnswer Jeopartyqa)
{
var jsonData = JObject.Parse(json);
var content = jsonData["choices"][0]["message"]["content"].ToString();

// Split into question and the rest
int firstOptionIndex = content.IndexOf("[A]");
Jeopartyqa.QuestionText = content.Substring(0, firstOptionIndex).Trim();

// Remaining content including options
string remainingContent = content.Substring(firstOptionIndex);

// Markers for options and correct answer
string[] markers = new string[] { "[A]", "[B]", "[C]", "[D]", "Correct Answer:" };

// Process each option
for (int i = 0; i < markers.Length - 1; i++)
{
int startIndex = remainingContent.IndexOf(markers[i]) + 3; // Length of marker like '[A]'
int endIndex = remainingContent.IndexOf(markers[i + 1]);

if (startIndex < endIndex && startIndex >= 0 && endIndex >= 0)
{
string optionValue = remainingContent.Substring(startIndex, endIndex - startIndex).Trim().Trim(new char[] { ',', ' ' });
Jeopartyqa.QuestionsOptions.Add(markers[i].Trim('[', ']')[0], optionValue);
}
}

// Process correct answer
int correctAnswerIndex = remainingContent.IndexOf("Correct Answer:") + "Correct Answer:".Length;
string correctAnswerPart = remainingContent.Substring(correctAnswerIndex).Trim();
char answerKey = correctAnswerPart[1];
string answerText = correctAnswerPart.Substring(3).Split('.')[0].Trim();

Jeopartyqa.Answer = answerKey;
Jeopartyqa.AnswerText = answerText;
}

This process involves parsing the JSON data and storing the information in my class structure. Subsequently, the question and its answer options are displayed on the webpage.

When a user submits an answer, the system compares the selected answer with the correct one and displays the corresponding result on the result page.

 public IActionResult OnPostSubmit(char userSelectedAnswer, string jeopartyQAData)
{
JeopartyQA = JsonConvert.DeserializeObject<JeopardyQuestionsAndAnswer>(jeopartyQAData);
JeopartyQA.UserSelectedAnswer = userSelectedAnswer;


if (JeopartyQA.QuestionsOptions.TryGetValue(userSelectedAnswer, out string value))
{
JeopartyQA.UserSelectedAnswerText = value;
}

JeopartyQA.UserAnswerIsCorrect = JeopartyQA.Answer == userSelectedAnswer;



TempData["Jeoparty"] = JsonConvert.SerializeObject(JeopartyQA);


return RedirectToPage("/Game/Result");


}

If you find the questions too easy and wish to increase their difficulty, this can be achieved by altering the text sent to ChatGPT.

    content = "Create a question that suite for post graduate student level with four multiple-choice answers labeled [A], [B], [C], and [D]. " +
"Follow the following format to provide question and answer: " +
"What is the capital of USA? \n\n [A] Washington DC, [B] New York, [C] Los Angeles, [D] Chicago. Correct Answer: [A],Washington DC."

So this is the more difficult question based on my input.

Or you can specify certain area of questions, for example movies-related knowledge.

  content = "Create a question that about movies with four multiple-choice answers labeled [A], [B], [C], and [D]. " +
"Follow the following format to provide question and answer: " +
"What is the capital of USA? \n\n [A] Washington DC, [B] New York, [C] Los Angeles, [D] Chicago. Correct Answer: [A],Washington DC."

Then we can have a movies related question.

Remark:
1. The UI of my project might vary based on the response of chatGPT. You may see less than 4 options answers, this is because the response returned from ChatGPT do not follow my instruction, thus I unable to parse it correctly.

2. While the OpenAI API is not free, it is quite affordable. For instance, during the development of this dummy project, I called the API over 100 times and it cost me less than 1 dollar.

3. The questions generated by ChatGPT tend to repeat each time the website is launched. Further research into the API is necessary to ensure a unique set of questions for each session.

You may have my source from from Github.

*Please note that this project requires your own OpenAI API Key to function. You will need to add funds (I believe the minimum is 5 dollars) to obtain your API Key.

--

--

No responses yet