Advertisement
Guest User

Untitled

a guest
Aug 5th, 2015
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. // It's a bit messy, but it seems to work
  2.  
  3. function player(name) {
  4. this.name = name;
  5. this.questionCount = 0;
  6. this.number;
  7. }
  8.  
  9. player.prototype.setOther = function(other, otherNumber) {
  10. this.other = other;
  11. this.otherNumber = otherNumber;
  12. this.possibleNumbers = [otherNumber - 1, otherNumber + 1];
  13. }
  14.  
  15. player.prototype.knowsNumber = function() {
  16. if (this.number) {
  17. this.end();
  18. return true;
  19. }
  20.  
  21. // If more questions have been asked than the other person's number,
  22. // and they still don't know what they are, we're the higher number
  23. if (this.questionCount >= this.otherNumber) {
  24. this.number = this.possibleNumbers[1];
  25.  
  26. setTimeout(function() {
  27. this.other.knowsNumber();
  28. }.bind(this));
  29.  
  30. this.end();
  31.  
  32. return true;
  33. } else {
  34. this.questionCount++;
  35. setTimeout(this.ask.bind(this));
  36. }
  37. }
  38.  
  39. player.prototype.ask = function() {
  40. if (this.other.knowsNumber()) {
  41. // If they figured theirs out first, that means we're the lower number
  42. this.number = this.possibleNumbers[0];
  43. } else {
  44. this.questionCount++;
  45. }
  46. }
  47.  
  48. player.prototype.end = function() {
  49. console.log(this.name, this.number);
  50. }
  51.  
  52. var i = 0;
  53. var skew = 1;
  54. var inter = setInterval(function() {
  55. skew = (skew+1)%2;
  56. if (skew === 0) {
  57. i++;
  58. }
  59. if (i >= 10) {
  60. clearInterval(inter);
  61. }
  62. var player1 = new player("player1");
  63. var player2 = new player("player2");
  64.  
  65. // Associate players
  66. player1.setOther(player2, i+1-skew);
  67. player2.setOther(player1, i+skew);
  68.  
  69. // Kick off the questions
  70. console.log("--");
  71. console.log("Should be player1:" + (i+skew) + " player2:" + (i+1-skew));
  72. player1.ask();
  73. }, 100);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement