JavaScript学习:逻辑猜数游戏

≯℡__Kan透↙ 提交于 2020-03-02 02:37:18

一、游戏规则

逻辑猜数游戏也叫猜数字游戏,游戏的规则非常简单:由系统给出一个没有重复数字的四位数(第一位不为0),玩家每次猜一个数,系统根据这个数字判断:位置正确的数字个数(记为A)、数字正确但位置不正确的数字个数(记为B)。

在本程序中,玩家最多有8次机会猜测,如果第8次仍未猜出正确答案,则游戏失败。

二、页面代码

建立一个文件bulls_and_cows.html,里面输入下面代码:

<html>
  <head>
    <title>JS学习 - 逻辑猜数</title>
  </head>
  <style type="text/css">
      table
      {
          border-spacing: 0 0;
          border-collapse: collapse;
          font-size: 10pt;
      }
      table th
      {
          background: #3399FF;
          text-align: center;
          text-decoration: none;
          font-weight: normal;
          padding: 3px 6px 3px 6px;
          width:200px;
      }
      table td
      {
          vertical-align: top;
          text-align: center;
          padding: 3px 6px 3px 6px;
          margin: 0px;
          border: 1px solid #3399FF;
      }
  </style>
  <body>
    请输入你猜测的答案
    <input type="text" id="myGuess" onkeydown="keydown();" />
    <input type="button" id="submit" value="提交结果" onclick="submit();" />
    <input type="button" id="reset" value="重新开始" onclick="restart();" />
    <input type="button" id="cheat" value="显示答案" disabled="true" onclick="cheat();" />
    <hr>
    <table id="console">
      <tr>
        <th>序号</th>
        <th>我的猜测</th>
        <th>线索</th>
      </tr>
    </table>
    <br />
    <div id="result"></div>
    <script>

      var counter = 1;
      var answer = "";

      function submit() {
          //输入合法性校验
          var myGuess = document.getElementById("myGuess").value;
          if (myGuess.trim() == "") {
              alert("未输入任何数据");
              return;
          } else if (!/^(?!.*?(\d).*?\1.*?$)\d+$/.test(myGuess) || myGuess.length != 4) { 
              alert("请输入四个不重复的数字");
              return;
          }
          if (counter == 1) {
              answer = generateAnswer();
              document.getElementById("cheat").disabled = false;
          }
          //提交数据
          var table = document.getElementById("console");
          var root = table.insertRow(table.rows.length);
          var c1 = root.insertCell(0);
          c1.innerHTML = counter;
          var c2 = root.insertCell(1);
          c2.innerHTML = myGuess;
          var c3 = root.insertCell(2);
          var hint = getHint(answer, myGuess);
          c3.innerHTML = hint;
          if (hint == "4A0B") {
              victory();
          } else if (counter == 8) {
              defeat();
          }
          counter++;
          document.getElementById("myGuess").value = ""; //清空输入框数据
      }

      //获胜
      function victory() {
          document.getElementById("result").innerHTML = "恭喜你,猜对了";
          document.getElementById("myGuess").value = "";
          document.getElementById("myGuess").readOnly = true;
          document.getElementById("submit").disabled = true;
          document.getElementById("cheat").disabled = true;
      }

      //直接查看答案
      function cheat() {
          document.getElementById("result").innerHTML = "正确答案是【" + answer + "】";
          document.getElementById("myGuess").value = "";
          document.getElementById("myGuess").readOnly = true;
          document.getElementById("submit").disabled = true;
          document.getElementById("cheat").disabled = true;
      }

      //失败
      function defeat() {
          document.getElementById("result").innerHTML = 
            "猜测次数超过限制,解题失败,正确答案是【" + answer + "】";
          document.getElementById("myGuess").value = "";
          document.getElementById("myGuess").readOnly = true;
          document.getElementById("submit").disabled = true;
          document.getElementById("cheat").disabled = true;
      }

      //重新开始游戏
      function restart() {
          //清空table
          var table = document.getElementById("console");
          while (table.rows.length > 1) {
            table.deleteRow(1);
          }
          //按钮可用性设置
          document.getElementById("result").innerHTML = "";
          document.getElementById("myGuess").value = "";
          document.getElementById("myGuess").readOnly = false;
          document.getElementById("submit").disabled = false;
          document.getElementById("cheat").disabled = true;
          //重置参数
          counter = 1;
          answer = "";
      }

      //生成随机数
      var getRand = function (begin, end) {
          return Math.floor(Math.random() * (end-begin)) + begin;
      }

      //生成一个由不同数字组成的四位数
      var generateAnswer = function() {
          var a, b, c, d;
          a = getRand(1, 10);
          do {
            b = getRand(0, 10);
          } while (b == a);
          do {
            c = getRand(0, 10);
          } while (c == b || c == a);
          do {
            d = getRand(0, 10);
          } while (d == c || d == b || d == a);
          //console.log(a.toString() + b + c + d);
          return a.toString() + b + c + d;
      }

      //获取线索
      var getHint = function(secret, guess) {
          if (secret === null || guess === null || secret.length != guess.length) {
              return "";
          }
          var countA = 0;
          var countB = 0;
          var count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
          for (var i = 0; i < secret.length; i++) {
              if (secret[i] == guess[i]) {
                  countA++;
              } else {
                  count[secret[i]]++;
                  if (count[secret[i]] <= 0) {
                      countB++;
                  }
                  count[guess[i]]--;
                  if (count[guess[i]] >= 0) {
                      countB++;
                  }
              }
          }
          return countA + "A" + countB + "B";
      }

      //在文本框输入完毕后按下回车视同提交
      function keydown() {
          if (event.keyCode == 13) {
              var button = document.getElementById("submit");
              button.click();
          } 
      }

    </script>
  </body>
</html>

三、效果演示

使用Firefox浏览器(版本号43.0.4)打开bulls_and_cows.html后,效果如下图所示:

END

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!