Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/dreancaste/TriviaPP/llms.txt

Use this file to discover all available pages before exploring further.

TriviaService is the brain of every TriviaPP game session. It generates TriviaQuestion objects on demand, blending a bank of 19 hand-crafted Spanish-language lore questions with dynamically assembled questions sourced from the live SWAPI API — covering character homeworlds, planet climates, and film directors. A deduplication guard tracks every question key used in the current session and automatically falls back to lore questions when SWAPI questions repeat.

TriviaQuestion Interface

Every question produced by this service conforms to the following interface, defined in trivia-question.model.ts:
export interface TriviaQuestion {
  question: string;       // The question text displayed to the player (in Spanish)
  options: string[];      // Array of 4 answer choices (shuffled)
  correctAnswer: string;  // The exact string from options[] that is correct
  category: string;       // "Lore" | "Personajes" | "Planetas" | "Películas"
}

Constructor / Dependencies

DependencyRole
SwapiServiceFetches people, planet, and film data from SWAPI
TranslationServiceTranslates English climate/terrain strings to Spanish
@Injectable({ providedIn: 'root' })
export class TriviaService {
  private usedQuestionKeys: string[] = [];
  constructor(
    private swapiService: SwapiService,
    private translationService: TranslationService
  ) {}
}

Lore Question Bank

The service embeds 19 hardcoded Spanish-language questions covering iconic Star Wars lore. These are always available, load instantly (no network request), and serve as the fallback pool when SWAPI questions are exhausted or duplicated. Topics include master/apprentice relationships, Sith identities, Order 66, planet homes, and key saga events.
When all 19 lore questions have been used in a session and a lore question is requested again, generateLoreQuestion() calls resetUsedQuestions() internally and starts the cycle over, ensuring the game never stalls.

Public Methods

generateQuestion()

The primary entry point for the game loop. Generates a single, deduplicated TriviaQuestion each time it is called.
async generateQuestion(): Promise<TriviaQuestion>
Selection logic:
ProbabilityQuestion typeData source
60% (random < 0.6)Lore questionHardcoded bank (19 questions, Spanish)
~13% eachPeople questionSWAPI /people/?page=1 + homeworld URL resolution
~13% eachPlanet questionSWAPI /planets/?page=1 + climate translated to Spanish
~13% eachFilm questionSWAPI /films/ director name
When a SWAPI question is selected, the service checks whether the generated question text is already in usedQuestionKeys. If it is, it retries with a different generator — up to 10 retries before falling back to a lore question. This prevents the same SWAPI question from appearing twice in a session without blocking gameplay. Every question returned (whether lore or SWAPI) is recorded in usedQuestionKeys by its question text.

resetUsedQuestions()

Clears the session deduplication list. Call this at the beginning of every new game so that questions from the previous session become eligible again.
resetUsedQuestions(): void
Failing to call resetUsedQuestions() at the start of a new game session means the deduplication guard will carry over used keys from the previous game, potentially exhausting the SWAPI question pool faster than expected.

Private Methods (Internal API)

These methods are internal implementation details and are not part of the public API surface. They are described here for contributors.
MethodDescription
generateLoreQuestion()Picks a random unused question from the hardcoded bank; resets and retries if all are used
generatePeopleQuestion()Fetches page 1 of people, picks a random character with a homeworld, resolves the homeworld URL, and builds “¿De qué planeta es ?” with 4 planet name options
generatePlanetQuestion()Fetches page 1 of planets, filters out unknowns, picks a random planet, translates its climate to Spanish via TranslationService, and builds “¿Cuál es el clima de ?”
generateFilmQuestion()Fetches all films, picks a random one, and builds “¿Quién dirigió la película ''?” with 4 director name options
buildUniqueOptions(correct, wrongs, total)Deduplicates and shuffles answer options, ensuring correctAnswer is always included; pads to total (default 4) if necessary
shuffleArray(array)Returns a new array with elements in random order using Array.sort(() => Math.random() - 0.5)
getRandomItems(array, count)Returns count randomly selected items from array using a sort-based shuffle
capitalizeFirst(text)Uppercases the first character of a string; returns "" for falsy input
markQuestionAsUsed(question)Pushes the question’s question text into usedQuestionKeys and returns the question unchanged

Usage Example

import { TriviaService } from './services/trivia.service';
import { TriviaQuestion } from './models/trivia-question.model';

@Component({ ... })
export class GamePage implements OnInit {
  currentQuestion: TriviaQuestion | null = null;
  score = 0;
  correctCount = 0;

  constructor(private triviaService: TriviaService) {}

  ngOnInit() {
    // Always reset deduplication state at the start of a new game
    this.triviaService.resetUsedQuestions();
    this.loadNextQuestion();
  }

  async loadNextQuestion() {
    this.currentQuestion = await this.triviaService.generateQuestion();
    // currentQuestion.category will be one of:
    //   "Lore" | "Personajes" | "Planetas" | "Películas"
  }

  async onAnswer(selected: string) {
    if (!this.currentQuestion) return;

    if (selected === this.currentQuestion.correctAnswer) {
      this.score += 10;
      this.correctCount++;
    }

    await this.loadNextQuestion();
  }
}
generateQuestion() makes network calls for SWAPI questions. Await it inside a loading state to avoid a blank question card flickering on screen between questions.

Build docs developers (and LLMs) love