# Your First Behavior Tree

Behavior trees define how characters make decisions. They model the thought process: "Try this first, and if it fails, try that instead." In this chapter, you will create your first behavior tree for Martha.

## What is a Behavior Tree?

A behavior tree is a hierarchy of nodes that executes from top to bottom. Each node either **succeeds** or **fails**, and the tree uses that result to decide what to do next.

There are two fundamental building blocks:

- **`choose`** (Selector): Try children in order until one succeeds. Think "try A, else try B, else try C."
- **`then`** (Sequence): Run children in order, stopping if any fails. Think "do A, then B, then C -- all must succeed."

## Your First Tree

Let us give Martha a simple baking behavior:

```storybook
behavior Martha_BakeRoutine {
    choose what_to_do {
        then fill_special_orders {
            CheckSpecialOrders
            PrepareSpecialIngredients
            BakeSpecialItem
        }

        then daily_bread {
            MixDough
            KneadDough
            BakeLoaves
        }

        CleanWorkstation
    }
}
```

Reading this as a story:

> Martha will **choose** what to do. First, she tries to **fill special orders**: she checks for orders, prepares special ingredients, and bakes the item. If that path fails (maybe there are no special orders), she tries **daily bread**: she mixes dough, kneads it, and bakes loaves. If even that fails, she simply cleans her workstation.

## Understanding choose (Selector)

A `choose` node tries its children one at a time. As soon as one succeeds, it stops and returns success. If all children fail, it returns failure.

```storybook
choose response {
    HandleUrgentOrder   // Try first: handle urgent order
    ServeCustomer       // If that fails: serve a customer
    RestockShelves      // If that fails: restock
}
```

This is like a priority list -- the first successful option wins.

## Understanding then (Sequence)

A `then` node runs its children in order. If any child fails, the whole sequence fails and stops. All children must succeed for the sequence to succeed.

```storybook
then make_sourdough {
    MixDough         // Must succeed
    KneadDough       // Must succeed
    FirstRise        // Must succeed
    ShapeLoaves      // Must succeed
}
```

If `MixDough` fails (no flour available), the whole process stops.

## Naming Your Nodes

Both `choose` and `then` accept optional labels:

```storybook
choose daily_priority {
    then morning_baking { ... }
    then afternoon_sales { ... }
}
```

Labels are optional but highly recommended. They make your trees readable as narratives and help with debugging. Compare:

```storybook
// Without labels (hard to read)
choose {
    then { MixDough, BakeLoaves }
    then { ServeCustomer, CollectPayment }
}

// With labels (reads like a story)
choose priority {
    then baking { MixDough, BakeLoaves }
    then sales { ServeCustomer, CollectPayment }
}
```

## Combining choose and then

Behavior trees become powerful when you nest selectors and sequences:

```storybook
behavior Jane_PastryRoutine {
    choose pastry_priorities {
        // Highest priority: fill custom cake orders
        then custom_orders {
            ReviewCakeOrder
            DesignDecoration
            BakeAndDecorate
            PackageForPickup
        }

        // If no orders: prepare display pastries
        then display_pastries {
            RollPastryDough
            PrepareFillings
            AssemblePastries
            ArrangeDisplay
        }

        // Default: experiment with new recipes
        ExperimentWithFlavors
    }
}
```

Reading this as narrative:

> Jane always prioritizes custom cake orders. She reviews the order, designs the decoration, bakes and decorates, then packages it. If there are no orders, she prepares display pastries. If there is nothing else to do, she experiments with new flavors.

## Actions

The leaf nodes in a behavior tree are **actions** -- concrete things a character does:

```storybook
MixDough              // Simple action
KneadDough            // Simple action
ServeCustomer         // Simple action
```

Actions are identifiers that the runtime interprets. They represent the actual behaviors executed in your simulation.

## A Complete Example

Here is a behavior tree for the morning rush at the bakery:

```storybook
behavior Bakery_MorningRush {
    ---description
    Handles the busy morning rush when customers are
    lining up for fresh bread and pastries.
    ---

    choose morning_priority {
        then serve_waiting_customer {
            GreetCustomer
            TakeOrder
            PackageItems
            CollectPayment
            ThankCustomer
        }

        then restock_display {
            CheckDisplayLevels
            FetchFromKitchen
            ArrangeOnShelves
        }

        then quick_bake {
            CheckInventory
            StartQuickBatch
            MonitorOven
        }
    }
}
```

Notice the prose block (`---description ... ---`) at the top of the behavior. You can document what the behavior does right alongside the code.

## Behavior-Character Connection

Characters link to behaviors using the `uses behaviors` clause:

```storybook
character Martha: Human {
    age: 34

    uses behaviors: [
        { tree: Martha_BakeRoutine },
        { tree: HandleEmergency }
    ]
}
```

This tells the simulation that Martha uses two behavior trees. We will cover advanced behavior linking (priorities, conditions) in [Making Characters Act](./04-making-characters-act.md).

## Next Steps

Your behavior trees so far make decisions between options and run sequences of actions. In [Making Characters Act](./04-making-characters-act.md), you will learn how to add conditions, decorators, and parameters to create truly dynamic behaviors.

---

**Reference**: For complete behavior tree syntax, see the [Behavior Trees Reference](../reference/11-behavior-trees.md).
