<bigwig> service: guess


service {
  protected shared int plays ;
  
  resource HiScore ;
  
  shared int record;
  shared string holder;
  html GuessDoc = <html>
    Please guess a number between 0 and 99:
    <input name="guess" type="text" size=2 maxlength=2>
  </html>;
  html Again = <html>
    That is not correct. Try a <b><[correction]></b> number:
    <input name="guess" type="text" size=2 maxlength=2>
  </html>;
  html Done = <html>
    You got it, using <b><[trys]></b> guesses.
  </html>;
  html Record = <html>
    That makes you the new record holder,
    beating the old record of <[old]> guesses.
    <p>
    Please enter your name for the hi-score list
    <input name="name" type="text" size=20>
  </html>;
  html HiScoreDoc = <html>
    In <[plays]> plays of this game, the record
    holder is <b><[holder]></b> with <b><[record]></b> guesses.
  </html>;
  
  session Play() {
    int number, guesses, guess, r;
    
    number = random(100);
    writer (plays) {
      plays++;
    }
    show GuessDoc receive [guess=guess];
    guesses = 1;
    while (guess != number) {
      if (guess > number) {
        show Again <[correction="lower"] receive [guess=guess];
      }
      if (guess < number) {
        show Again <[correction="higher"] receive [guess=guess];
      }
      guesses++;
    }
    reader (HiScore) r = record;
    if (r == 0 || r >= guesses) {
      string name;
      
      show Record <[old=r] receive [name=name];
      writer (HiScore) {
        holder = name;
        record = guesses;
      }
    }
    exit <html>Thank you for playing this exciting game</html>;
  }
  
  session HiScore() {
    int p, r;
    string h;
    
    reader (plays) {
      p = plays;
    }
    reader (HiScore) {
      r = record;
      h = holder;
    }
    exit HiScoreDoc <[plays=p, holder=h, record=r];
  }
}