26.6. Number Guess Example: Firing Rules at a Specific Point in NumberGuess.drl

rule "Get user Guess"
    ruleflow-group "Guess"
    no-loop
    when
        $r : RandomNumber()
        rules : GameRules( allowed : allowedGuesses )
        game : Game( guessCount < allowed )
        not ( Guess() )
    then
        System.out.println( "You have " + ( rules.allowedGuesses - game.guessCount )
                            + " out of " + rules.allowedGuesses
                            + " guesses left.\nPlease enter your guess from 0 to "
                            + rules.maxRange );
        br = new BufferedReader( new InputStreamReader( System.in ) );
        i = br.readLine();        
        modify ( game ) { guessCount = game.guessCount + 1 }
        insert( new Guess( i ) );
end
  • The various nodes in combination with the rules make the Number Guess game work. For example, the "Guess" Rule Flow Group allows only the rule "Get user Guess" to fire, because only that rule has a matching attribute of ruleflow-group "Guess".
  • The LHS section (after when) of the rule states that it will be activated for each RandomNumber object inserted into the Working Memory where guessCount is less than allowedGuesses from the GameRules object and where the user has not guessed the correct number.
  • The RHS section (or consequence, after then) prints a message to the user and then awaits user input from System.in. After obtaining this input (the readLine() method call blocks until the return key is pressed) it modifies the guess count and inserts the new guess, making both available to the Working Memory.
  • The package declares the dialect as MVEL and various Java classes are imported.
In total, there are five rules in this file:
  1. Get User Guess, the Rule examined above.
  2. A Rule to record the highest guess.
  3. A Rule to record the lowest guess.
  4. A Rule to inspect the guess and retract it from memory if incorrect.
  5. A Rule that notifies the user that all guesses have been used up.