Advanced

Juice: making the state visible without changing it

Feel comes from presentation reading the state and adding to the paint, never from the state reading the paint. A particle burst, a screen shake, and a hit flash are all effects produced from a state difference, and none of them may feed back.

What you will see

The identical state. A different state means an effect is doing rules work.

About 1 min of reading

Try It

Emit one effect from a difference

1

Diff the states

printf 'const hits = n.hits - o.hits; if (hits > 0) fx.push({ type: "burst", at: n.player.x, n: Math.min(hits * 6, 24) }); ' | tee game/fx.js

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The burst count comes from the difference and is capped.
2

Cap the total on screen

printf 'fx = fx.reduce((a, e) => a + e.n, 0); if (fx > 200) trim to 200 ' | tee -a game/fx.js

Before you run it, say out loud what it will print. Then open the answer.

What it prints
A hard ceiling. Without it, a large hit produces a frame that takes a second.
3

Prove the effects do not write state

run the same inputs with the effects disabled and print the final state

Before you run it, say out loud what it will print. Then open the answer.

What it prints
The identical state. A different state means an effect is doing rules work.
Do not let an effect change the state. Then the game depends on how much juice ran, and the replay stops matching.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

State difference to an effect
1 Rules return the new state
↓
2 Caller diffs old and new
↓
3 Caller emits the effects implied
↓
4 Draw reads state plus effects
Why this works
The order that keeps it clean

Rules, then diff, then emit effects, then draw. The draw reads the state and the effect list, and nothing else.

Where juice lies

When it is the only feedback for a rule. If the player cannot tell what happened without the effect, the rule needs a clearer state read, not more particles.

Examples

Derive the effect from the difference

The rules return the new state; the caller compares it to the old and emits the effects that the difference implies.

Effects never write state

A particle that damages on contact is a rule, not an effect. If it writes state, it belongs to the rules and not to the juice.

Budget the juice

Cap the particles on screen. An uncapped burst on a big hit is a frame that takes a second, and the cap is the limit.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Recording and replaying a run
Previous Lesson
Recording and replaying a run
Next Lesson
Balancing a game by measurement, not by play
Balancing a game by measurement, not by play →