0%

JS地下城 6F 60秒算數遊戲

要求

  • 020 秒為 1位數計算 ,2140 秒為 2 位數計算,41~60 秒為 3 位數計算,加減乘除規則請用隨機產生,不可寫死題目,60 秒內可無限次數答題。
  • 040 秒答對加一分,4160 秒答對加五分,答錯扣一分,最多僅能扣到零分
  • 不可設計跳轉頁面,都得在同一頁內部切換頁面完成。

    攻略

  • 利用setInterval()達到每秒更新
  • 利用Math.floor() Math.random() 達成亂數規則

製作一個倒數計時器

這邊踩到的雷是換轉頁面時,setInterval()還在執行,
clearInterval(timeId),必須要宣告個變數接timeId
不可直接帶入,這裡卡了好久 😭😭 ,附上相關連結

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
let sec
let timeId

function getTime() {
if(main.classList[1]=='d-none')return
if(sec==0){
main.classList.add('d-none')
restart.classList.remove('d-none')
getStatus(main.classList[1])
return
}
else if(sec<=10){
sec -=1
time.textContent=`00 : 0${sec}`
}else{
sec -=1
time.textContent=`00 : ${sec}`
}
}

function getStatus(status) {
if(status!='d-none'){
timeId=setInterval(getTime,1000)

}else if(status=='d-none'){
clearInterval(timeId)
}
}

製作一個亂數選擇器

Math.random()會產生 0~1隨機小數,再利用Math.floor()取最大整數

1
2
3
4
5
6
Math.random(); // 0.23012228691419123 
Math.random(); // 0.8107096418156079

Math.floor(Math.random()); //回傳0
Math.floor(0.8888888); //回傳0

當我們把Math.random()*2放進Math.floor()中會得到 0、1 的結果。

1
2
3
4
(Math.random()*2 ) // 0.000...02~1.999...98
Math.floor(Math.random()*2); //回傳0或1
Math.floor(Math.random()*5); //回傳0或1或2或3或4
Math.floor(Math.random()*50); //回傳0或1或2或3...或49

我們來實作 min~max 之間的亂數,min 為最小值 max為最大值。

1
2
3
4
5
6
7
8
9
function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1))+min;
};

//會產生1~10之間的隨機亂數
getRandom(1,10);
//會產生100~500之間的隨機亂數
getRandom(100,500);