Vue

by luka kupunia

HTML

<div id="app">
  <div>
    <h1>Math Game</h1>
    <h2>
      {{ firstNumber }}
      {{operators[0] }}
      {{ secondNumber }}
      =
      <form @submit.prevent="getAnswer();">
        <input type="text" v-model="answer">
      </form>
      <h3>
        time: {{ time }}
      </h3>
      <h3>
        score: {{ score }}
      </h3>
    </h2>
  </div>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

Vue

new Vue({
  el: "#app",
  data: {
      operators: ['-','+'],
      firstNumber: Math.floor(Math.random() * 50),
      secondNumber: Math.floor(Math.random() * 50),
      time: 2400,
      answer: '',
      correcAnswer: null,
      score: 0,
      isPlaying: true
  },
  methods: {
  	getAnswer() {
        if (Number(this.answer) === this.correcAnswer) {
            this.firstNumber = Math.floor(Math.random() * 50)
            this.secondNumber = Math.floor(Math.random() * 50)
            this.correcAnswer = eval(this.firstNumber + this.operators[0] + this.secondNumber)
            this.score++
            this.time -= 200
            this.answer = null
        }else {
            alert('you lose, score: ' + this.score)
        }
    },
      test() {
          this.correcAnswer = eval(this.firstNumber + this.operators[0] + this.secondNumber)
      },
      startTime() {

          if(this.isPlaying){
              this.time --;
          }


          if (this.time < 0) {
              this.isPlaying = false
              alert('you lose, score: ' + this.score)
              location.reload()
              return
          }

          requestAnimationFrame(this.startTime)
      }
  },
  
  	mounted() {
            this.test()
            this.startTime()
        }
  
})