<bigwig> service: guess2


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 guesses, guess, r;
    int low_number = -1;
    int high_number = 100;
    bool done;
    string correction;
    
    writer (plays) {
      plays++;
    }
    show GuessDoc receive [guess=guess];
    guesses = 0;
    while (!done) {
      if (guess >= high_number) {
        correction = "lower(!)";
      }
      else if (guess <= low_number) {
        correction = "higher(!)";
      }
      else if (guess - low_number > high_number - guess) {
        high_number = guess;
        correction = "lower";
      }
      else {
        low_number = guess;
        correction = "higher";
      }
      if (high_number == low_number + 1) done = true;
      else show Again <[correction=correction] 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];
  }
}