Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // It's a bit messy, but it seems to work
- function player(name) {
- this.name = name;
- this.questionCount = 0;
- this.number;
- }
- player.prototype.setOther = function(other, otherNumber) {
- this.other = other;
- this.otherNumber = otherNumber;
- this.possibleNumbers = [otherNumber - 1, otherNumber + 1];
- }
- player.prototype.knowsNumber = function() {
- if (this.number) {
- this.end();
- return true;
- }
- // If more questions have been asked than the other person's number,
- // and they still don't know what they are, we're the higher number
- if (this.questionCount >= this.otherNumber) {
- this.number = this.possibleNumbers[1];
- setTimeout(function() {
- this.other.knowsNumber();
- }.bind(this));
- this.end();
- return true;
- } else {
- this.questionCount++;
- setTimeout(this.ask.bind(this));
- }
- }
- player.prototype.ask = function() {
- if (this.other.knowsNumber()) {
- // If they figured theirs out first, that means we're the lower number
- this.number = this.possibleNumbers[0];
- } else {
- this.questionCount++;
- }
- }
- player.prototype.end = function() {
- console.log(this.name, this.number);
- }
- var i = 0;
- var skew = 1;
- var inter = setInterval(function() {
- skew = (skew+1)%2;
- if (skew === 0) {
- i++;
- }
- if (i >= 10) {
- clearInterval(inter);
- }
- var player1 = new player("player1");
- var player2 = new player("player2");
- // Associate players
- player1.setOther(player2, i+1-skew);
- player2.setOther(player1, i+skew);
- // Kick off the questions
- console.log("--");
- console.log("Should be player1:" + (i+skew) + " player2:" + (i+1-skew));
- player1.ask();
- }, 100);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement