SlideShare ist ein Scribd-Unternehmen logo
1 von 55
Downloaden Sie, um offline zu lesen
Learning Rule Based 
Programming 
Using Games
1979 Rete Algorithm by Charles Forgy 2
Clips and Jess 
Clips 1986 
! 
! 
! 
! 
! 
! 
! 
3 
Clips 1995 
! 
! 
! 
! 
! 
! 
!
Rules and Patterns
5 
What is a Rule 
rule <rule_name> 
<attribute><value> 
when 
<conditions> 
then 
<actions> 
end
6 
Pattern Matching 
Person( age >= 18 ) 
field name restriction 
object type constraint 
pattern
CashFlow
CashFlow Example 
8 
Classes 
Account 
long accountNo 
int balance 
CashFlow 
Date date 
int amount 
AccountPeriod 
Date start 
Date end
CashFlow Rule 
select * from Account acc, 
Cashflow cf, AccountPeriod ap 
where acc.accountNo == cf.accountNo and 
cf.type == CREDIT 
cf.date >= ap.start and 
cf.date <= ap.end 
rule “increase balance for AccountPeriod Credits” 
when 
ap : AccountPeriod() 
acc : Account() 
cf : CashFlow( type == CREDIT, 
accountNo == acc.accountNo, 
date >= ap.start && <= ap.end ) 
then 
acc.balance += cf.amount; 
end 
9 
acc.balance += cf.amount
CashFlow Rule 
select * from Account acc, 
Cashflow cf, AccountPeriod ap 
where acc.accountNo == cf.accountNo and 
cf.type == CREDIT 
cf.date >= ap.start and 
cf.date <= ap.end 
rule “increase balance for AccountPeriod Credits” 
when 
ap : AccountPeriod() 
acc : Account() 
cf : CashFlow( type == CREDIT, 
accountNo == acc.accountNo, 
date >= ap.start && <= ap.end ) 
then 
acc.balance += cf.amount; 
end 
10 
acc.balance += cf.amount
CashFlow Rule 
select * from Account acc, 
Cashflow cf, AccountPeriod ap 
where acc.accountNo == cf.accountNo and 
cf.type == CREDIT 
cf.date >= ap.start and 
cf.date <= ap.end 
rule “increase balance for AccountPeriod Credits” 
when 
ap : AccountPeriod() 
acc : Account() 
cf : CashFlow( type == CREDIT, 
accountNo == acc.accountNo, 
date >= ap.start && <= ap.end ) 
then 
acc.balance += cf.amount; 
end 
11 
acc.balance += cf.amount
CashFlow Rule 
select * from Account acc, 
Cashflow cf, AccountPeriod ap 
where acc.accountNo == cf.accountNo and 
cf.type == CREDIT 
cf.date >= ap.start and 
cf.date <= ap.end 
rule “increase balance for AccountPeriod Credits” 
when 
ap : AccountPeriod() 
acc : Account() 
cf : CashFlow( type == CREDIT, 
accountNo == acc.accountNo, 
date >= ap.start && <= ap.end ) 
then 
acc.balance += cf.amount; 
end 
12 
acc.balance += cf.amount
CashFlow Rule 
select * from Account acc, 
Cashflow cf, AccountPeriod ap 
where acc.accountNo == cf.accountNo and 
cf.type == CREDIT 
cf.date >= ap.start and 
cf.date <= ap.end 
rule “increase balance for AccountPeriod Credits” 
when 
ap : AccountPeriod() 
acc : Account() 
cf : CashFlow( type == CREDIT, 
accountNo == acc.accountNo, 
date >= ap.start && <= ap.end ) 
then 
acc.balance += cf.amount; 
end 
13 
acc.balance += cf.amount
CashFlow Example 
14 
rule "Increase balance for AccountPeriod Credits" 
when 
ap : AccountPeriod( ) 
acc : Account( ) 
cf : CashFlow( type == CashFlowType.CREDIT, 
accountNo == acc.accountNo, 
date >= ap.start && <= ap.end ) 
then 
acc.balance = acc.balance + cf.amount; 
end 
rule "Decrease balance for AccountPeriod Debits" 
when 
ap : AccountPeriod( ) 
acc : Account( ) 
cf : CashFlow( type == CashFlowType.DEBIT, 
accountNo == acc.accountNo, 
date >= ap.start && <= ap.end ) 
then 
acc.balance = acc.balance - cf.amount; 
end 
CashFlow 
date amount type accountNo 
12-Jan-12 100 CREDIT 1 
2-Feb-12 200 DEBIT 1 
18-May-12 50 CREDIT 1 
9-Mar-12 75 CREDIT 1 
AccountingPeriod 
start end 
01-JAN-2012 31-MAR-2012 
Account 
accountNo balance 
1 0 
CashFlow 
date amount type accountNo 
12-Jan-12 100 CREDIT 1 
9-Mar-12 75 CREDIT 1 
CashFlow 
date amount type accountNo 
2-Feb-12 200 DEBIT 1 
Account 
accountNo balance 
1 -25
CashFlow Example 
rule "Print blance for AccountPeriod" salience -50 
when 
15 
ap : AccountPeriod() 
acc : Account( ) 
then 
System.out.println( "Account Number " + acc.accountNo + " balance " + acc.balance ); 
end 
Agenda 
1 increase balance 
2 decrease balance arbitrary 
3 increase balance 
4 print balance
16 
Two Phase
01-JAN-2012 31-MAR-2012 
accountNo balance 
update AccountPeriod 
set start=“01-Apr-2012” end = “31-MAR-2012” 
17 
AccountingPeriod 
start end 
Account 
1 0 
AccountingPeriod 
start end 
01-Apr-2012 30-JUN-2012 
Account 
accountNo balance 
1 0
CashFlow Example 
18 
rule "Increase balance for AccountPeriod Credits" 
when 
ap : AccountPeriod( ) 
acc : Account( ) 
cf : CashFlow( type == CashFlowType.CREDIT, 
accountNo == acc.accountNo, 
date >= ap.start && <= ap.end ) 
then 
acc.balance = acc.balance + cf.amount; 
end 
rule "Decrease balance for AccountPeriod Debits" 
when 
ap : AccountPeriod( ) 
acc : Account( ) 
cf : CashFlow( type == CashFlowType.DEBIT, 
accountNo == acc.accountNo, 
date >= ap.start && <= ap.end ) 
then 
acc.balance = acc.balance - cf.amount; 
end 
CashFlow 
date amount type accountNo 
12-Jan-12 100 CREDIT 1 
2-Feb-12 200 DEBIT 1 
18-May-12 50 CREDIT 1 
9-Mar-12 75 CREDIT 1 
AccountingPeriod 
start end 
01-Apr-2012 30-JUN-2012 
Account 
accountNo balance 
1 0 
CashFlow 
date amount type accountNo 
18-May-12 75 CREDIT 1 
CashFlow 
date amount type accountNo 
Account 
accountNo balance 
1 25
19 
Conditional Elements 
not Bus( color = “red” ) 
exists Bus( color = “red” ) 
forall ( $bus : Bus( color == “red” ) ) 
forall ( $bus : Bus( floors == 2 ) 
Bus( this == $bus, color == “red” ) )
Fire System
Definitions 
public class Room { 
private String name 
// getter and setter methods here 
} 
public class Sprinkler { 
private Room room; 
private boolean on; 
// getter and setter methods here 
} 
public class Fire { 
private Room room; 
// getter and setter methods here 
} 
public class Alarm { 
}
Definitions 
rule "When there is a fire turn on the sprinkler" when 
f : Fire() 
s : Sprinkler( room == f.room, on == false ) 
then 
modify( s ) { on = true }; 
println( "Turn on the sprinkler for room " + r.name ); 
end 
rule "When the fire is gone turn off the sprinkler" when 
r : Room( ) 
s : Sprinkler( room == r, on == true ) 
not Fire( room == r ) 
then 
modify( s) { on = false }; 
println( "Turn off the sprinkler for room " + r.name); 
end
Definitions 
rule "Raise the alarm when we have one or more fires" when 
exists Fire() 
then 
insert( new Alarm() ); 
println( "Raise the alarm" ); 
end 
rule "Cancel the alarm when all the fires have gone" when 
not Fire() 
a: Alarm() 
then 
retract( a ); 
println( "Cancel the alarm" ); 
end
Definitions 
rule "Status output when things are ok" when 
not Alarm() 
not Sprinkler( on == true ) 
then 
println( "Everything is ok" ); 
end
Executing 
String[] names = new String[]{"kitchen", "bedroom", "office", "livingroom"}; 
Map<String,Room> name2room = new HashMap<String,Room>(); 
! 
for( String name: names ){ 
Room room = new Room( name ); 
name2room.put( name, room ); 
ksession.insert( room ); 
Sprinkler sprinkler = new Sprinkler( room ); 
ksession.insert( sprinkler ); 
} 
! 
ksession.fireAllRules() 
> Everything is ok
Executing 
Fire kitchenFire = new Fire( name2room.get( "kitchen" ) ); 
Fire officeFire = new Fire( name2room.get( "office" ) ); 
! 
FactHandle kitchenFireHandle = ksession.insert( kitchenFire ); 
FactHandle officeFireHandle = ksession.insert( officeFire ); 
! 
ksession.fireAllRules(); 
> Raise the alarm 
> Turn on the sprinkler for room kitchen 
> Turn on the sprinkler for room office
Executing 
ksession.retract( kitchenFireHandle ); 
ksession.retract( officeFireHandle ); 
! 
ksession.fireAllRules() 
> Turn off the sprinkler for room office 
> Turn off the sprinkler for room kitchen 
> Cancel the alarm 
> Everything is ok 
rule "Status output when things are ok" when 
not Alarm() 
not Sprinkler( on == true ) 
then 
println( "Everything is ok" ); 
end
Number Guess
public class Game { 
private int biggest; 
private int smallest; 
private int guessCount; 
public class Guess { 
private int value; 
public class GameRules { 
private int maxRange; 
private int allowedGuesses; 
public class RandomNumber { 
private int randomNumber;
public class Game { 
private int biggest; 
private int smallest; 
private int guessCount; 
public class Guess { 
private int value; 
public class GameRules { 
private int maxRange; 
private int allowedGuesses; 
public class RandomNumber { 
private int randomNumber; 
<kbase name="NumberGuessKB" packages="org.drools.games.numberguess"> 
public class NumberGuessMain { 
public static void main(String[] args) { 
KieContainer kc = KieServices.Factory.get().getKieClasspathContainer(); 
final KieSession ksession = kc.newKieSession( "NumberGuessKS"); 
ksession.insert( new GameRules( 100, 5 ) ); 
ksession.insert( new RandomNumber() ); 
ksession.insert( new Game() ); 
ksession.fireAllRules(); 
} 
} 
<ksession name="NumberGuessKS"/> 
</kbase>
rule Main when 
rules : GameRules( ) 
game : Game( guessCount < rules.allowedGuesses ) 
not Guess() 
then 
setFocus("Guess"); 
end 
rule "Get user Guess" agenda-group "Guess" when 
$r : RandomNumber() 
rules : GameRules( ) 
game : Game( ) 
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 ) ); 
modify (game) { guessCount = game.guessCount + 1 } 
int i = Integer.parseInt( br.readLine() ); 
insert( new Guess( i ) ); 
end
rule "Record the highest Guess" agenda-group "Guess" no-loop when 
game : Game( ) 
r : RandomNumber() 
guess : Guess( value > r.value) 
then 
modify ( game ) { biggest = guess.value }; 
retract( guess ); 
System.out.println( "Your guess was too high" ); 
end
rule "Record the highest Guess" agenda-group "Guess" no-loop when 
game : Game( ) 
r : RandomNumber() 
guess : Guess( value > r.value) 
then 
modify ( game ) { biggest = guess.value }; 
retract( guess ); 
System.out.println( "Your guess was too high" ); 
end 
rule "Record the lowest Guess" agenda-group "Guess" when 
game : Game( ) 
r : RandomNumber() 
guess : Guess(value < r.value ) 
then 
modify ( game ) { smallest = guess.value }; 
retract( guess ); 
System.out.println( "Your guess was too low" ); 
end
rule "Record the highest Guess" agenda-group "Guess" no-loop when 
game : Game( ) 
r : RandomNumber() 
guess : Guess( value > r.value) 
then 
modify ( game ) { biggest = guess.value }; 
retract( guess ); 
System.out.println( "Your guess was too high" ); 
end 
rule "Record the lowest Guess" agenda-group "Guess" when 
game : Game( ) 
r : RandomNumber() 
guess : Guess(value < r.value ) 
then 
modify ( game ) { smallest = guess.value }; 
retract( guess ); 
System.out.println( "Your guess was too low" ); 
end 
rule "Guess correct" agenda-group "Guess" when 
game : Game( ) 
r : RandomNumber() 
guess : Guess( value == r.value) 
then 
System.out.println( "You guessed correctly" ); 
end
rule Main when 
rules : GameRules( ) 
game : Game( guessCount < rules.allowedGuesses ) 
not Guess() 
then 
setFocus("Guess"); 
end 
rule "No more Guesses" when 
rules : GameRules( ) 
game : Game( guessCount == rules.allowedGuesses ) 
not Guess() 
r : RandomNumber() 
then 
System.out.println( "You have no more guessesnThe correct guess was " + r.value ); 
end
rooms = [ 
"basement" : new Room("basement"), 
"lounge" : new Room("lounge"), 
"dining room” : new Room("dining room"), 
“kitchen" : new Room("kitchen"), 
"ground floor hallway" : new Room("ground floor hallway"), 
"bedroom1" : new Room("bedroom1"), 
"bedroom2" : new Room("bedroom2"), 
“bathroom" : new Room("bathroom"), 
"office" : new Room("office"), 
"first floor hallway" : new Room("first floor hallway") 
]; 
doors = [ 
"d1" : new Door( rooms[“kitchen", rooms["basement"] ), 
"d2" : new Door( rooms["ground floor hallway"], rooms["lounge"]), 
"d3" : new Door( rooms["ground floor hallway"], rooms["dining room"] ), 
"d4" : new Door( rooms["ground floor hallway"], rooms["kitchen"]), 
"d5" : new Door( rooms["ground floor hallway"], rooms[ "first floor hallway"] ), 
"d6" : new Door( rooms["first floor hallway"], rooms[ "bedroom1"] ), 
"d7" : new Door( rooms["first floor hallway”], rooms[ "bedroom2"] ), 
"d8" : new Door( rooms["first floor hallway"], rooms[ "bathroom"] ), 
"d9" : new Door( rooms["first floor hallway”], rooms[ "office"] ) 
];
characters = [ "hero" : new Character( "hero" ), 
"monster" : new Character( "monster" ) ]; 
items = [ 
"mace" : new Item( "mace" ), 
"cucumber" : new Item( "cucumber" ), 
"torch" : new Item( "torch" ), 
"umbrella" : new Item( "umbrella" ) 
]; 
locations = [ 
"mace" : new Location( items["mace"], rooms["basement"] ), 
"monster" : new Location( characters["monster"], rooms["basement"] ), 
"cucumber" : new Location( items["cucumber"], rooms["kitchen"] ), 
"torch" : new Location( items["torch"], rooms["office"] ), 
"hero" : new Location( characters["hero"], rooms["ground floor hallway"] ), 
"umbrella" : new Location( items["umbrella"], rooms["ground floor hallway"] ) 
];
doors = [ 
"d1" : new Door( rooms[“kitchen", rooms["basement"] ), 
"d2" : new Door( rooms["ground floor hallway"], rooms["lounge"]), 
"d3" : new Door( rooms["ground floor hallway"], rooms["dining room"] ), 
"d4" : new Door( rooms["ground floor hallway"], rooms["kitchen"]), 
"d5" : new Door( rooms["ground floor hallway"], rooms[ "first floor hallway"] ), 
"d6" : new Door( rooms["first floor hallway"], rooms[ "bedroom1"] ), 
"d7" : new Door( rooms["first floor hallway”], rooms[ "bedroom2"] ), 
"d8" : new Door( rooms["first floor hallway"], rooms[ "bathroom"] ), 
"d9" : new Door( rooms["first floor hallway”], rooms[ "office"] ) 
]; 
query connect( Room $x, Room $y ) 
Door($id, $x, $y;) 
or 
Door($id, $y, $x;) 
end
locations = [ 
query things(Character $char, List $things) 
$char := Character() 
Location( $char, $room; ) 
$things := List() from accumulate( Location($thing, $room; thing != $char), 
collectList( $thing ) ) 
end 
"mace" : new Location( items["mace"], rooms["basement"] ), 
"monster" : new Location( characters["monster"], rooms["basement"] ), 
"cucumber" : new Location( items["cucumber"], rooms["kitchen"] ), 
"torch" : new Location( items["torch"], rooms["office"] ), 
"hero" : new Location( characters["hero"], rooms["ground floor hallway"] ), 
"umbrella" : new Location( items["umbrella"], rooms["ground floor hallway"] ) 
]; 
query exits(Character $char, List $exits) 
$char := Character() 
Location( $char, $room; ) 
$exits := List() from accumulate( connect($room, $exit;), 
collectList( $exit ) ) 
end
query look(Character $char, List $things, List $exits) 
$char := Character() 
things( $char, $things; ) 
exits( $char, $exits; ) 
end 
rule lookCmd agenda-group "commands" lock-on-active auto-focus when 
lc : LookCommand( c : character ) 
Location( thing == c, $room : target ) 
?look( c, things, exits; ) 
then 
str = "You are in the " + $room + "n"; 
str +="You can see " + things + "n"; 
str +="Available exits are " + exits + "n"; 
str +="n"; 
res = new Response( str ); 
res.localId = lc.requestId; 
insert( res ); 
end
rule lookCmd agenda-group "commands" lock-on-active auto-focus when 
lc : LookCommand( c : character ) 
Location( thing == c, $room : target ) 
?look( c, things, exits; ) 
then 
str = "You are in the " + $room + "n"; 
str +="You can see " + things + "n"; 
str +="Available exits are " + exits + "n"; 
str +="n"; 
res = new Response( str ); 
res.localId = lc.requestId; 
insert( res ); 
end
rule validMove agenda-group "commands" lock-on-active auto-focus when 
mc : MoveCommand( c : character, r : room ) 
l : Location( thing == c, ltarget : target ) 
exists ?connect( r, ltarget; ) 
then 
modify( l ) { target = r }; 
res = new Response( "You have entered the " + l.target + "n" ); 
res.localId = mc.requestId; 
insert( res ); 
end 
rule lookCmd agenda-group "commands" lock-on-active auto-focus when 
lc : LookCommand( c : character ) 
Location( thing == c, $room : target ) 
?look( c, things, exits; ) 
then 
str = "You are in the " + $room + "n"; 
str +="You can see " + things + "n"; 
str +="Available exits are " + exits + "n"; 
str +="n"; 
res = new Response( str ); 
res.localId = lc.requestId; 
insert( res ); 
end
rule validPickup agenda-group "commands" lock-on-active auto-focus when 
pc : PickupCommand( c : character, t : thing) 
cl : Location( thing == c ) 
tl : Location( thing == t, target == cl.target ) 
then 
insert( new Holding( c, t ) ); 
modify( tl ) { target = c }; 
res = new Response( "You have picked up the " + t + "n" ); 
res.localId = pc.requestId; 
insert( res ); 
end
rule validPickup agenda-group "commands" lock-on-active auto-focus when 
pc : PickupCommand( c : character, t : thing) 
cl : Location( thing == c ) 
tl : Location( thing == t, target == cl.target ) 
then 
insert( new Holding( c, t ) ); 
modify( tl ) { target = c }; 
res = new Response( "You have picked up the " + t + "n" ); 
res.localId = pc.requestId; 
insert( res ); 
end 
rule validDrop agenda-group "commands" lock-on-active auto-focus when 
dc : DropCommand( c : character, t : thing) 
cl : Location( thing == c ) 
tl : Location( thing == t ) 
h : Holding( c, t;) 
then 
modify( tl ) { target = cl.target }; 
retract ( h ); 
insert( new DropEvent( c, t ) ); 
res = new Response( "You have droped the " + t + "n" ); 
res.localId = dc.requestId; 
insert( res ); 
end
rule validGive agenda-group "commands" lock-on-active auto-focus when 
gc : GiveCommand( $giver : giver, $thing : thing ) 
// They are in the same room 
giverl : Location( thing == gc.giver ) 
Location( thing == gc.receiver, target == giverl.target ) 
// The giver must be holding the thing 
h : Holding( $giver, $thing;) 
then 
modify( h ) { character = gc.receiver }; 
insert( new GiveEvent( gc.giver, gc.thing, gc.receiver ) ); 
res = new Response( "You have given the " + gc.thing + " to " + gc.receiver + "n" ); 
res.localId = gc.requestId; 
insert( res ); 
end
Classic Games Development with Drools
Classic Games Development with Drools
Classic Games Development with Drools
Classic Games Development with Drools
Classic Games Development with Drools
Classic Games Development with Drools
Classic Games Development with Drools
Classic Games Development with Drools
Classic Games Development with Drools
Classic Games Development with Drools

Weitere ähnliche Inhalte

Was ist angesagt?

Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]
User1test
 
20141001 delapsley-oc-openstack-final
20141001 delapsley-oc-openstack-final20141001 delapsley-oc-openstack-final
20141001 delapsley-oc-openstack-final
David Lapsley
 

Was ist angesagt? (20)

Drools 6.0 (CamelOne 2013)
Drools 6.0 (CamelOne 2013)Drools 6.0 (CamelOne 2013)
Drools 6.0 (CamelOne 2013)
 
RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術RxJS - 封裝程式的藝術
RxJS - 封裝程式的藝術
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript
 
Mcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singhMcs011 solved assignment by divya singh
Mcs011 solved assignment by divya singh
 
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
 
JBoss World 2011 - Drools
JBoss World 2011 - DroolsJBoss World 2011 - Drools
JBoss World 2011 - Drools
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
Drools, jBPM OptaPlanner presentation
Drools, jBPM OptaPlanner presentationDrools, jBPM OptaPlanner presentation
Drools, jBPM OptaPlanner presentation
 
Java Se next Generetion
Java Se next GeneretionJava Se next Generetion
Java Se next Generetion
 
Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.
 
Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]
 
Python: the coolest is yet to come
Python: the coolest is yet to comePython: the coolest is yet to come
Python: the coolest is yet to come
 
Azure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesAzure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best Practices
 
Aaron Bedra - Effective Software Security Teams
Aaron Bedra - Effective Software Security TeamsAaron Bedra - Effective Software Security Teams
Aaron Bedra - Effective Software Security Teams
 
Client-side Rendering with AngularJS
Client-side Rendering with AngularJSClient-side Rendering with AngularJS
Client-side Rendering with AngularJS
 
A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project Files
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
 
20141001 delapsley-oc-openstack-final
20141001 delapsley-oc-openstack-final20141001 delapsley-oc-openstack-final
20141001 delapsley-oc-openstack-final
 
PostgreSQL Open SV 2018
PostgreSQL Open SV 2018PostgreSQL Open SV 2018
PostgreSQL Open SV 2018
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 

Ähnlich wie Classic Games Development with Drools

Hybrid rule engines (rulesfest 2010)
Hybrid rule engines (rulesfest 2010)Hybrid rule engines (rulesfest 2010)
Hybrid rule engines (rulesfest 2010)
Geoffrey De Smet
 
The java class Account that simultes the Account class.pdf
   The java class Account that simultes  the Account class.pdf   The java class Account that simultes  the Account class.pdf
The java class Account that simultes the Account class.pdf
akshay1213
 

Ähnlich wie Classic Games Development with Drools (20)

rules, events and workflow
rules, events and workflowrules, events and workflow
rules, events and workflow
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
Buenos Aires Drools Expert Presentation
Buenos Aires Drools Expert PresentationBuenos Aires Drools Expert Presentation
Buenos Aires Drools Expert Presentation
 
Hybrid rule engines (rulesfest 2010)
Hybrid rule engines (rulesfest 2010)Hybrid rule engines (rulesfest 2010)
Hybrid rule engines (rulesfest 2010)
 
Clojure workshop
Clojure workshopClojure workshop
Clojure workshop
 
Advanced redux
Advanced reduxAdvanced redux
Advanced redux
 
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
Joe Bew - Apprendi un nuovo linguaggio sfruttando il TDD e il Clean Code - Co...
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
project
projectproject
project
 
The java class Account that simultes the Account class.pdf
   The java class Account that simultes  the Account class.pdf   The java class Account that simultes  the Account class.pdf
The java class Account that simultes the Account class.pdf
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210
 
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
Por qué usar Spock en lugar de JUnit / Mockito para tus tests Java - Codemoti...
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
The Ring programming language version 1.9 book - Part 45 of 210
The Ring programming language version 1.9 book - Part 45 of 210The Ring programming language version 1.9 book - Part 45 of 210
The Ring programming language version 1.9 book - Part 45 of 210
 
Using Change Streams to Keep Up with Your Data
Using Change Streams to Keep Up with Your DataUsing Change Streams to Keep Up with Your Data
Using Change Streams to Keep Up with Your Data
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 

Mehr von Mark Proctor

Drools 6.0 (JudCon 2013)
Drools 6.0 (JudCon 2013)Drools 6.0 (JudCon 2013)
Drools 6.0 (JudCon 2013)
Mark Proctor
 

Mehr von Mark Proctor (20)

Rule Modularity and Execution Control
Rule Modularity and Execution ControlRule Modularity and Execution Control
Rule Modularity and Execution Control
 
Reducing the Cost of the Linear Growth Effect using Adaptive Rules with Unlin...
Reducing the Cost of the Linear Growth Effect using Adaptive Rules with Unlin...Reducing the Cost of the Linear Growth Effect using Adaptive Rules with Unlin...
Reducing the Cost of the Linear Growth Effect using Adaptive Rules with Unlin...
 
Drools, jBPM and OptaPlanner (NYC and DC Sept 2017 - Keynote Talk Video)
Drools, jBPM and OptaPlanner (NYC and DC Sept 2017 - Keynote Talk Video)Drools, jBPM and OptaPlanner (NYC and DC Sept 2017 - Keynote Talk Video)
Drools, jBPM and OptaPlanner (NYC and DC Sept 2017 - Keynote Talk Video)
 
Drools Happenings 7.0 - Devnation 2016
Drools Happenings 7.0 - Devnation 2016Drools Happenings 7.0 - Devnation 2016
Drools Happenings 7.0 - Devnation 2016
 
RuleML2015 : Hybrid Relational and Graph Reasoning
RuleML2015 : Hybrid Relational and Graph Reasoning RuleML2015 : Hybrid Relational and Graph Reasoning
RuleML2015 : Hybrid Relational and Graph Reasoning
 
Red Hat Summit 2015 : Drools, jBPM and UberFire Roadmaps
Red Hat Summit 2015 : Drools, jBPM and UberFire RoadmapsRed Hat Summit 2015 : Drools, jBPM and UberFire Roadmaps
Red Hat Summit 2015 : Drools, jBPM and UberFire Roadmaps
 
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client TechnologyRed Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
Red Hat JBoss BRMS and BPMS Workbench and Rich Client Technology
 
Drools and jBPM 6 Overview
Drools and jBPM 6 OverviewDrools and jBPM 6 Overview
Drools and jBPM 6 Overview
 
UberFire Quick Intro and Overview (early beta Aug 2013)
UberFire Quick Intro and Overview (early beta Aug 2013)UberFire Quick Intro and Overview (early beta Aug 2013)
UberFire Quick Intro and Overview (early beta Aug 2013)
 
Property Reactive RuleML 2013
Property Reactive RuleML 2013Property Reactive RuleML 2013
Property Reactive RuleML 2013
 
Reactive Transitive Closures with Drools (Backward Chaining)
Reactive Transitive Closures with Drools (Backward Chaining)Reactive Transitive Closures with Drools (Backward Chaining)
Reactive Transitive Closures with Drools (Backward Chaining)
 
Drools 6.0 (JudCon 2013)
Drools 6.0 (JudCon 2013)Drools 6.0 (JudCon 2013)
Drools 6.0 (JudCon 2013)
 
UberFire Quick Intro and Overview (early beta Jul 2013)
UberFire Quick Intro and Overview (early beta Jul 2013)UberFire Quick Intro and Overview (early beta Jul 2013)
UberFire Quick Intro and Overview (early beta Jul 2013)
 
UberFire (JudCon 2013)
UberFire (JudCon 2013)UberFire (JudCon 2013)
UberFire (JudCon 2013)
 
Drools 6.0 (Red Hat Summit 2013)
Drools 6.0 (Red Hat Summit 2013)Drools 6.0 (Red Hat Summit 2013)
Drools 6.0 (Red Hat Summit 2013)
 
Games development with the Drools rule engine
Games development with the Drools rule engineGames development with the Drools rule engine
Games development with the Drools rule engine
 
Drools & jBPM future roadmap talk
Drools & jBPM future roadmap talkDrools & jBPM future roadmap talk
Drools & jBPM future roadmap talk
 
Drools @ IntelliFest 2012
Drools @ IntelliFest 2012Drools @ IntelliFest 2012
Drools @ IntelliFest 2012
 
JUDCon India 2012 Drools Fusion
JUDCon  India 2012 Drools FusionJUDCon  India 2012 Drools Fusion
JUDCon India 2012 Drools Fusion
 
JUDCon India 2012 Drools Expert
JUDCon  India 2012 Drools ExpertJUDCon  India 2012 Drools Expert
JUDCon India 2012 Drools Expert
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Classic Games Development with Drools

  • 1. Learning Rule Based Programming Using Games
  • 2. 1979 Rete Algorithm by Charles Forgy 2
  • 3. Clips and Jess Clips 1986 ! ! ! ! ! ! ! 3 Clips 1995 ! ! ! ! ! ! !
  • 5. 5 What is a Rule rule <rule_name> <attribute><value> when <conditions> then <actions> end
  • 6. 6 Pattern Matching Person( age >= 18 ) field name restriction object type constraint pattern
  • 8. CashFlow Example 8 Classes Account long accountNo int balance CashFlow Date date int amount AccountPeriod Date start Date end
  • 9. CashFlow Rule select * from Account acc, Cashflow cf, AccountPeriod ap where acc.accountNo == cf.accountNo and cf.type == CREDIT cf.date >= ap.start and cf.date <= ap.end rule “increase balance for AccountPeriod Credits” when ap : AccountPeriod() acc : Account() cf : CashFlow( type == CREDIT, accountNo == acc.accountNo, date >= ap.start && <= ap.end ) then acc.balance += cf.amount; end 9 acc.balance += cf.amount
  • 10. CashFlow Rule select * from Account acc, Cashflow cf, AccountPeriod ap where acc.accountNo == cf.accountNo and cf.type == CREDIT cf.date >= ap.start and cf.date <= ap.end rule “increase balance for AccountPeriod Credits” when ap : AccountPeriod() acc : Account() cf : CashFlow( type == CREDIT, accountNo == acc.accountNo, date >= ap.start && <= ap.end ) then acc.balance += cf.amount; end 10 acc.balance += cf.amount
  • 11. CashFlow Rule select * from Account acc, Cashflow cf, AccountPeriod ap where acc.accountNo == cf.accountNo and cf.type == CREDIT cf.date >= ap.start and cf.date <= ap.end rule “increase balance for AccountPeriod Credits” when ap : AccountPeriod() acc : Account() cf : CashFlow( type == CREDIT, accountNo == acc.accountNo, date >= ap.start && <= ap.end ) then acc.balance += cf.amount; end 11 acc.balance += cf.amount
  • 12. CashFlow Rule select * from Account acc, Cashflow cf, AccountPeriod ap where acc.accountNo == cf.accountNo and cf.type == CREDIT cf.date >= ap.start and cf.date <= ap.end rule “increase balance for AccountPeriod Credits” when ap : AccountPeriod() acc : Account() cf : CashFlow( type == CREDIT, accountNo == acc.accountNo, date >= ap.start && <= ap.end ) then acc.balance += cf.amount; end 12 acc.balance += cf.amount
  • 13. CashFlow Rule select * from Account acc, Cashflow cf, AccountPeriod ap where acc.accountNo == cf.accountNo and cf.type == CREDIT cf.date >= ap.start and cf.date <= ap.end rule “increase balance for AccountPeriod Credits” when ap : AccountPeriod() acc : Account() cf : CashFlow( type == CREDIT, accountNo == acc.accountNo, date >= ap.start && <= ap.end ) then acc.balance += cf.amount; end 13 acc.balance += cf.amount
  • 14. CashFlow Example 14 rule "Increase balance for AccountPeriod Credits" when ap : AccountPeriod( ) acc : Account( ) cf : CashFlow( type == CashFlowType.CREDIT, accountNo == acc.accountNo, date >= ap.start && <= ap.end ) then acc.balance = acc.balance + cf.amount; end rule "Decrease balance for AccountPeriod Debits" when ap : AccountPeriod( ) acc : Account( ) cf : CashFlow( type == CashFlowType.DEBIT, accountNo == acc.accountNo, date >= ap.start && <= ap.end ) then acc.balance = acc.balance - cf.amount; end CashFlow date amount type accountNo 12-Jan-12 100 CREDIT 1 2-Feb-12 200 DEBIT 1 18-May-12 50 CREDIT 1 9-Mar-12 75 CREDIT 1 AccountingPeriod start end 01-JAN-2012 31-MAR-2012 Account accountNo balance 1 0 CashFlow date amount type accountNo 12-Jan-12 100 CREDIT 1 9-Mar-12 75 CREDIT 1 CashFlow date amount type accountNo 2-Feb-12 200 DEBIT 1 Account accountNo balance 1 -25
  • 15. CashFlow Example rule "Print blance for AccountPeriod" salience -50 when 15 ap : AccountPeriod() acc : Account( ) then System.out.println( "Account Number " + acc.accountNo + " balance " + acc.balance ); end Agenda 1 increase balance 2 decrease balance arbitrary 3 increase balance 4 print balance
  • 17. 01-JAN-2012 31-MAR-2012 accountNo balance update AccountPeriod set start=“01-Apr-2012” end = “31-MAR-2012” 17 AccountingPeriod start end Account 1 0 AccountingPeriod start end 01-Apr-2012 30-JUN-2012 Account accountNo balance 1 0
  • 18. CashFlow Example 18 rule "Increase balance for AccountPeriod Credits" when ap : AccountPeriod( ) acc : Account( ) cf : CashFlow( type == CashFlowType.CREDIT, accountNo == acc.accountNo, date >= ap.start && <= ap.end ) then acc.balance = acc.balance + cf.amount; end rule "Decrease balance for AccountPeriod Debits" when ap : AccountPeriod( ) acc : Account( ) cf : CashFlow( type == CashFlowType.DEBIT, accountNo == acc.accountNo, date >= ap.start && <= ap.end ) then acc.balance = acc.balance - cf.amount; end CashFlow date amount type accountNo 12-Jan-12 100 CREDIT 1 2-Feb-12 200 DEBIT 1 18-May-12 50 CREDIT 1 9-Mar-12 75 CREDIT 1 AccountingPeriod start end 01-Apr-2012 30-JUN-2012 Account accountNo balance 1 0 CashFlow date amount type accountNo 18-May-12 75 CREDIT 1 CashFlow date amount type accountNo Account accountNo balance 1 25
  • 19. 19 Conditional Elements not Bus( color = “red” ) exists Bus( color = “red” ) forall ( $bus : Bus( color == “red” ) ) forall ( $bus : Bus( floors == 2 ) Bus( this == $bus, color == “red” ) )
  • 21. Definitions public class Room { private String name // getter and setter methods here } public class Sprinkler { private Room room; private boolean on; // getter and setter methods here } public class Fire { private Room room; // getter and setter methods here } public class Alarm { }
  • 22. Definitions rule "When there is a fire turn on the sprinkler" when f : Fire() s : Sprinkler( room == f.room, on == false ) then modify( s ) { on = true }; println( "Turn on the sprinkler for room " + r.name ); end rule "When the fire is gone turn off the sprinkler" when r : Room( ) s : Sprinkler( room == r, on == true ) not Fire( room == r ) then modify( s) { on = false }; println( "Turn off the sprinkler for room " + r.name); end
  • 23. Definitions rule "Raise the alarm when we have one or more fires" when exists Fire() then insert( new Alarm() ); println( "Raise the alarm" ); end rule "Cancel the alarm when all the fires have gone" when not Fire() a: Alarm() then retract( a ); println( "Cancel the alarm" ); end
  • 24. Definitions rule "Status output when things are ok" when not Alarm() not Sprinkler( on == true ) then println( "Everything is ok" ); end
  • 25. Executing String[] names = new String[]{"kitchen", "bedroom", "office", "livingroom"}; Map<String,Room> name2room = new HashMap<String,Room>(); ! for( String name: names ){ Room room = new Room( name ); name2room.put( name, room ); ksession.insert( room ); Sprinkler sprinkler = new Sprinkler( room ); ksession.insert( sprinkler ); } ! ksession.fireAllRules() > Everything is ok
  • 26. Executing Fire kitchenFire = new Fire( name2room.get( "kitchen" ) ); Fire officeFire = new Fire( name2room.get( "office" ) ); ! FactHandle kitchenFireHandle = ksession.insert( kitchenFire ); FactHandle officeFireHandle = ksession.insert( officeFire ); ! ksession.fireAllRules(); > Raise the alarm > Turn on the sprinkler for room kitchen > Turn on the sprinkler for room office
  • 27. Executing ksession.retract( kitchenFireHandle ); ksession.retract( officeFireHandle ); ! ksession.fireAllRules() > Turn off the sprinkler for room office > Turn off the sprinkler for room kitchen > Cancel the alarm > Everything is ok rule "Status output when things are ok" when not Alarm() not Sprinkler( on == true ) then println( "Everything is ok" ); end
  • 29. public class Game { private int biggest; private int smallest; private int guessCount; public class Guess { private int value; public class GameRules { private int maxRange; private int allowedGuesses; public class RandomNumber { private int randomNumber;
  • 30. public class Game { private int biggest; private int smallest; private int guessCount; public class Guess { private int value; public class GameRules { private int maxRange; private int allowedGuesses; public class RandomNumber { private int randomNumber; <kbase name="NumberGuessKB" packages="org.drools.games.numberguess"> public class NumberGuessMain { public static void main(String[] args) { KieContainer kc = KieServices.Factory.get().getKieClasspathContainer(); final KieSession ksession = kc.newKieSession( "NumberGuessKS"); ksession.insert( new GameRules( 100, 5 ) ); ksession.insert( new RandomNumber() ); ksession.insert( new Game() ); ksession.fireAllRules(); } } <ksession name="NumberGuessKS"/> </kbase>
  • 31. rule Main when rules : GameRules( ) game : Game( guessCount < rules.allowedGuesses ) not Guess() then setFocus("Guess"); end rule "Get user Guess" agenda-group "Guess" when $r : RandomNumber() rules : GameRules( ) game : Game( ) 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 ) ); modify (game) { guessCount = game.guessCount + 1 } int i = Integer.parseInt( br.readLine() ); insert( new Guess( i ) ); end
  • 32. rule "Record the highest Guess" agenda-group "Guess" no-loop when game : Game( ) r : RandomNumber() guess : Guess( value > r.value) then modify ( game ) { biggest = guess.value }; retract( guess ); System.out.println( "Your guess was too high" ); end
  • 33. rule "Record the highest Guess" agenda-group "Guess" no-loop when game : Game( ) r : RandomNumber() guess : Guess( value > r.value) then modify ( game ) { biggest = guess.value }; retract( guess ); System.out.println( "Your guess was too high" ); end rule "Record the lowest Guess" agenda-group "Guess" when game : Game( ) r : RandomNumber() guess : Guess(value < r.value ) then modify ( game ) { smallest = guess.value }; retract( guess ); System.out.println( "Your guess was too low" ); end
  • 34. rule "Record the highest Guess" agenda-group "Guess" no-loop when game : Game( ) r : RandomNumber() guess : Guess( value > r.value) then modify ( game ) { biggest = guess.value }; retract( guess ); System.out.println( "Your guess was too high" ); end rule "Record the lowest Guess" agenda-group "Guess" when game : Game( ) r : RandomNumber() guess : Guess(value < r.value ) then modify ( game ) { smallest = guess.value }; retract( guess ); System.out.println( "Your guess was too low" ); end rule "Guess correct" agenda-group "Guess" when game : Game( ) r : RandomNumber() guess : Guess( value == r.value) then System.out.println( "You guessed correctly" ); end
  • 35. rule Main when rules : GameRules( ) game : Game( guessCount < rules.allowedGuesses ) not Guess() then setFocus("Guess"); end rule "No more Guesses" when rules : GameRules( ) game : Game( guessCount == rules.allowedGuesses ) not Guess() r : RandomNumber() then System.out.println( "You have no more guessesnThe correct guess was " + r.value ); end
  • 36. rooms = [ "basement" : new Room("basement"), "lounge" : new Room("lounge"), "dining room” : new Room("dining room"), “kitchen" : new Room("kitchen"), "ground floor hallway" : new Room("ground floor hallway"), "bedroom1" : new Room("bedroom1"), "bedroom2" : new Room("bedroom2"), “bathroom" : new Room("bathroom"), "office" : new Room("office"), "first floor hallway" : new Room("first floor hallway") ]; doors = [ "d1" : new Door( rooms[“kitchen", rooms["basement"] ), "d2" : new Door( rooms["ground floor hallway"], rooms["lounge"]), "d3" : new Door( rooms["ground floor hallway"], rooms["dining room"] ), "d4" : new Door( rooms["ground floor hallway"], rooms["kitchen"]), "d5" : new Door( rooms["ground floor hallway"], rooms[ "first floor hallway"] ), "d6" : new Door( rooms["first floor hallway"], rooms[ "bedroom1"] ), "d7" : new Door( rooms["first floor hallway”], rooms[ "bedroom2"] ), "d8" : new Door( rooms["first floor hallway"], rooms[ "bathroom"] ), "d9" : new Door( rooms["first floor hallway”], rooms[ "office"] ) ];
  • 37. characters = [ "hero" : new Character( "hero" ), "monster" : new Character( "monster" ) ]; items = [ "mace" : new Item( "mace" ), "cucumber" : new Item( "cucumber" ), "torch" : new Item( "torch" ), "umbrella" : new Item( "umbrella" ) ]; locations = [ "mace" : new Location( items["mace"], rooms["basement"] ), "monster" : new Location( characters["monster"], rooms["basement"] ), "cucumber" : new Location( items["cucumber"], rooms["kitchen"] ), "torch" : new Location( items["torch"], rooms["office"] ), "hero" : new Location( characters["hero"], rooms["ground floor hallway"] ), "umbrella" : new Location( items["umbrella"], rooms["ground floor hallway"] ) ];
  • 38. doors = [ "d1" : new Door( rooms[“kitchen", rooms["basement"] ), "d2" : new Door( rooms["ground floor hallway"], rooms["lounge"]), "d3" : new Door( rooms["ground floor hallway"], rooms["dining room"] ), "d4" : new Door( rooms["ground floor hallway"], rooms["kitchen"]), "d5" : new Door( rooms["ground floor hallway"], rooms[ "first floor hallway"] ), "d6" : new Door( rooms["first floor hallway"], rooms[ "bedroom1"] ), "d7" : new Door( rooms["first floor hallway”], rooms[ "bedroom2"] ), "d8" : new Door( rooms["first floor hallway"], rooms[ "bathroom"] ), "d9" : new Door( rooms["first floor hallway”], rooms[ "office"] ) ]; query connect( Room $x, Room $y ) Door($id, $x, $y;) or Door($id, $y, $x;) end
  • 39. locations = [ query things(Character $char, List $things) $char := Character() Location( $char, $room; ) $things := List() from accumulate( Location($thing, $room; thing != $char), collectList( $thing ) ) end "mace" : new Location( items["mace"], rooms["basement"] ), "monster" : new Location( characters["monster"], rooms["basement"] ), "cucumber" : new Location( items["cucumber"], rooms["kitchen"] ), "torch" : new Location( items["torch"], rooms["office"] ), "hero" : new Location( characters["hero"], rooms["ground floor hallway"] ), "umbrella" : new Location( items["umbrella"], rooms["ground floor hallway"] ) ]; query exits(Character $char, List $exits) $char := Character() Location( $char, $room; ) $exits := List() from accumulate( connect($room, $exit;), collectList( $exit ) ) end
  • 40. query look(Character $char, List $things, List $exits) $char := Character() things( $char, $things; ) exits( $char, $exits; ) end rule lookCmd agenda-group "commands" lock-on-active auto-focus when lc : LookCommand( c : character ) Location( thing == c, $room : target ) ?look( c, things, exits; ) then str = "You are in the " + $room + "n"; str +="You can see " + things + "n"; str +="Available exits are " + exits + "n"; str +="n"; res = new Response( str ); res.localId = lc.requestId; insert( res ); end
  • 41. rule lookCmd agenda-group "commands" lock-on-active auto-focus when lc : LookCommand( c : character ) Location( thing == c, $room : target ) ?look( c, things, exits; ) then str = "You are in the " + $room + "n"; str +="You can see " + things + "n"; str +="Available exits are " + exits + "n"; str +="n"; res = new Response( str ); res.localId = lc.requestId; insert( res ); end
  • 42. rule validMove agenda-group "commands" lock-on-active auto-focus when mc : MoveCommand( c : character, r : room ) l : Location( thing == c, ltarget : target ) exists ?connect( r, ltarget; ) then modify( l ) { target = r }; res = new Response( "You have entered the " + l.target + "n" ); res.localId = mc.requestId; insert( res ); end rule lookCmd agenda-group "commands" lock-on-active auto-focus when lc : LookCommand( c : character ) Location( thing == c, $room : target ) ?look( c, things, exits; ) then str = "You are in the " + $room + "n"; str +="You can see " + things + "n"; str +="Available exits are " + exits + "n"; str +="n"; res = new Response( str ); res.localId = lc.requestId; insert( res ); end
  • 43. rule validPickup agenda-group "commands" lock-on-active auto-focus when pc : PickupCommand( c : character, t : thing) cl : Location( thing == c ) tl : Location( thing == t, target == cl.target ) then insert( new Holding( c, t ) ); modify( tl ) { target = c }; res = new Response( "You have picked up the " + t + "n" ); res.localId = pc.requestId; insert( res ); end
  • 44. rule validPickup agenda-group "commands" lock-on-active auto-focus when pc : PickupCommand( c : character, t : thing) cl : Location( thing == c ) tl : Location( thing == t, target == cl.target ) then insert( new Holding( c, t ) ); modify( tl ) { target = c }; res = new Response( "You have picked up the " + t + "n" ); res.localId = pc.requestId; insert( res ); end rule validDrop agenda-group "commands" lock-on-active auto-focus when dc : DropCommand( c : character, t : thing) cl : Location( thing == c ) tl : Location( thing == t ) h : Holding( c, t;) then modify( tl ) { target = cl.target }; retract ( h ); insert( new DropEvent( c, t ) ); res = new Response( "You have droped the " + t + "n" ); res.localId = dc.requestId; insert( res ); end
  • 45. rule validGive agenda-group "commands" lock-on-active auto-focus when gc : GiveCommand( $giver : giver, $thing : thing ) // They are in the same room giverl : Location( thing == gc.giver ) Location( thing == gc.receiver, target == giverl.target ) // The giver must be holding the thing h : Holding( $giver, $thing;) then modify( h ) { character = gc.receiver }; insert( new GiveEvent( gc.giver, gc.thing, gc.receiver ) ); res = new Response( "You have given the " + gc.thing + " to " + gc.receiver + "n" ); res.localId = gc.requestId; insert( res ); end