Created
July 6, 2013 17:08
-
-
Save mutoo/5940540 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment