无法理解JavaScript代码块的逻辑[牛与牛游戏]

千里眼

我需要一点帮助。我需要为Bulls and Cows游戏编写JavaScript代码的详细解释,但我不完全了解主要逻辑块中发生的情况。这是块:

        //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;

}

另外,这里是整个程序,如果您需要检查变量的相互连接,例如:

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 = "";
}

我了解该块的一般概念,但是我看不到具体细节,也看不到它背后的逻辑,如果有人可以向我解释此块或制作快速流程图,我将不胜感激。

	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 ;-)
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章