Skip to content

Instantly share code, notes, and snippets.

@ptrelford
Last active August 29, 2015 14:01
Show Gist options
  • Save ptrelford/4bed1b868927b394c9e6 to your computer and use it in GitHub Desktop.
Save ptrelford/4bed1b868927b394c9e6 to your computer and use it in GitHub Desktop.
Simplest Behaviour Tree
type Result = Success | Failure | Running
type Behavior =
| Action of (unit -> Result)
| Selector of Behavior list
| Sequence of Behavior list
let rec behave = function
| Action f -> f ()
| Selector xs -> select xs
| Sequence xs -> sequence xs
and select xs =
match xs with
| [] -> Failure
| x::xs' ->
match behave x with
| Failure -> select xs'
| Success -> Success
| Running -> Running
and sequence xs =
match xs with
| [] -> Failure
| x::xs' ->
match behave x with
| Success -> sequence xs'
| Failure -> Failure
| Running -> sequence xs
let getToPlantingGrounds steps =
let i = ref 0
fun () ->
incr i
if !i < steps then
printfn "Action - searching planting grounds"
Running
else
Success
let plantSeeds () =
printfn "Action - plant"
Success
let weedsNotCoveringGround() =
printfn "Conditional - is there space"
Failure
let run () =
let plant = Action(plantSeeds)
let plantIfThereIsSpace =
Selector [Action(weedsNotCoveringGround); plant]
let sequence = Sequence [Action(getToPlantingGrounds 10); plant]
let root = Selector [sequence; plantIfThereIsSpace]
behave root
run ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment