Skip to content

Instantly share code, notes, and snippets.

@SethTisue
Created June 27, 2012 16:17
Show Gist options
  • Save SethTisue/3005156 to your computer and use it in GitHub Desktop.
Save SethTisue/3005156 to your computer and use it in GitHub Desktop.
Example of an optional command block in a NetLogo extension primitive
public static class Reflect
extends DefaultCommand
implements org.nlogo.nvm.CustomAssembled
{
public Syntax getSyntax()
{
int[] right = { Syntax.TYPE_NUMBER , Syntax.TYPE_BOOLEAN_BLOCK ,
Syntax.TYPE_COMMAND_BLOCK | Syntax.TYPE_OPTIONAL } ;
return Syntax.commandSyntax( right ) ;
}
public String getAgentClassString()
{
return "T:--P-" ;
}
public void assemble( org.nlogo.nvm.AssemblerAssistant a )
{
a.block() ;
a.done() ;
}
public void perform( Argument args[] , final Context context )
throws ExtensionException, LogoException
{
try
{
// we're breaking the rules here a little bit but not it a way that it
// hasn't been before either for cities or p2p. ev 7/13/07
reflect( (Turtle) context.getAgent() , args[ 0 ].getDoubleValue() ,
((org.nlogo.nvm.ExtensionContext) context).nvmContext() ,
((org.nlogo.nvm.Argument)args[ 1 ]).getReporter() ) ;
}
catch( org.nlogo.api.AgentException e )
{
throw new ExtensionException( e.getMessage() ) ;
}
}
public void reflect( Turtle turtle , double dist ,
org.nlogo.nvm.Context context ,
org.nlogo.nvm.Reporter condition )
throws org.nlogo.api.AgentException , LogoException
{
org.nlogo.agent.Patch nextPatch = (org.nlogo.agent.Patch) nextPatch( turtle ) ;
double distToBoundary = distanceToBoundary( turtle , nextPatch ) ;
org.nlogo.nvm.Context freshContext = new org.nlogo.nvm.Context( context , nextPatch ) ;
condition.checkAgentClass( nextPatch , context ) ;
while ( dist >= distToBoundary )
{
Patch lastPatch = turtle.getPatchHere() ;
turtle.jump( distToBoundary ) ;
Object value = freshContext.evaluateReporter( nextPatch , condition ) ;
if( value instanceof Boolean && ( ( Boolean ) value ).booleanValue() )
{
if( lastPatch.pycor() == nextPatch.pycor() )
{
turtle.heading( - turtle.heading() ) ;
}
else
{
turtle.heading( 180 - turtle.heading() ) ;
}
org.nlogo.agent.AgentSet patchSet = new org.nlogo.agent.ArrayAgentSet
( org.nlogo.agent.Patch.class , 1 , false , nextPatch.world() ) ;
patchSet.add( nextPatch ) ;
context.runExclusiveJob( patchSet , context.ip + 1 ) ;
}
dist -= distToBoundary ;
nextPatch = (org.nlogo.agent.Patch) nextPatch( turtle ) ;
distToBoundary = distanceToBoundary( turtle , nextPatch ) ;
}
turtle.jump( dist ) ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment