# Automating your story with rules

> Add dependable automatic reactions to your LoreHat story with zero coding — pick the right tool for each mechanic, borrow five real story recipes, and copy an AI prompt to design your rules.

A **Rule** is an automatic, behind-the-scenes reaction built right into your story — no coding required. Whenever something happens in chat (like a player sending a message, entering a new scene, or reaching a milestone in a variable), LoreHat checks your condition and runs the exact action you chose, every single time.

Open **Advanced → Rules** in Studio to create rules with simple point-and-click dropdowns.

![Studio Advanced Rules screen showing the default no-code way to automate a story with the Add rule button](/illustrations/studio-systems/studio-rules.webp)

## When should you use a Rule — and when is a simpler tool better?

Think of the AI as a **brilliant improvisational actor** and Rules as your **dependable stagehand**. Let the AI handle dialogue, emotion, and creativity; use a Rule whenever the **exact same moment should always produce the exact same result** without hoping the AI remembers to do math or flip a switch.

| What you want to happen | Best tool to use | Why |
| :-- | :-- | :-- |
| _"Elena is playful on the surface, but dodges questions about her brother"_ | **Characters** & **Story → Global story guidance** | Personality and dialogue nuance belong to the AI |
| _"Bring up Harbor Law only when the player asks about the docks"_ | **World Lore** | Built specifically for on-demand lore |
| _"Make replies tense and cinematic during a chase"_ | **Writing style** | Writing styles shape prose rhythm without hard-coded logic |
| _"Track whether the player found the brass key (and let the AI notice)"_ | **Work variables** (with **Allow AI to adjust**) | Variables remember facts; AI updates work great for flexible story judgment |
| _"Add +1 turn counter every message, flip `storm_active` when entering the Harbor, or trigger a milestone cue once `trust >= 60`"_ | **Advanced → Rules** | Predictable every time, instant, and 100% consistent |
| _"Change the chat's color palette or background when `storm_active` is true"_ | **Visuals & interactivity → + Derive a visual version** (triggered by a Rule's variable) | Visual versions automatically react to variables |
| _"Roll RPG dice with modifiers, check inventory weight, or run complex math"_ | **Advanced → Script** (with Studio's **Copy AI prompt** button) | Scripts handle math and custom logic beyond simple forms |

> **Golden rule of simplicity:** If your card is a pure conversation or slow-burn relationship story, you may not need a single Rule at all. Add Rules only when you notice the AI forgetting to count, forgetting to flip a flag, or missing a scene transition cue.

## Every Rule reads like one plain-English sentence

Open **Advanced → Rules** and click **Add rule**. Every rule follows the exact same three-part sentence:

1. **When (Trigger):** What moment wakes the rule up?
   - **Chat starts** — once, when a brand-new chat opens
   - **Player sends message** — right as the player hits Send (before the character replies)
   - **Reply received** — right after the character finishes replying
   - **Story node entered** — the moment the story steps into a specific scene
   - **Choice selected** — when the player takes a named story choice
   - **Variables change** — whenever a variable's value actually changes _(Want to react to interactive panel button clicks? Those are handled in **Advanced → Script** via `component.action`.)_
2. **Only if (all match):** Optional checks that must all be true right now _(for example: `trust >= 50`, `storm_active` is `false`, or `turnNumber >= 10`)_.
3. **Do (Effects):** One or more automatic actions LoreHat runs immediately:
   - **Set value** — update a variable (set it to a value, or add/subtract a number)
   - **Go to story node** — move the story to another scene
   - **Apply a writing style** — switch on one of your saved Writing styles for that turn
   - **Add hint** — whisper a secret one-turn stage direction to the AI _(for example: "Describe rain drumming on the roof")_
   - **Suggest reading** — nudge the AI to pull in a helpful piece of lore _(To change chat colors or backgrounds automatically, have a Rule set a variable like `storm_active = true` and attach that variable to a visual version under **Visuals & interactivity → + Derive a visual version**.)_

Before adding rules, create the variables they will use under **Work variables** so Studio can offer them in dropdown menus automatically.

![Studio Work variables screen showing structured variables like level, topic, and streak ready to use in conditions and rules](/illustrations/studio-systems/studio-variables.webp)

## Five ready-to-borrow story recipes

### Recipe 1: Trigger a rainstorm and shift the chat colors (Mystery / Noir)

- **Variables needed:** `storm_active` (Yes/No, initial `false`)
- **Rule name:** `harbor-storm-start`
- **When:** **Story node entered** → _At the Harbor_
- **Only if:** `storm_active` equals `false`
- **Do:**
  1. **Set value:** `storm_active` = `true`
  2. **Add hint:** _"Describe the sudden drop in temperature, wind howling off the pier, and rain drumming on the warehouse roof."_
- **Visual bonus:** Under **Visuals & interactivity**, click **+ Derive a visual version** named _Harbor Storm_ with condition `storm_active == true`. The moment the player reaches the harbor, the entire chat shifts into stormy slate-blue tones — and switches back when another rule sets `storm_active` to `false` inside the shelter!

### Recipe 2: Count turns automatically for timed events (Slice of Life / Thriller)

- **Variables needed:** `turns_spent` (Number, initial `0`)
- **Rule name:** `count-turns`
- **When:** **Player sends message**
- **Only if:** _(leave empty so it runs every turn)_
- **Do:** **Set value:** add `1` to `turns_spent`
- **Why it's great:** Now you can trigger a midnight curfew, a surprise phone call, or an alternate character profile when `turns_spent >= 10` — without ever asking the AI to count turns in its head!

### Recipe 3: Shift prose tone once trust deepens (Slow-Burn Romance)

A Rule's **Apply a writing style** effect applies for **that single triggered turn**. So for a **lasting** tone shift plus a one-time turning-point cue, pair a conditional Writing style with a guarded one-time Rule:

- **Variables needed:** `trust` (Number, initial `20`, **Allow AI to adjust** enabled) and `warm_tone_unlocked` (Yes/No, initial `false`)
- **Lasting style change (no rule needed!):** In **Writing style** (or **World Lore → Add writing style**), create **Warm & Candid** and set its own **Condition** to `trust >= 60`. From that moment on, every turn while `trust >= 60` automatically uses it!
- **One-time turning-point Rule (`unlock-warm-moment`):**
  - **When:** **Player sends message** _(the rule reads the saved `trust` before the reply is written, so the hint reaches the AI with the first message the player sends after the threshold)_
  - **Only if:** `trust >= 60` AND `warm_tone_unlocked` equals `false`
  - **Do:**
    1. **Set value:** `warm_tone_unlocked` = `true`
    2. **Apply a writing style:** **Warm & Candid** _(if the AI raises `trust` while writing a reply, the style starts with the next reply)_
    3. **Add hint:** _"The character has finally let their guard down with the player; let warmth show naturally without announcing it."_

### Recipe 4: Celebrate a study streak (Language Buddy / Tutor)

- **Variables needed:** `streak` (Number, initial `0`, **Allow AI to adjust** enabled), `celebrated_five` (Yes/No, initial `false`)
- **Rule name:** `five-streak-praise`
- **When:** **Player sends message**. If the AI records the fifth correct answer while writing its reply, the rule checks the streak when the learner sends their next message, and the AI gets the celebration hint for its reply to that message. If the learner stops after five answers, the celebration does not appear.
- **Only if:** `streak >= 5` AND `celebrated_five` equals `false`
- **Do:**
  1. **Set value:** `celebrated_five` = `true`
  2. **Add hint:** _"Briefly celebrate the learner's 5-answer streak in character, then offer a slightly livelier real-world scenario."_
- **Notice the safety flag (`celebrated_five`):** Flipping a Yes/No flag to `true` ensures the celebration fires **once**, instead of repeating on turn 6, 7, and 8!

### Recipe 5: Enforce a dramatic deadline (Investigation / Escape Room)

A countdown needs **two tiny rules** — one to tick the clock down, and one to fire when time runs out:

- **Variables needed:** `hours_left` (Number, initial `6`) and `deadline_hit` (Yes/No, initial `false`)
- **Rule A (`tick-down-hours`):**
  - **When:** **Player sends message** _(or **Story node entered** if time passes only when changing locations)_
  - **Only if:** `hours_left > 0`
  - **Do:** **Set value:** add `-1` to `hours_left`
- **Rule B (`time-ran-out`):**
  - **When:** **Variables change**
  - **Only if:** `hours_left <= 0` AND `deadline_hit` equals `false`
  - **Do:**
    1. **Set value:** `deadline_hit` = `true`
    2. **Go to story node:** _Dawn Breaks — The Harbor Closes_
    3. **Add hint:** _"Time has run out; the ferry horn sounds in the distance and the final confrontation begins immediately."_

## Good habits that keep rules bug-free

- **Name every rule clearly:** Use names like `harbor-storm-start` or `five-streak-praise` instead of `Rule 1` or `test`. Future-you will thank you.
- **One job per rule:** A work can hold up to **32 rules**. Keeping each rule focused on one crisp beat makes it easy to toggle **Enabled** on or off while testing.
- **Give each variable one clear owner:** Avoid letting both a Rule _and_ the AI fight over changing the exact same counter on the same turn. For example, let a Rule own `turns_spent`, and let the AI own `trust`.
- **Add a one-time flag when a reaction shouldn't repeat:** Just like `celebrated_five` in Recipe 4, pair `>=` checks with a Yes/No flag if the hint should only happen once.

## How to test your rules in Preview chat

After adding or editing a rule, wait for **Draft saved**, open **Preview chat → Restart**, and verify four quick things:

1. **It fires when expected:** Trigger the exact scene, message, or threshold and confirm the variable, writing style, or visual theme actually changes.
2. **It stays quiet when it shouldn't:** Send an unrelated message first to confirm it didn't fire early.
3. **It doesn't double-fire:** Trigger the moment twice (or send one more message right after) to confirm counters don't jump twice and one-time hints don't repeat endlessly.
4. **Old rules still work:** Double-check earlier rules and story branches so nothing conflicts.

> **Why "the chat didn't crash" isn't enough:** If a rule ever hits an unexpected problem (such as pointing at a deleted variable or scene), LoreHat skips that rule safely so the player's chat never breaks. Always confirm in **Preview chat** that your expected change actually happened!

## Copy-paste prompt: Ask your AI to design your Studio Rules

Know the story effect you want, but unsure which triggers, variables, and conditions to pick in Studio? Paste this into your favorite AI assistant — it will hand back exact click-by-click Studio settings (no code!):

```text
Help me design no-code LoreHat Studio Rules for my interactive story. Do NOT write JavaScript — give me exact point-and-click settings for Studio's "Work variables" and "Advanced → Rules" screens.

My story & genre: [e.g., Cozy detective mystery in a coastal town]
What I want to happen automatically:
1. [e.g., Count how many places the player visits, and start a rainstorm on visit 4]
2. [e.g., When the player's trust reaches 60, shift the tone to warmer dialogue — only once]
3. [e.g., If suspiciousness reaches 5, jump to the "Confrontation" scene]

Available Studio Rule triggers: Chat starts, Player sends message, Reply received, Story node entered, Choice selected, Variables change.
Available Studio Rule effects: Set value (set or add/subtract), Go to story node, Apply a writing style, Add hint (one-turn AI note), Suggest reading. (For visual theme shifts, have a Rule set a variable and pair it with Visuals & interactivity → + Derive a visual version.)

Please return:
1. A clean table of Work variables to create (Name, Type, Initial value, and whether "Allow AI to adjust" should be ON or OFF so the AI and rules don't fight).
2. For each Rule:
   - Rule name
   - When (Trigger)
   - Only if (all match) conditions (include any one-time Yes/No guard flag so it doesn't repeat by mistake)
   - Do (Effects)
3. A quick 3-step checklist for testing all of these in Preview chat.
```

## Ready for logic a form can't express?

If you ever need dice rolls, inventory capacity limits, custom keyword matching, or buttons wired to interactive panels, move up to **Advanced → Script** — and you still don't have to code by hand! Studio's built-in **Copy AI prompt** button packages your work's exact variables and rules so an AI assistant can write and test the script for you.

Continue to [Automation & custom scripts guide](/en/creator/workers-reference/), or return to [World Lore, writing styles, variables, and visuals](/en/creator/systems/).
