Hi all,

I´m new in drools and after read documentation I have tried to do  my own project  based in NumberGuess example.

This project is a hangman game, but running it I have detected two errors that I don´t know how to solve.

I enclose the project files if someone wants to try it  and can help me to understand the malfunctions.

Malfunctions:
1-. I have a rule with no-loop activated into a RuleFlowGroup(in project, Take a Decision).  After rule execution , the flow continues
 but if you have introduced a bad option, the flow executes an action(Sysout("Bad Character")) and then returns to the same RuleFlowGroup, but at this time the rule doesn´t execute. For this reason the program enters into a infinite loop. I don´t understand this behaviour, taking into account that the rule executes again when another RuleFlowGroup appears between "Take a Decision" RuleFlowGroups.

2-. When you try to solve the word and you guess it, the flow continues towards the Wrong way instead of towards the Well way. I have added some code lines to see the solution after the first try of solving to allow an easy way to test this.

I know that probably all RuleFlowGroups in the flow are really not necessary but they are my first steps with drools.

Another thing that I want to ask is the way to use in a Action block the objects that I have already in the working memory, using java.


Thank you.

Kevin.

#created on: 17-abr-2009
package src.main.rules

dialect "mvel"

#list any import classes here.
import hangman.Hangman.RandomWord;
import hangman.Hangman.GuessedWord;
import hangman.Hangman.GameRules;
import hangman.Hangman.Solution;

import java.io.InputStreamReader;
import java.io.BufferedReader;


#declare any global variables here


rule "Letter or Solve"
        ruleflow-group "Decision"
        no-loop
        when    
            rules : GameRules(g : allowedGuesses , s : allowedSolves)
            GuessedWord( guess : guessedWord , l : letters )

        then
            //Erase, if it exists, the previous value of decision
            //modify ( rules ) { decision = null }
            System.out.println("\n WORD:");
            System.out.println(guess + "\n");
            
            System.out.println( "Said Letters: "+ l +"\n");
            
            System.out.println( "*You still have "+ g +" tries to guess a 
letter and "+ s + " tries to solve the word.\n");
            System.out.println( "Press  \"X\" to exit, \"S\" to solve the word 
or \"L\" to guess a new Letter");
        br = new BufferedReader( new InputStreamReader( System.in ) );
        i = br.readLine().toUpperCase();     
            modify ( rules ) { decision = i }
end



rule "Letter"
        ruleflow-group "Letter"
        no-loop
        when    
            rules : GameRules( allowedGuesses > 0 )
            guess : GuessedWord()           
        then
            modify ( rules ) { allowedGuesses -= 1 }
            System.out.println( "Write a Letter:");
        br = new BufferedReader( new InputStreamReader( System.in ) );
        l = br.readLine().toUpperCase();  
        System.out.println( l ); 
                System.out.println( guess.guessedWord);
                guess.sayOneLetter(l);
                System.out.println( guess.guessedWord);
                System.out.println( guess.letters);
end      



rule "Enter Solution"
        ruleflow-group "Solve"
        no-loop
        when    
            rules : GameRules( allowedSolves > 0 )
            sol : Solution()
            RandomWord(word : randomWord)
            
        then
                modify ( rules ) { allowedSolves -= 1 }
            System.out.println( "Write the solution:");
        br = new BufferedReader( new InputStreamReader( System.in ) );
        i = br.readLine().toUpperCase();  
        System.out.println( "You have written"+i ); 
        System.out.println( "SSHHH Don´t say it to anyone:"+word );  
        System.out.println( word.compareTo(i));
        modify ( sol ) { solution = i }
        System.out.println( sol.solution);
end     
<?xml version="1.0" encoding="UTF-8"?> 
<process xmlns="http://drools.org/drools-5.0/process";
         xmlns:xs="http://www.w3.org/2001/XMLSchema-instance";
         xs:schemaLocation="http://drools.org/drools-5.0/process drools-processes-5.0.xsd"
         type="RuleFlow" name="hangman" id="Hangman" package-name="hangman" >

  <header>
    <imports>
      <import name="hangman.Hangman.RandomWord" />
      <import name="hangman.Hangman.GuessedWord" />
      <import name="hangman.Hangman.GameRules" />
      <import name="hangman.Hangman.Solution" />
    </imports>
  </header>

  <nodes>
    <start id="1" name="Start" x="159" y="-5" width="80" height="40" />
    <end id="3" name="End" x="130" y="618" width="80" height="40" />
    <actionNode id="4" name="Introduction" x="160" y="59" width="80" height="40" >
        <action type="expression" dialect="java" >System.out.println("Welcome to the HANGMAN Game.");
System.out.println("");
System.out.println("You can only fail 4 times guessering the letter and two tries to solve the word.");
System.out.println("");
System.out.println("Let´s go");</action>
    </actionNode>
    <split id="5" name="Letter or Solve?" x="160" y="293" width="80" height="40" type="2" >
      <constraints>
        <constraint toNodeId="12" toType="DROOLS_DEFAULT" name="Bad Character" priority="1" type="rule" dialect="mvel" >GameRules(decision != "L") 
GameRules(decision != "S")</constraint>
        <constraint toNodeId="18" toType="DROOLS_DEFAULT" name="Solve" priority="1" type="rule" dialect="mvel" >GameRules(decision == "S")</constraint>
        <constraint toNodeId="6" toType="DROOLS_DEFAULT" name="Letter" priority="1" type="rule" dialect="mvel" >GameRules(decision == "L")</constraint>
        <constraint toNodeId="19" toType="DROOLS_DEFAULT" name="Exit" priority="1" type="rule" dialect="mvel" >GameRules(decision == "X")</constraint>
      </constraints>
    </split>
    <ruleSet id="6" name="Letter" x="291" y="293" width="80" height="40" ruleFlowGroup="Letter" />
    <ruleSet id="7" name="Solve" x="158" y="471" width="80" height="40" ruleFlowGroup="Solve" />
    <ruleSet id="8" name="Take a Decision" x="158" y="198" width="80" height="40" ruleFlowGroup="Decision" />
    <join id="9" name="Join" x="161" y="130" width="80" height="40" type="2" />
    <actionNode id="11" name="Action" x="259" y="617" width="80" height="40" >
        <action type="expression" dialect="java" >System.out.println("FINAL");</action>
    </actionNode>
    <actionNode id="12" name="Action" x="1" y="129" width="80" height="40" >
        <action type="expression" dialect="java" >System.out.println("");
System.out.println("Bad Character!!");
System.out.println("");</action>
    </actionNode>
    <join id="13" name="Join" x="260" y="541" width="80" height="40" type="2" />
    <split id="14" name="Analize Solution" x="259" y="472" width="80" height="40" type="2" >
      <constraints>
        <constraint toNodeId="13" toType="DROOLS_DEFAULT" name="Well" priority="1" type="rule" dialect="mvel" >RandomWord( word : randomWord)
Solution( solution == word )</constraint>
        <constraint toNodeId="16" toType="DROOLS_DEFAULT" name="Wrong" priority="1" type="rule" dialect="mvel" >RandomWord(  word : randomWord)
Solution( solution != word )</constraint>
      </constraints>
    </split>
    <split id="17" name="More Guesses" x="409" y="541" width="80" height="40" type="2" >
      <constraints>
        <constraint toNodeId="9" toType="DROOLS_DEFAULT" name="Yes" priority="1" type="rule" dialect="mvel" >GameRules( allowedGuesses &gt; 0 )</constraint>
        <constraint toNodeId="13" toType="DROOLS_DEFAULT" name="No" priority="1" type="rule" dialect="mvel" >GameRules(allowedSolves == 0)</constraint>
        <constraint toNodeId="18" toType="DROOLS_DEFAULT" name="Only Solve" priority="1" type="rule" dialect="mvel" >GameRules( allowedSolves &gt; 0 )
GameRules( allowedGuesses == 0 )</constraint>
      </constraints>
    </split>
    <join id="16" name="Join" x="409" y="294" width="80" height="40" type="2" />
    <end id="19" name="End" x="45" y="365" width="61" height="30" />
    <join id="18" name="Join" x="159" y="378" width="80" height="40" type="2" />
  </nodes>

  <connections>
    <connection from="11" to="3" />
    <connection from="1" to="4" />
    <connection from="8" to="5" />
    <connection from="5" to="6" />
    <connection from="18" to="7" />
    <connection from="9" to="8" />
    <connection from="4" to="9" />
    <connection from="12" to="9" />
    <connection from="17" to="9" bendpoints="[448,605;582,605;585,149]" />
    <connection from="13" to="11" />
    <connection from="5" to="12" bendpoints="[42,312]" />
    <connection from="14" to="13" />
    <connection from="17" to="13" />
    <connection from="7" to="14" />
    <connection from="16" to="17" />
    <connection from="14" to="16" />
    <connection from="6" to="16" />
    <connection from="5" to="19" />
    <connection from="5" to="18" />
    <connection from="17" to="18" bendpoints="[532,560;531,398]" />
  </connections>

</process>
package hangman;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;

import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;

/**
 * This is a sample file to launch a process.
 */
public class Hangman {

        public static final void main(String[] args) {
//              try {
//                      // load up the knowledge base
//                      KnowledgeBase kbase = readKnowledgeBase();
//                      StatefulKnowledgeSession ksession = 
kbase.newStatefulKnowledgeSession();
//                      KnowledgeRuntimeLogger logger = 
KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "Hangman");
//                      
//                      //Insert classes into a session to allow the management 
of those
//                      RandomWord rW = new RandomWord();
//                      ksession.insert( rW );
//                      ksession.insert( new GuessedWord() );
//              ksession.insert( new GameRules(4) );
//                      
//                      // start a new process instance
//                      ksession.startProcess("Hangman");
//                      logger.close();
//              } catch (Throwable t) {
//                      t.printStackTrace();
//              }
                
                //Add Rules and Flow to Knowledge Builder 
        final KnowledgeBuilder kbuilder = 
KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( ResourceFactory.newClassPathResource( "hangman.drl",
                        Hangman.class ),//Ponía ShppongExample.class
                              ResourceType.DRL );
        kbuilder.add( ResourceFactory.newClassPathResource( "hangman.rf",
                        Hangman.class ),
                              ResourceType.DRF );

        //Create Knowledge Base and add Knowledge from KBuilder
        final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
        
        // Create a stateful session
        final StatefulKnowledgeSession ksession = 
kbase.newStatefulKnowledgeSession();
        
        //Generate a log file of the session
        KnowledgeRuntimeLogger logger = 
KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "log/hang");

        //Insert classes into a session to allow the management of those
        RandomWord rW = new RandomWord();
                ksession.insert( rW );
                ksession.insert( new GuessedWord(rW) );
                ksession.insert( new Solution() );
        ksession.insert( new GameRules(4) );
        
        //Start the the process
        ksession.startProcess( "Hangman" );
        
        //Fire all rules
        ksession.fireAllRules();
        
        //Close the logger
        logger.close();

        ksession.dispose();
                
                
        }

        private static KnowledgeBase readKnowledgeBase() throws Exception {
                KnowledgeBuilder kbuilder = 
KnowledgeBuilderFactory.newKnowledgeBuilder();
                
kbuilder.add(ResourceFactory.newClassPathResource("hangman.rf"), 
ResourceType.DRF);
                KnowledgeBuilderErrors errors = kbuilder.getErrors();
                if (errors.size() > 0) {
                        for (KnowledgeBuilderError error: errors) {
                                System.err.println(error);
                        }
                        throw new IllegalArgumentException("Could not parse 
knowledge.");
                }
                KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
                kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
                return kbase;
        }
        
        public static class RandomWord {
        private String randomWord;

        public RandomWord() {
            int index = new Random().nextInt( 9 );
            Map<Integer,String> m = new HashMap<Integer, String>();
            m.put(0,"MULTIMEDIA");
            m.put(1,"INFORMATION");
            m.put(2,"RETRIEVAL");
            m.put(3,"DROOLS");
            m.put(4,"MORTGAGE");
            m.put(5,"INSURANCE");
            m.put(6,"TUPPERWARE");
            m.put(7,"HANGMAN");
            m.put(8,"MOVIES");
            m.put(9,"CAR");
            this.randomWord = m.get(index);
        }

        public String getrandomWord() {
            return this.randomWord;
        }
        
    }
        
        public static class GuessedWord {
        private RandomWord randomWord;
        private String guessedWord = "";
        private String letters = "";

        public GuessedWord(RandomWord rW){
                randomWord = rW;
                this.guessedWord = "";
                int count = this.randomWord.getrandomWord().length();
                while(count != 0){
                        this.guessedWord = this.guessedWord + "_ ";
                        count = count -1;
                }
        }
        
        public boolean solution(String solution){
                solution = solution.toUpperCase();
                if(solution.compareTo(randomWord.getrandomWord()) == 0){
                        return true;
                }
                else{
                        return false;
                }
        }
        
        public void sayOneLetter(String c){
                c = c.toUpperCase();
                StringBuffer buffer = new 
StringBuffer(this.randomWord.getrandomWord());
                StringBuffer buffer2 = new StringBuffer(this.guessedWord);
                this.letters = this.letters + c + " ";
                int index = 0;
                while((index = buffer.indexOf(c, index)) != -1){
                        buffer2 = buffer2.replace(index*2, index*2+2, c+" ");
                        index = index + 1;
                }
                this.guessedWord = buffer2.toString();
        }

        public String getGuessedWord() {
            return this.guessedWord;
        }
        
        public String getLetters() {
            return this.letters;
        }
        
        public String getrandomWord() {
            return this.randomWord.getrandomWord();
        }
    }
        
        public static class GameRules {
        private int allowedGuesses;
//        private int allowedSolves;
        private int value;
        private boolean exit = false;
        public String decision;

        public GameRules(int allowedGuesses) {
            this.allowedGuesses = allowedGuesses;
//            this.allowedSolves = 2;
            this.value = 2;
        }
        
        public int getAllowedGuesses() {
            return this.allowedGuesses;
        }
        
        public void setAllowedGuesses(int in) {
            this.allowedGuesses = in;
        }
        
        public int getAllowedSolves() {
//            return this.allowedSolves;
                return this.value;
        }
        
        public void setAllowedSolves(int in) {
//            this.allowedSolves = in;
                this.value = in;
        }
        
        public String getDecision() {
            return this.decision;
        }
        
        public void setDecision(String in) {
            this.decision = in;
        }

                public void setExit(boolean exit) {
                        this.exit = exit;
                }

                public boolean isExit() {
                        return exit;
                }
        }
        
        public static class Solution {
        private String solution;
        
        public Solution() {
            this.solution = "";
        }
        
        public String getSolution() {
            return this.solution;
        }
        
        public void setSolution(String in) {
            this.solution = in;
        }
        }
}
_______________________________________________
rules-users mailing list
[email protected]
https://lists.jboss.org/mailman/listinfo/rules-users

Reply via email to