簡體   English   中英

用 JavaScript 為學校作業創建一個猜字母游戲

[英]Creating a letter guessing game for school assignment in JavaScript

所以我一直堅持這個練習太久了,不知道我做錯了什么。 我在使用數組並與它們合並循環時遇到了困難。

作業是將 10 個字母放入一個數組中,讓用戶至少猜對一個字母。 3 次嘗試后告訴用戶他們已經丟失並終止代碼。

<!DOCTYPE html>
<html>
<head>
  <title>Exercise 5</title>
  <link rel="stylesheet" type="text/css" href="css/styles5.css"/>
</head>



<body>
  <!--E X C E R S I S E 5 !-->
  <section id="allContent">
    <div id="container">
      <div class="bar1"></div><div id="bar2"></div>
      <h1 id="excersize">E x c e r c i c e &ensp;5</h1>
      <div id="titleBox">
        <p id="titlePRG">Enter five words</p>
      </div>
      <input type="text"   id="textField">
      <form>
        <input type="button" value="Enter" class="button" onclick="getValue()">   
      </form>
      <div id="valueReturned">
        <p id="returnText"><p>
        </div>
        <a href="index6.html"><h3> Next Exercise </h3></a>
      </div>
      <img src ="blank-laptop-png-transparent-pictures-free-icons-graphic-transparent-library-laptop-png-4042_3027.png" alt="laptopGraphic">
  </section>
    <!--E N D   O F   E X C E R c I c E 5 !-->


            <!-- S C R I P T I N G !-->
            <script>
        function getValue(){
          var input = document.getElementById("textField").value;
          var letters  =  ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] ;
          var a = letters.indexOf(input);


          for(var attempts = 0; attempts < 3; attempts++){

            if(input == ""){
            document.getElementById("valueReturned").innerHTML = "No input!";
            }else if( a >= 0){
              document.getElementById("valueReturned").innerHTML = "You guessed right!";

             break;

            } else if(input != a && attempts == 0){
              document.getElementById("valueReturned").innerHTML = "Two tries left!";
            }else if(input != a && attempts == 1){
              document.getElementById("valueReturned").innerHTML = "One more try!";
            }else if(input != a && attempts == 2){
              document.getElementById("valueReturned").innerHTML = "That was your last try! Get lost!";
            }

            }

           }// end of function
   </script>
   </body>
   </html> 

所以如果用戶猜對了,我希望代碼停止運行或循環。 如果第一次嘗試的猜測是錯誤的,那么它應該顯示一條消息“還剩兩次嘗試!” 如果第二次嘗試的猜測是錯誤的,那么它應該顯示一條消息“剩下一次嘗試!” 等等...

我暫時沒有用 else 語句關閉我的條件,不確定是否需要。 我的 For 循環設置不正確嗎? 是我的 if, else if 條件不對嗎?

我非常需要你們的幫助!

讓我們來看看你的邏輯

<script>
        function getValue(){
          var input = document.getElementById("textField").value;
          var letters  =  ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] ;
          var a = letters.indexOf(input);

在這一點上,您打開了一個腳本標記並聲明了一個函數getValue 然后從 id 為"textField"的 html 元素中獲取輸入,用 10 個字母初始化一個letters數組,然后搜索input letters ,返回其索引。 但是,這會導致輸入僅被讀取一次。 然后它將執行您的 for 循環 3 次迭代,從而產生潛在的不需要的錯誤。

這么一想,

您的功能需要在某處啟動。 通過嵌入在 html 中,它將在輸入下的按鈕上發生onclick() 這意味着每次調用該函數時,都會讀取一次輸入,並且循環在同一輸入上運行三次 我將首先getValue函數之外創建一個變量——我們稱之為attempts這將允許我們在每次運行函數時更新變量。 然后擺脫 for 循環,並使用條件分支,例如

var attempts = 0;
function getValue(){
  var input = document.getElementById("textField").value;
  var letters  =  ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] ;
  var a = letters.indexOf(input);
  if (attempts < 3) {
    // check if input is right
    if (input != "" && a != -1) {
       alert("success");
    }
    attempts += 1;
  }
// no else statement needed to terminate the program
// simply don't handle occurrences of attempts greater than  3
}

請評論任何你不確定的東西

問題是您每次嘗試都在迭代 3 次嘗試

您需要對所有嘗試進行全局迭代。

換句話說,跟蹤函數外部的嘗試,否則每次調用該函數時,您都將嘗試重置為 3 - 它永遠不會失敗。

這是我對您的代碼的重構,它還修復了其他一些問題並對其進行了優化。

(() => {
    let attempts = 3,
        input_el = document.getElementById('textField'),
        result_el = document.getElementById('valueReturned');
    window.getValue = () => {
        let input = input_el.value,
        letters  =  ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
        correct = letters.includes(input),
        msg;

        if (!attempts)
            msg = 'No attempts left!';
        else if (!input)
            msg = "No input!";
        else if(!correct) {
            attempts--;
            switch (attempts) {
                case 2:
                    msg = 'Two tries left!'
                    break;
                case 1:
                    msg = 'One more try!';
                    break;
                case 0:
                    msg = 'That was your last try! Get lost!';
                    break;
            }
        } else
            msg = 'You guessed right!';

        result_el.innerHTML = msg;

    }
})();

小提琴

一些注意事項:

  • 指示性地命名您的變量
  • 將您的 JS 與您的 HTML 分開 - 將其放在專用的.js文件中。
  • 這些天使用let over var
  • 考慮集中事件處理而不是通過onclick屬性內聯 JS。 這也意味着我們不必在window上聲明一個全局函數供您的onclick引用。
  • 我們將整個內容包裝在一個 IIFE(立即調用的函數表達式)中,以防止對全局命名空間的污染。
  • 想想也不需要每次您事件觸發被復制。 我們不需要每次都從 DOM 中獲取對相同元素的引用——讓我們在函數之外這樣做。
  • array.includes(val)等價於array.indexOf(val) !== -1
  • 我還讓用戶無法進行 3 次以上的嘗試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM