package org.drools.games.wumpus

global java.util.Random randomInteger;

dialect "mvel"

rule "Start Game Init Process" when
then
   insert( new Init() );
end

rule "Insert Score" when
    Init()
    not Score()
then
    insert( new Score() );
end        
	
rule "Create Cells" when
    Init()
	$i : Integer() from [0, 1, 2, 3, 4]
	$j : Integer() from [0, 1, 2, 3, 4]
	$c : Cell() from new Cell($i, $j)
then
    insert( $c );
end

rule "Show First Cell" when
    Init()
    $c : Cell( row == 0, col == 0, hidden == true )
then
    modify( $c ) { hidden = false };
end    

rule "Create Pitt" when
    Init()
    $c : Cell( row != 0, col != 0 )
    Number( this > 0 && <= 20 ) from randomInteger.nextInt( 100 )
then
    Pit pit = new Pit( $c.row, $c.col )    
    insert( pit );
end    

rule "Create Wumpus" when
    Init()
    not Wumpus()// here to break sharing, to force new random numbers, also retriggers on retraction
    $row : Integer() from randomInteger.nextInt( 4 )
    $col : Integer() from randomInteger.nextInt( 4 )
then
    Wumpus wumpus = new Wumpus($row, $col);
    insert( wumpus );    
end

rule "Invalid Wumpus" when
    Init()
    $w : Wumpus( row == 0, col == 0 )    
then
    retract( $w ); // retraction triggers the "not" CE
end    

rule "Create Gold" when
    Init()
    not Gold() // here to break sharing, to force new random numbers, also retriggers on retraction
    $row : Integer() from randomInteger.nextInt( 4 )
    $col : Integer() from randomInteger.nextInt( 4 )
then
    Gold gold = new Gold($row, $col);
    insert( gold );
end

rule "Invalid Gold"  when
    Init()
    $g : Gold( row == 0, col == 0 )  
    not Hero( gold == true ) // gold can be in row first square, if hero is carrying it
then
    retract( $g ); // retraction triggers the "not" CE
end   

rule "Create Hero" when
    Init()
    exists Wumpus( row != 0 || col != 0 ) // create the Hero after the Wumpus has been created in a safe location
    exists Gold( row != 0 || col != 0 ) // create the Hero after the Gold has been placed in a good location
then
    insert( new Hero( 0, 0 ) );
end

rule "Trigger Play" salience -100 when
    $i : Init()
then
    retract( $i );
    insert( new Play() );
    insert( new SensorArray() );    
end

rule "End Play" salience 100 when
    Reset()
    $p : Play()
then
    retract( $p );
end

rule "Reset Cells" when
    Reset()
    $c : Cell()
then
    retract( $c );
end 

rule "Reset Pits" when
    Reset()
    $p : Pit()
then
    retract( $p );
end 

rule "Reset Score" when
    $r : Reset(resetScore == true)
    $s : Score()
then
    retract( $s );
end  

rule "Reset Wumpus, Gold and Hero" when
    $r : Reset()
    not Pit()
    not Cell()
    not PitDeath()
    not GoldWin()
    not WumpusDeath()
    $w : Wumpus()
    $g : Gold()
    $h : Hero()
then
    retract( $w );
    retract( $g );    
    retract( $h );
    retract( $r );
    insert( new Init() );
end 

  