需要幫助瞭解如何做到以下幾點:數字遊戲 - 隨機
- 每2秒的間隔,這兩個數字將生成一個包含整數值的隨機數從1到3
- 在按下「匹配「按鈕,如果兩個數字相同,則綠色標籤上的數字加1。
- 按下」匹配「按鈕後,如果兩個數字不同,紅色標籤上的數字增加1。
- 如果兩個隨機生成的數字相同,並且用戶沒有按t他在2秒鐘內「匹配」按鈕,紫色標籤上的數字增加1.
- 增強評分系統以確保綠色標籤和紅色標籤只會增加1,即使用戶在其中按下多次間隔2秒。
代碼:被製成
每2秒間隔
var no1, no2; function randomize(){ no1 = Math.ceil(Math.random()*3); no2 = Math.ceil(Math.random()*3); } function print(){ $("#number1 > span").text(no1); $("#number2 > span").text(no2); } function check(){ if (no1 == no2){ alert("Both numbers are the same") } if (no1 != no2){ alert("Both numbers are the different") } } $().ready(function(){ randomize() print() $(":input").click(function(){ if (no1 == no2){ alert("Both numbers are the same") } if (no1 != no2){ alert("Both numbers are the different") } randomize() print() }) })
改進,這兩個數字(即數1和2號)將產生含有整數隨機數值從5到6.
對於每個隨機數ge毫不費力,2秒間隔將減少0.1秒。
隨機速度文本將顯示生成的每個隨機數的當前秒間隔。
一旦間隔達到0.8秒,javascript警報框將顯示消息「間隔已達0.8秒」。
當用戶關閉警報時,隨機速度文本被重置爲初始值,並重新開始爲每個間隔隨機生成兩個數字的速度。
目前代碼
var no1, no2, correctScore, wrongScore, missedScore, generatedNum, delay
function updateScreen(disabled) {
$('#correctScore').text(correctScore);
$('#wrongScore').text(wrongScore);
$('#missedScore').text(missedScore);
$('#generatedNum > span').text(generatedNum);
$("#number1 > span").text(no1);
$("#number2 > span").text(no2);
$(":input").val(generatedNum >= generateTotal ? "START!" : "MATCH!");
$(":input").prop('disabled', disabled);
}
function generate() {
if (no1 == no2 && !$(":input").prop('disabled')) ++missedScore;
if (generatedNum >= generateTotal) {
updateScreen(false); // needed to show missedScore.
if (confirm('The interval has reached 0.8 seconds')) start();
return; // exit
}
no1 = 5 + Math.floor(Math.random()*2);
no2 = 5 + Math.floor(Math.random()*2);
++generatedNum;
updateScreen(false);
setTimeout(generate, delay *= 0.95);
}
function start() {
correctScore = wrongScore = missedScore = generatedNum = 0;
delay = 2000;
updateScreen(true);
generate();
}
function check() {
if (generatedNum >= generateTotal) return start(); // Start pressed
if (no1 == no2) {
++correctScore;
} else {
++wrongScore;
}
updateScreen(true); // disable button
}
$(function(){
$(":input").click(check);
start();
});
$(function(){
$(":input").click(check);
start();
});
閱讀有關'setInterval'和/或' setTimeout'。 – trincot
感謝提示(: – user5992661
@trincot試過,我正確應用?https://jsfiddle.net/k58bbpf3/#&togetherjs=QRsbUQdPER – user5992661