Nuxt.jsで作る数学ゲーム

Nuxt.jsを使用して作成した簡単なゲームのコード例です。

このゲームは、簡単な数学の問題を解くものです。

  <template>
  <div>
    <div v-if="!gameOver">
      <h2>{{ currentQuestion }}</h2>
      <form @submit.prevent="checkAnswer">
        <input type="number" v-model="userAnswer" required>
        <button>Submit</button>
      </form>
    </div>
    <div v-else>
      <h2>Game Over!</h2>
      <p>Your final score is {{ score }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      gameOver: false,
      currentQuestion: '',
      correctAnswer: 0,
      userAnswer: null,
      score: 0,
      maxQuestions: 10,
      currentQuestionNumber: 0,
    }
  },
  mounted() {
    this.getNextQuestion()
  },
  methods: {
    getNextQuestion() {
      if (this.currentQuestionNumber >= this.maxQuestions) {
        this.gameOver = true
        return
      }

      const a = Math.floor(Math.random() * 10) + 1
      const b = Math.floor(Math.random() * 10) + 1
      this.currentQuestion = `${a} + ${b}`
      this.correctAnswer = a + b
      this.currentQuestionNumber++
    },
    checkAnswer() {
      if (parseInt(this.userAnswer) === this.correctAnswer) {
        this.score++
      }
      this.getNextQuestion()
    },
  },
}
</script>

このゲームでは、 data() でゲームに必要な変数を初期化し、 mounted() で最初の問題を表示します。

getNextQuestion() メソッドは、ランダムな2つの数字を選んで、足し算の問題を作成し、正解を計算します。

checkAnswer() メソッドは、ユーザーの答えが正しいかどうかをチェックし、スコアを更新します。

v-if と v-else を使って、ゲームが終了した後にスコアを表示します。

Next Post Previous Post