//<script type="text/javascript">
var guess = (function() {
var code = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var randomize = function(a, b) {
return Math.random() < 0.5 ? -1 : 1;
};
var total = 10;
var remain;
return {
reset: function() {
// generate code;
this.code = [].concat(code);
this.code.sort(randomize);
this.code.length = 4;
console.log(this.code);
// reset flags;
remain = total;
},
play: function() {
var right = false;
var ans;
while (remain) {
while (!(ans = prompt("Guess it! remain:" + remain)));
ans = ans.split("");
document.writeln("<p>" + ans.join(",") + "</p>");
var varify = [].concat(this.code);
var standby = [];
this.a = 0;
this.b = 0;
for (var i = 0; i < 4; i++) {
if (ans[i] == varify[i]) {
this.a++;
varify[i] = -1;
} else {
standby.push(ans[i]);
}
}
for (var i = 0; i < standby.length; i++) {
if (varify.indexOf(parseInt(standby[i])) != -1)
this.b++;
}
if (this.a == 4) {
right = true;
break;
}
document.writeln("<p>a:" + this.a + " b:" + this.b + "</p>");
remain--;
}
if (right) {
switch (remain) {
default: alert("You win!");
}
} else {
alert("You lose! code is " + this.code.join(","));
}
}
}
})();
guess.reset();
guess.play();
//</script>