2012-08-01 158 views
3

我已經創建了這個javascript,它產生一個範圍從0到20的隨機數。我想要做的是創建一個文本字段,用戶有4次嘗試猜測生成的數字。我將如何做到這一點?需要幫助使用javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 
<title>Untitled 1</title> 
</head> 
<body> 
<form><input name="code" id="code" type="text" value="" ></input> 
<script type="text/javascript"> 
function makeid() { 
    return Math.floor(Math.random() * 20) 
} 
</script> 
<input type="button" style="font-size:9pt" value="Generate Code" onclick="document.getElementById('code').value = makeid()"> 
</input> 
</form> 
</body> 
</html> 
+1

這裏:) http://jsfiddle.net/r7M4n/ – NicoSantangelo 2012-08-01 04:58:08

回答

1

您可以使用全局跟蹤狀態。但是,這種安全性很弱,因爲用戶可以簡單地重新加載頁面來規避限制。那麼你真正需要做的是服務器端的跟蹤狀態(例如數據庫),然後使用AJAX調用瀏覽器上做檢查:)

<script type="text/javascript"> 
var count = 0; 
function makeid() { 
    count++; 
    if (count <= 4) { 
     return Math.floor(Math.random() * 20); 
    } 
    alert('Out of attempts'); 
} 
</script> 

編輯 道歉,我只回答了一半的問題。

<script type="text/javascript"> 
     var attempts = 0; 
     var secretValue = makeid(); // Calculate the secret value once, and don't vary it once page is loaded 
     function makeid() { 
      return Math.floor(Math.random() * 20); 
     } 
     function checkId(userValue) { 
      if (parseInt(userValue) == secretValue) { 
       alert('Correct'); 
      } 
      else { 
       attempts++; 
       if (attempts <= 4) { 
        alert('Wrong - try again'); 
       } 
       else { 
        alert('Out of attempts'); 
       } 
      } 
     } 
    </script> 

,然後更改你的點擊處理程序

onclick="checkId(document.getElementById('code').value);" 
+0

好的,謝謝你的幫助! – 2012-08-01 04:50:39

+2

OP並不是如何只產生四個隨機數字,而是如何限制用戶只有四次嘗試猜測它是什麼。 – RobG 2012-08-01 04:54:55

+0

嗯,用戶現在必須每次猜測一個新號碼 – mplungjan 2012-08-01 04:57:36

0

一種方法是將生成的數字放入隱藏的元素中。保持嘗試的次數,當用戶正確或4次嘗試時,顯示該值以及他們是否正確猜測。也許還會顯示嘗試次數。

包含一個重置按鈕來重置計數器並生成一個新的隱藏值。

0

而不是使用文本字段,爲什麼不嘗試使用prompt()功能?以下是控制流程的基本思路:

  1. 生成您的隨機數並將其存儲在變量中。
  2. 創建一些變量,如正確並將其設置爲false。
  3. 提示用戶猜測for loop(有4次迭代)
  4. 每次猜測後,檢查猜測是否與您存儲的號碼相符。如果是,則break正確設置爲true後提前退出循環。
  5. 在退出for循環時,alert用戶是基於正確的值贏得還是輸了。