1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OpenTDBとは何か

Last updated at Posted at 2024-03-16

OPENTDB とは何か

Open Trivia Database の略で,オープンソースのトリビアデータベースです.
トリビアとは,雑学や豆知識のことで,簡単に言うとクイズの問題です.
つまり,この api を使えばクイズアプリを作っているときに,クイズのデモ問題をわざわざ用意しなくて良くなります!

使い方

https://opentdb.com/api_config.php

ここにアクセスして,クイズのカテゴリーや難易度,問題数などを設定して,その URL を使って GET リクエストを送ると,クイズの問題が返ってきます.

公式 HP で条件を入力すると,その条件に合った URL が生成されます.

https://opentdb.com/api_config.php

言語はVue.jsを使っています.

<template>
  <div>
    <h1>クイズアプリ</h1>
    <div v-if="quiz">
      <p>{{ quiz.question }}</p>
      <button v-for="(answer, index) in quiz.answers" :key="index" @click="submitAnswer(answer)">
        {{ answer }}
      </button>
    </div>
    <p v-else>読み込み中...</p>
    <p>スコア: {{ score }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      quiz: null,
      score: 0
    };
  },
  created() {
    this.getQuiz();
  },
  methods: {
    submitAnswer(answer) {
      if (answer === this.quiz.correctAnswer) {
        this.score++;
      }
      this.getQuiz();
    },
    async getQuiz() {
      let data;
      do {
        const response = await fetch('https://opentdb.com/api.php?amount=1&type=multiple&encode=base64');
        data = await response.json();
      } while (data.response_code === 5);

      const quizData = data.results[0];
      this.quiz = {
        question: atob(quizData.question),
        answers: this.shuffleArray([...quizData.incorrect_answers.map(answer => atob(answer)), atob(quizData.correct_answer)]),
        correctAnswer: atob(quizData.correct_answer)
      };
    },
    shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
    }
  }
};
</script>

api

使用した api はこれです
https://opentdb.com/api.php?amount=1&type=multiple&encode=base64

簡単に説明すると,

Parameter Description
amount 問題数
type 問題の形式(選択か yes,no か)
encode エンコードの種類

エンコードをしておかないと,"&quot;のようになってしまうので,エンコード・デコードを行っています.

response_code

response_codeが 5 のときは,問題取得に失敗したときなので,再度リクエストを送るようにしています.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?