# Build your first cascade slot

> A tutorial that builds a 6x5 cascade slot in about 80 lines of TypeScript, for readers new to pixi-reels.

Source: https://pixi-reels.schmooky.dev/learn/your-first-cascade/

This tutorial builds a 6x5 cascade slot in about 80 lines of TypeScript. A click drops the symbols in, the game detects 3-in-a-row wins, the winners vanish, new symbols refill from above, and that repeats until there are no more wins. You need no prior `pixi-reels` knowledge. PixiJS basics help.

If you already know `pixi-reels`, skim the [cascades guide](/mechanics/cascade/#concept) for the mental model and the [API reference](/reference/api-reelset/) for the verbs.

## Step 0. Install

```bash
npm install pixi-reels pixi.js gsap
```

`pixi-reels` requires PixiJS v8 and uses GSAP for its tweens. Both are peer dependencies.

## Step 1. Boot PixiJS

```ts
import { Application } from 'pixi.js';
import { gsap } from 'gsap';

const app = new Application();
await app.init({ background: 0xffffff, resizeTo: window, antialias: true });
document.body.appendChild(app.canvas);

// Sync GSAP to PixiJS so tweens run in hidden tabs / iframes.
gsap.ticker.remove(gsap.updateRoot);
app.ticker.add(() => gsap.updateRoot(app.ticker.lastTime / 1000));
```

The two GSAP lines are required. Without them GSAP freezes in background tabs and your cascade animations stall mid-drop. See [the GSAP gotcha section in CLAUDE.md](https://github.com/schmooky/pixi-reels/blob/main/CLAUDE.md#known-gotchas).

## Step 2. Wire the reel set

```ts
import { ReelSetBuilder, SpriteSymbol, SpeedPresets, enableDebug } from 'pixi-reels';

const SYMBOLS = ['A', 'B', 'C', 'D', 'wild'];

const reelSet = new ReelSetBuilder()
  .reels(6)
  .visibleCells(5)
  .symbolSize(95, 95)
  .symbolGap(5, 5)
  .symbols((r) => {
    for (const id of SYMBOLS) {
      r.register(id, SpriteSymbol, { textures });  // your loaded sprite textures
    }
  })
  .weights({ A: 18, B: 14, C: 10, D: 6, wild: 2 })
  .speed('normal', SpeedPresets.NORMAL)
  .tumble({
    fall:   { duration: 280, ease: 'sine.in',       cellStagger: 40 },
    dropIn: { duration: 480, ease: 'back.out(1.6)', cellStagger: 50, distance: 'perHole' },
  })
  .ticker(app.ticker)
  .build();

app.stage.addChild(reelSet);
enableDebug(reelSet);   // exposes window.__PIXI_REELS_DEBUG, used in Step 7
```

The `tumble` call switches the default spin mode to cascade and wires the three cascade phases (`cascade:fall`, `cascade:place`, `cascade:dropIn`). Its config is animation parameters only. Multipliers, sound and win clearing are your code, listening to events.

## Step 3. A fake server

In production you call your real backend. For this tutorial, a function returns a random grid, and a second one returns a cascade refill that follows the gravity convention.

```ts
function randSymbol(): string {
  const weights: Record<string, number> = { A: 18, B: 14, C: 10, D: 6, wild: 2 };
  const total = Object.values(weights).reduce((a, b) => a + b, 0);
  let r = Math.random() * total;
  for (const [id, w] of Object.entries(weights)) {
    r -= w;
    if (r <= 0) return id;
  }
  return 'A';
}

import type { Cell } from 'pixi-reels';

const server = {
  spin: async (): Promise<string[][]> => {
    await new Promise((r) => setTimeout(r, 400 + Math.random() * 600));
    return Array.from({ length: 6 }, () => Array.from({ length: 5 }, randSymbol));
  },

  cascade: async (prev: string[][], winners: Cell[]) => {
    await new Promise((r) => setTimeout(r, 120));
    const winnersByReel = new Map<number, Set<number>>();
    for (const w of winners) {
      if (!winnersByReel.has(w.reel)) winnersByReel.set(w.reel, new Set());
      winnersByReel.get(w.reel)!.add(w.cell);
    }
    return prev.map((column, reel) => {
      const losers = winnersByReel.get(reel);
      if (!losers || losers.size === 0) return [...column];
      const survivors = column.filter((_, cell) => !losers.has(cell));
      const fillers = Array.from({ length: losers.size }, randSymbol);
      // Convention: top losers.size cells = new, rest = survivors in original order.
      return [...fillers, ...survivors];
    });
  },
};
```

The cascade function follows the [gravity convention](/mechanics/cascade/#refill-geometry-the-survivor-convention). If you have a real server, its response must follow the same convention.

## Step 4. Detect winners

This is game-rule code. A left-anchored run of 3 or more matching symbols at the same cell index counts as a win, and `wild` matches anything.

```ts
import type { Cell } from 'pixi-reels';

function detectWinners(grid: string[][]): Cell[] {
  const winners: Cell[] = [];
  for (let cell = 0; cell < 5; cell++) {
    const head = grid[0][cell];
    if (head === 'wild') continue;
    let run = 1;
    for (let reel = 1; reel < 6; reel++) {
      if (grid[reel][cell] === head || grid[reel][cell] === 'wild') run++;
      else break;
    }
    if (run >= 3) {
      for (let reel = 0; reel < run; reel++) winners.push({ reel, cell });
    }
  }
  return winners;
}
```

## Step 5. Drive a round

`runCascade` replaces a hand-rolled `while` loop with one call. It does the following.

1. Calls `detectWinners(grid)` with the current visible grid.
2. If the list is empty, ends the chain and resolves with a `RunCascadeResult` (`{ chainLength, totalWinners, finalGrid, wasSkipped }`).
3. Otherwise fires `cascade:chain:start`, calls `reelSet.destroySymbols(winners)`, then `nextGrid(grid, winners)`, then `reelSet.refill(...)`, then fires `cascade:chain:end`.
4. Loops back to step 1 with the post-refill grid.

It also takes an `AbortSignal`, so a button tap mid-round can end the chain cleanly. Step 6 wires that up, so the signature accepts one from the start.

```ts
async function playRound(signal: AbortSignal): Promise<void> {
  // Moment A: fall, wait, drop in.
  reelSet.setDropOrder('ltr');                  // left-to-right reveal
  const spinDone = reelSet.spin();
  reelSet.setResult((await server.spin()).map((visible) => ({ visible })));
  await spinDone;

  // Moment B: the cascade refill loop. runCascade owns the orchestration;
  // your two callbacks own the game rules.
  reelSet.setDropOrder('all');                  // all columns drop together on refills

  const { chainLength, totalWinners, wasSkipped } = await reelSet.runCascade({
    detectWinners: (grid) => detectWinners(grid),
    nextGrid:      (prev, winners) => server.cascade(prev, winners),
    onCascade:     ({ chain, winners }) => {
      console.log(`cascade ${chain}: ${winners.length} winners`);
    },
    signal,                                     // honors player slam between refills
  });

  console.log(
    `round done: ${chainLength} cascades, ${totalWinners} total winners` +
    (wasSkipped ? ' (slammed)' : ''),
  );
}
```

## Step 6. Wire the button

```ts
const button = document.createElement('button');
button.textContent = 'SPIN';
button.style.cssText = 'position:fixed;bottom:20px;left:50%;transform:translateX(-50%);padding:16px 32px;font-size:18px;';
document.body.appendChild(button);

let isPlaying = false;
let cascadeAbort: AbortController | null = null;

button.addEventListener('click', async () => {
  if (isPlaying) {
    reelSet.requestSkip();       // slam now, or queue it if the result hasn't landed
    cascadeAbort?.abort();       // end the cascade chain at the next await boundary
    return;
  }
  isPlaying = true;
  cascadeAbort = new AbortController();
  try {
    await playRound(cascadeAbort.signal);
  } finally {
    cascadeAbort = null;
    isPlaying = false;
  }
});
```

The slam handler does two things, and both are needed.

- `reelSet.requestSkip()` slams the engine's in-flight motion. If `setResult()` has not arrived yet, it queues the press until it does. That window is real here, because the mock server waits 400 to 1000 ms. Use `requestSkip()` rather than `skipSpin()`, which throws when called before the result lands, since there is nothing to land on yet. Both do nothing when the engine is idle.
- `AbortController.abort()` flips a flag that `runCascade` checks at its next await boundary. It works whether the engine is mid-refill or idle.

Together, the engine slams its in-flight motion and the cascade chain ends. See [the cancellation section in the cascades guide](/mechanics/cascade/#cancelling-a-chain-via-abortsignal) for the reasoning.

## Step 7. Try it

Click SPIN. The reels fall, the reels stay empty during the server round trip (400 to 1000 ms), then new symbols drop in. If `detectWinners` finds a 3-in-a-row, the winners disintegrate and the survivors slide down. That loops until there are no more wins.

Step 2 called `enableDebug(reelSet)`, so the browser console has
`window.__PIXI_REELS_DEBUG.log()`. It prints the visible grid and engine
state, which helps when something looks wrong.

## What you didn't have to do

Compared with hand-rolling cascades:

- No tween bookkeeping. `tumble({ fall, dropIn })` owns the animation timing.
- No survivor or gravity math. `refill({ winners, grid })` reads the gravity convention from your `grid` and animates the right offsets.
- No "fade then drop" choreography. `destroySymbols` defers to each symbol's `playDestroy()`, and the engine sequences `place` and `dropIn` for you.
- No slam state machine. `skipSpin()` is round-aware, and `wasSkipped` propagates through the chain.

## Next steps

Now that the slot works:

- Pick a feel. [Tumble feels](/mechanics/cascade/#tumble-feels) shows five preset `tumble({...})` shapes side by side.
- Tune the lead-in, the pause between the SPIN click and the first frame of the fall. See [fall delays](/mechanics/cascade/#fall-delays).
- Add a cascading multiplier by bumping a meter inside `onCascade`. See the [cascade-6x5 recipe](/mechanics/cascade/#cascade-6x5).
- Use Spine symbols with custom disintegration. Your `SpineReelSymbol` subclass overrides `playDestroy()` to play the `out` animation, and everything else stays the same. See [cascade wins: present, destroy, refill](/mechanics/cascade/#cascade-destroy-and-present) for the Spine wiring.
- Spin first, cascade after. Open with a strip-spin landing, then cascade. See [spin then cascade](/mechanics/cascade/#spin-then-cascade).

If you get stuck, read [the cascades guide](/mechanics/cascade/#concept). The mental model is what makes the verbs make sense.
