Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into #59
Browse files Browse the repository at this point in the history
  • Loading branch information
Carlos Fernández Martínez committed Feb 28, 2025
2 parents f1dda8f + 9f85f5d commit d0f5b4a
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 additions & 15 deletions gameservice/routers/RouterQuestionRetriever.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,38 @@ router.get('/game/:numQuestions?/:numOptions?', async (req, res) => {
const numQuestions = parseInt(req.params.numQuestions, 10) || 3;
const numOptions = parseInt(req.params.numOptions, 10) || 3;

// Retrieve all questions from the database
const allQuestions = await Question.find();
// Query: get random questions from the database to be used in the game
const gameQuestions = await Question.aggregate([
{ $sample: { size: numQuestions } }
]);

if (allQuestions.length < 3) {
return res.status(400).json({ error: 'No hay suficientes preguntas en la base de datos' });
if (gameQuestions.length < numQuestions) {
return res.status(400).json({ error: 'Not enough questions in DB.' });
}

const selectedQuestions = allQuestions.sort(() => 0.5 - Math.random()).slice(0, numQuestions);

const formattedQuestions = selectedQuestions.map(q => {
// Obtain random fake answers
let fakeAnswers = allQuestions
.filter(item => item.answer !== q.answer)
.map(item => item.answer);

// Select random incorrect answers and mix them with the correct answer
fakeAnswers = fakeAnswers.sort(() => 0.5 - Math.random()).slice(0, numOptions - 1);
const formattedQuestions = await Promise.all(gameQuestions.map(async q => {
// Obtain random fake answers from the database excluding the correct answer
const fakeAnswersDocs = await Question.aggregate([
{ $match: { answer: { $ne: q.answer } } },
{ $sample: { size: numOptions - 1 } }
]);

if (fakeAnswersDocs.length < numOptions - 1) {
throw new Error('Not enough questions to generate responses.');
}

// Create a pool of fake answers and select a random subset of them to be used as options
const fakeAnswers = fakeAnswersDocs.sort(() => 0.5 - Math.random()).slice(0, numOptions - 1).map(q => q.answer);

// Shuffle the correct answer with the fake answers
const answers = [q.answer, ...fakeAnswers].sort(() => 0.5 - Math.random());

return {
image_name: `/images/${q._id}.jpg`,
answers,
right_answer: q.answer
};
});
}));

res.status(200).json(formattedQuestions);

Expand Down

0 comments on commit d0f5b4a

Please sign in to comment.