简体   繁体   中英

Can't understand the logic of a JavaScript code block [Bulls and Cows game]

I'm in need of a little help. I need to write a detailed interpretation of a JavaScript code for a game of Bulls and Cows and I don't understand exactly what's happening in the main logic block. This is the block:

        //Check Bull,Cow,Try Again
    var bull, cow;

    if (check) {
        bull = 0;
        cow = 0;

        for (var i = 0; i < getNum.length; i++) {
            for (var k = 0; k < userText.length; k++) {
                if ((getNum[i] == userText[k]) && (i == k)) {
                    bull++;
                } else if ((getNum[i] == userText[k]) && (i != k)) {
                    cow++;
                }
            }
        }

        if (bull == 0 && cow == 0) {
            setText.innerHTML += "try again\n";
        } else if (bull == numLength) {
            setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
        } else {
            setText.innerHTML += userText + " : ";
            setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
        }
    }
    check = true;

}

Also here's the entire program in case you need to check the interconnection of variables and such:

var getNum = new Array();
var numLength;
var check = true;

window.onload = function() {
    numLength = document.getElementById("select").value;
    setNumber();
}

/*Get random numbers
Numbers must not be the same as each other
(found this entire codeblock on the internet
and adapted it, not gonna lie)*/
function setNumber() {
    var random;
    getNum.splice(0, getNum.length);
    while (getNum.length < numLength) {
        random = Math.floor(Math.random() * 9) + 1;

        for (var i = 0; i < getNum.length; i++) {
            if (getNum[i] == random) {
                check = false;
                break;
            }
        }

        if (check) {
            getNum.push(random);
        }
        check = true;
    }
}

//Check user number
function checkUserText() {
    var userText = document.getElementById("userText").value;
    var setText = document.getElementById("textArea");
    //Check if userText is number
    for (var i = 0; i < userText.length; i++) {
        if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57
                || userText.length != numLength) {
            setText.innerHTML += "Type only" + numLength + " numbers!\n";
            check = false;
            break;
        }
    }

    //Check Bull,Cow,Try Again
    var bull, cow;

    if (check) {
        bull = 0;
        cow = 0;

        for (var i = 0; i < getNum.length; i++) {
            for (var k = 0; k < userText.length; k++) {
                if ((getNum[i] == userText[k]) && (i == k)) {
                    bull++;
                } else if ((getNum[i] == userText[k]) && (i != k)) {
                    cow++;
                }
            }
        }

        if (bull == 0 && cow == 0) {
            setText.innerHTML += "try again\n";
        } else if (bull == numLength) {
            setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
        } else {
            setText.innerHTML += userText + " : ";
            setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
        }
    }
    check = true;

}

//change difficulty
function difficulty() {
    numLength = document.getElementById("select").value;
    reload();
}

//restart game
function reload() {
    setNumber();
    document.getElementById("textArea").innerHTML = "";
}

I understand the general idea of the block but I can't see the specifics, I can't see the logic behind it, if someone could explain this block to me or make a quick flow chart I would be more than grateful.

  var getNum = new Array(); var numLength; var check = true; window.onload = function() { numLength = document.getElementById("select").value; setNumber(); } /*Get random numbers Numbers must not be the same as each other (found this entire codeblock on the internet and adapted it, not gonna lie)*/ function setNumber() { var random; getNum.splice(0, getNum.length); while (getNum.length < numLength) { random = Math.floor(Math.random() * 9) + 1; for (var i = 0; i < getNum.length; i++) { if (getNum[i] == random) { check = false; break; } } if (check) { getNum.push(random); } check = true; } } //Check user number function checkUserText() { var userText = document.getElementById("userText").value; var setText = document.getElementById("textArea"); //Check if userText is number for (var i = 0; i < userText.length; i++) { if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57 || userText.length != numLength) { setText.innerHTML += "Type only" + numLength + " numbers!\\n"; check = false; break; } } //Check Bull,Cow,Try Again var bull, cow; if (check) { bull = 0; cow = 0; for (var i = 0; i < getNum.length; i++) { for (var k = 0; k < userText.length; k++) { if ((getNum[i] == userText[k]) && (i == k)) { bull++; } else if ((getNum[i] == userText[k]) && (i != k)) { cow++; } } } if (bull == 0 && cow == 0) { setText.innerHTML += "try again\\n"; } else if (bull == numLength) { setText.innerHTML += numLength + " bulls! you won the game!!!\\nclick restart to play again\\n"; } else { setText.innerHTML += userText + " : "; setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\\n"); } } check = true; } //change difficulty function difficulty() { numLength = document.getElementById("select").value; reload(); } //restart game function reload() { setNumber(); document.getElementById("textArea").innerHTML = ""; } 
 <!DOCTYPE html> <html> <head> <title>Bulls and Cows</title> <script type="text/javascript" src="operation.js"> </script> <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"> <style> h2 { font-family: Lobster; color: blue; } body { background-color: #cccccc } </style> </head> <body> <h2>Bulls and Cows</h2> <label for="userText">Type here: </label> <input type="text" id="userText"/> <br /> <button id="ch" onclick="checkUserText()">check</button> <button id="re" onclick="reload()">restart</button> Length : <select id="select" onchange="difficulty()"> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> <option>8</option> <option>9</option> <option>10</option> </select> <br /> <textarea id="textArea" rows="20" cols="30" readonly="readonly" style="overflow-y: scroll"></textarea> </body> </html> 

// ok lets assume the getNum.length is 3 
// and the random getNum is 123
// and user enters 321 and clicks check


var bull, cow;

if (check) {
    bull = 0;
    cow = 0;



    for (var i = 0; i < getNum.length; i++) {
      // this will loop three times
      // in the first iteration getNum[i] == 1 
      // the second iteration getNum[i] == 2 
      // the third iteration getNum[i] == 3 


        for (var k = 0; k < userText.length; k++) {

          // for each iteration of getNum it will iterate all user input (also 3 times)
          // so 3 times per iteration of getNum, clear so far? good 
          // so at first iteration userText[k] == 3
          // so at second iteration userText[k] == 2
          // so at third iteration userText[k] == 1
          // while i keeps the value of the outer loop

            // this expression checks if user input matches the same number on the same position in getNum
            if ((getNum[i] == userText[k]) && (i == k)) {
                // in the second iteration of the outer loop its a bull because 
                // getNum[i] == 2 == userText[k] == 2 AND 1 == 1 (number and position of number/index is matching the random number
                bull++;
            } else if ((getNum[i] == userText[k]) && (i != k)) {
                // in the first and last iteration of the outer loop its a cow because
                // getNum[i] == 1/2 == userText[k] == 1/2 AND 0/2 is NOT 2/0 (number is matching but position not matching) 
                cow++;
            }

            // if the getNum[i] doesnt exist at all in userText, neither cow or bull will count up
        }
    }

    if (bull == 0 && cow == 0) {
        // so if no number matched - try again
        setText.innerHTML += "try again\n";
    } else if (bull == numLength) {
        // if all numbers and positions (cow) matched you won
        setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
    } else {
        // else show how many "cows" and "bulls"
        setText.innerHTML += userText + " : ";
        setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
    }

    // so the output of above assumption would be 
    // 1 bull, 2 cows
    // cool game ;-)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM