Reputation: 2621
I try to create a rule that decides the bonus in a game that rely on age.
So if the player has age less than 16 and that he is ahead the sencond stage in game, a bonus of 30 will be given to the player.
My 1st problem is that age and stage are both integer.
Can you help me in fixing the rule?
Here it is my try in DRL file :
WHEN
age < 16 and stage > 2
Then
incrementBonus(30)
Also, can you give me some snippet of code about how to do in Drools?
Here what I did in my Java class :
int age = 14;
int stage = 4;
knowledgeSession.insert(age);
knowledgeSession.insert(stage);
knowledgeSession.fireAllRules();
Upvotes: 0
Views: 1858
Reputation: 31300
Please realize that Drools is an object oriented production rule system, and therefore you should consider using Java objects (Java beans) as facts. For your problem it's obvious:
public class Player {
private int age;
private int stage = 0;
private int bonus = 0;
public Player( int age ){ this.age = age; }
// getters and setters
}
Player px = new Player( 14 );
px.setStage( 14 );
knowledgeSession.insert(stage);
And the rule will be
rule "calc age/stage bonus"
when
$p: Player( age < 16, stage > 2 )
then
modify( $p ){ setBonus( $p.getBonus)() + 30 ) }
end
But there will be a problem: Modification of a fact causes reevaluation of the rules, and so this rule will be executed over and over again. You could add the rule attribute no-loop, but this may not solve the problem if you have other rules calculating similar bonus increments. It may be necessary to keep track (in Player) of the performed bonus additions. For instance, use a field for each bonus category:
class Player {
int bonusAgeStage = 0;
and implement getBonus as the sum of all such bonus fields.
Now the rule can be written safely as
rule "calc age/stage bonus"
when
$p: Player( age < 16, stage > 2, bonusAgeStage == 0 )
then
modify( $p ){ setBonusAgeStage( 30 ) }
end
Upvotes: 2