试图创造一个简单的“类似主脑”的游戏

时间:2015-06-11 08:16:31

标签: javascript algorithm

我一直在研究这个简单的数字mastermindlike游戏。目前,我有correct_number_correct_spot计数器工作,但没有correct_number_wrong_spot计数器。我仍然得到奇怪的读数,我无法弄清楚导致错误的原因。这是代码。

<!doctype html>
<html>
<head>
<script type="text/javascript" src="mastermind.js"></script>
</head>
<body onload="doSomeShit();">

    Submit Guess:<input type="text" id="guess">
    <button id="submit_button">Submit</button>
<div id="mymoves">

</div>

</body>
</html>

和js:

var right_answer=[1,2,3,4];
var max_turn= 12;
var current_turn=0;
var player_guess= [];

function make_move(guess){
    var myguess = document.getElementById("mymoves");

    var correct_number_correct_spot= 0;
    var correct_number_wrong_spot= 0;
    for(var i = 0; i < 4; ++i)
    {
        console.log(guess.split("").contains(i));
        if(right_answer[i] == guess[i])
            ++correct_number_correct_spot;
        else if(right_answer[i] !== guess[i] && guess.split("").contains(i))
            ++correct_number_wrong_spot;
        }




    myguess.innerHTML += correct_number_correct_spot + " were right!" +correct_number_wrong_spot+ "there but not in the right order";

}

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

function doSomeShit(){
    var btn = document.getElementById("submit_button");
    btn.onclick = function(){ // this makes button clickable
        var x = document.getElementById("guess").value; // gets the input value
        make_move(x);
    }
}

现在,我的correct_number_correct_spot检查程序正在运行,但是我的correct_number_wrong_spot计数器已关闭,并且在for循环中无法正常工作。换句话说,它似乎缺少检查而不是与输入的猜测相对应。换句话说,现在的默认答案是[1,2,3,4],所以如果输入1234,应该说4是正确的!“0但不是正确的顺序。如果我输入4321则应该说0是对!4但不是正确的顺序。等等。 编辑**我最终得到了更好的工作,但仍然没有完全,使用来自jquery的代码:

我确实通过这段代码得到了jquery:if(answers [i] == guess [i]){

++correct_number_correct_spot;
            }
        else if(answ[i] !== guess[i] && $.inArray(guess[i], answ) !== -1){
            ++correct_number_wrong_spot;
           }

现在唯一的问题是,当说答案是[3,6,7,8]并且您猜测为9,3,3,0时,它会告诉您有2个但没有正确的顺序。所以它仍然关闭。

1 个答案:

答案 0 :(得分:1)

if(right_answer[i] !== guess[i] && guess.split("").contains(i)

这似乎检查i中是否包含非常值guess。这很奇怪,因为i只是从0到3的索引,而不是实际的数字。我认为这应该是

if(right_answer[i] !== guess[i] && guess.split("").contains(right_answer[i])

另外我建议你将代码分成两部分:首先拆分guess,使其格式与right_answer相同(即数组),然后再计算答案