# Card duel

> Card-game style 3D cards: drawn, summoned face up, set face down and sideways, and flipped.

Example `card-duel`, running at https://nacatamalon.com/en/examples/card-duel. The whole catalogue: https://nacatamalon.com/llms/examples.md.

A duel in the style of the card game everybody knows: the opponent sets two cards, you draw five, summon one in attack, set a monster face down in defence, set a trap, change position, flip-summon and spring the trap. **Click** when it is over to gather the cards and deal again.

**A card is an object with two faces**: two textured planes looking in opposite directions. The renderer only draws the side of a triangle that faces the camera, so you see whichever is turned towards you and the other is skipped. No logic decides whether it is face up: turning it over is the decision.

Every card does the same thing, `move()`, from one pose to another, lifting a little on the way so it never passes through the cards below. A pose is where it lies, which way it points on the table, how far it leans towards you and which face is up. Attack is upright, defence is a quarter turn and set is face down: the positions of the game are numbers in that pose, driven by `useTween`.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { WIDTH, HEIGHT } from './settings';
import { Duel } from './scenes/demo';

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    smooth: true,
    msaa: 4,
    pixelRatio: 'device',
    fullscreenScaling: 'contain',
    background: '#0b0710',
});

// Declare Scenes
game({
    Duel,
});
```

`components/card.ts`:

```ts
import { createMesh, usePlaneGeometry, useTransform, type useTween, type TMesh, type TTexture, type TTransform3d, type TTweenHandle } from 'nacatamalon';
import { easeInOutCubic, lerp } from 'nacatamalon/math';

// A card is an object with two faces, and nothing else.
//
// Each face is a flat plane with a picture on it, and the two look in opposite directions: the
// front up, the back down. The renderer only draws the side of a triangle that faces the camera,
// so whichever face is turned towards you is the one you see, and the other is skipped. No logic
// decides "face up" or "face down": turning the card over IS the decision.
//
// The object (its transform) says where the card is and which way it points on the table. The two
// faces carry the flip, turning about the card's long side the way a hand turns one over.
export const CARD_WIDTH = 0.69;
export const CARD_LENGTH = 1;

/** Where a card is and how it lies. `flip` is 0 face down and 1 face up; `yaw` turns it on the table. */
export type TPose = { x: number; y: number; z: number; yaw: number; tilt: number; flip: number; };

export type TCard = {
    body: TTransform3d;
    front: TMesh;
    back: TMesh;
    pose: TPose;
    /** The move in progress, so a new one can stop it instead of fighting it for the same numbers. */
    moving: TTweenHandle | null;
};

/** Writes a pose into the object and its two faces. */
export const place = (card: TCard, pose: TPose) => {
    card.pose = pose;
    card.body.x = pose.x;
    card.body.y = pose.y;
    card.body.z = pose.z;
    card.body.rotationY = pose.yaw;
    card.body.rotationX = pose.tilt;

    // The back starts half a turn round from the front, so at flip 0 it is the back looking up.
    const turn = (1 - pose.flip) * Math.PI;

    card.front.transform.rotation = turn;
    card.back.transform.rotation = turn + Math.PI;
};

/** Built with useSpawn: one object per card, so each moves, turns and flips as one thing. */
export const Card = (front: TTexture, back: TTexture, cards: TCard[]) => {
    const body = useTransform();

    const geometry = usePlaneGeometry({
        width: CARD_WIDTH,
        depth: CARD_LENGTH,
    });

    const card: TCard = {
        body,
        front: createMesh({
            geometry,
            texture: front,
        }),
        back: createMesh({
            geometry,
            texture: back,
        }),
        pose: {
            x: 0,
            y: 0,
            z: 0,
            yaw: 0,
            tilt: 0,
            flip: 0,
        },
        moving: null,
    };

    cards.push(card);
};

/**
 * The one movement every card makes: from where it is to a new pose, lifting off the table on the
 * way so it never slides through the cards it passes over. A deal, a summon, a flip and a change of
 * position are all this, with different ends.
 */
export const move = (
    tween: ReturnType<typeof useTween>,
    card: TCard,
    to: Partial<TPose>,
    duration: number,
    lift = 0.6,
) => {
    card.moving?.stop();

    const from = card.pose;

    const end: TPose = {
        ...from,
        ...to,
    };

    const moving = tween({
        from: 0,
        to: 1,
        duration,
        ease: easeInOutCubic,
        onUpdate: (t) => place(card, {
            x: lerp(from.x, end.x, t),
            y: lerp(from.y, end.y, t) + Math.sin(t * Math.PI) * lift,
            z: lerp(from.z, end.z, t),
            yaw: lerp(from.yaw, end.yaw, t),
            tilt: lerp(from.tilt, end.tilt, t),
            flip: lerp(from.flip, end.flip, t),
        }),
    });

    moving.onEnd(() => {
        card.moving = null;
    });
    moving.play();
    card.moving = moving;
};
```

`components/duel.ts`:

```ts
import { createText, useLoadBitmapFont, useLoadTexture, usePointer, useSpawn, useTimer, useTween } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { Card, move, place, type TCard, type TPose } from './card';
import { Field, MONSTER_Z, SPELL_Z, ZONE_X } from './field';
import { inDeck, inHand } from '../geometry/poses';
import { FRONTS, BACK, QUARTER } from '../settings';

export const DuelTable = () => {
    useSpawn(Field)();

    const back = useLoadTexture({
        src: BACK,
        key: 'card-back',
    });

    const cards: TCard[] = [];
    const spawnCard = useSpawn(Card);

    for (const src of FRONTS) {
        spawnCard(useLoadTexture({
            src,
            key: src,
        }), back, cards);
    }

    const tween = useTween();
    const random = useRandom();

    const font = useLoadBitmapFont({
        json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
        atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png',
    });

    const label = createText({
        text: '',
        font,
        style: {
            fontSize: 16,
        },
        tint: '#ffb347',
        anchor: {
            x: 0.5,
            y: 0,
        },
        transform: {
            x: 320,
            y: 20,
        },
    });

    // What spaces the moves out so each can be watched: every step is scheduled from the start of
    // the duel, and the whole lot is called off when it starts again.
    const timer = useTimer();

    let deck: TCard[] = [];
    let hand: TCard[] = [];
    let done = false;

    const relayHand = () => hand.forEach((card, i) => move(tween, card, inHand(i, hand.length), 0.45, 0.1));

    const play = (card: TCard, to: Partial<TPose>, lift: number) => {
        hand = hand.filter((one) => one !== card);
        move(tween, card, {
            y: 0.012,
            tilt: 0,
            ...to,
        }, 0.8, lift);
        relayHand();
    };

    const duel = () => {
        done = false;
        // Shuffled on the table: every card straight to its new place in the pile, face down.
        deck = random.shuffle(cards);
        deck.forEach((card, n) => place(card, inDeck(n)));
        hand = [];

        const [opponentMonster, opponentTrap] = [deck.pop()!, deck.pop()!];

        // The opponent's cards point at them, so they are turned half round as well as set.
        timer.after(0.3, () => {
            label.text = 'OPPONENT SETS TWO CARDS';
        });
        timer.after(0.4, () => move(tween, opponentMonster, {
            x: ZONE_X[2],
            y: 0.012,
            z: -MONSTER_Z,
            yaw: Math.PI + QUARTER,
        }, 0.9, 1));
        timer.after(0.7, () => move(tween, opponentTrap, {
            x: ZONE_X[3],
            y: 0.012,
            z: -SPELL_Z,
            yaw: Math.PI,
        }, 0.9, 1));

        timer.after(2, () => {
            label.text = 'DRAW FIVE';
        });

        for (let i = 0; i < 5; i++) {
            timer.after(2.1 + i * 0.25, () => {
                const card = deck.pop()!;

                hand.push(card);
                move(tween, card, inHand(i, 5), 0.7, 0.8);
            });
        }

        const [summoned, setMonster, trap] = [0, 1, 2];
        let picks: TCard[] = [];

        timer.after(4.2, () => {
            picks = hand.slice(0, 3);
            label.text = 'NORMAL SUMMON IN ATTACK';
        });
        timer.after(4.3, () => play(picks[summoned], {
            x: ZONE_X[1],
            z: MONSTER_Z,
            yaw: 0,
            flip: 1,
        }, 0.9));

        timer.after(5.6, () => {
            label.text = 'SET A MONSTER IN DEFENCE';
        });
        timer.after(5.7, () => play(picks[setMonster], {
            x: ZONE_X[2],
            z: MONSTER_Z,
            yaw: QUARTER,
            flip: 0,
        }, 0.9));

        timer.after(7, () => {
            label.text = 'SET A TRAP';
        });
        timer.after(7.1, () => play(picks[trap], {
            x: ZONE_X[2],
            z: SPELL_Z,
            yaw: 0,
            flip: 0,
        }, 0.9));

        timer.after(8.6, () => {
            label.text = 'CHANGE TO DEFENCE';
        });
        timer.after(8.7, () => move(tween, picks[summoned], {
            yaw: QUARTER,
        }, 0.6, 0.15));

        timer.after(9.9, () => {
            label.text = 'FLIP SUMMON';
        });
        timer.after(10, () => move(tween, picks[setMonster], {
            yaw: 0,
            flip: 1,
        }, 0.8, 0.5));

        timer.after(11.4, () => {
            label.text = 'TRAP CARD';
        });
        timer.after(11.5, () => move(tween, picks[trap], {
            flip: 1,
            y: 0.25,
        }, 0.6, 0.4));
        timer.after(12.3, () => move(tween, picks[trap], {
            y: 0.012,
        }, 0.4, 0));

        timer.after(13.5, () => {
            label.text = 'CLICK TO DUEL AGAIN';
            done = true;
        });
    };

    // Gathered back to the deck face down, each from wherever it ended, then dealt again.
    usePointer().onDown(() => {
        if (!done) {
            return;
        }

        done = false;
        timer.cancelAll();
        label.text = 'SHUFFLE';
        cards.forEach((card, n) => timer.after(n * 0.04, () => move(tween, card, inDeck(n), 0.7, 0.9)));
        timer.after(cards.length * 0.04 + 0.9, duel);
    });

    duel();
};
```

`components/field.ts`:

```ts
import { createMesh, usePlaneGeometry } from 'nacatamalon';
import { CARD_LENGTH, CARD_WIDTH } from './card';

// The duel field, laid out the way the card game lays it out: on each side a row of five monster
// zones nearest the middle, a row of five spell and trap zones behind it, and the deck to the right.
// The opponent's half is the same, mirrored, so the table reads as a field before a card is played.
//
// Everything here is flat planes a hair above the mat. Nothing is drawn as an outline: a zone is a
// darker rectangle, which is all a zone printed on a play mat ever was.
export const ZONE_X = [-2.2, -1.1, 0, 1.1, 2.2];
export const MONSTER_Z = 0.85;
export const SPELL_Z = 2.15;
export const DECK = {
    x: 3.3,
    z: 2.15,
};
export const HAND_Z = 3.55;

export const Field = () => {
    const mat = usePlaneGeometry({
        width: 10,
        depth: 8.6,
    });

    createMesh({
        geometry: mat,
        tint: '#1b1530',
        transform: {
            z: 0.4,
        },
    });

    const zone = usePlaneGeometry({
        width: CARD_WIDTH + 0.16,
        depth: CARD_LENGTH + 0.16,
    });

    const sideways = usePlaneGeometry({
        width: CARD_LENGTH + 0.16,
        depth: CARD_WIDTH + 0.16,
    });

    for (const side of [1, -1]) {
        for (const x of ZONE_X) {
            // A monster zone is square-ish because a monster in defence lies across it.
            createMesh({
                geometry: zone,
                tint: '#3a2a5c',
                transform: {
                    x,
                    y: 0.004,
                    z: MONSTER_Z * side,
                },
            });
            createMesh({
                geometry: sideways,
                tint: '#2c2148',
                transform: {
                    x,
                    y: 0.003,
                    z: MONSTER_Z * side,
                },
            });
            createMesh({
                geometry: zone,
                tint: '#24304f',
                transform: {
                    x,
                    y: 0.004,
                    z: SPELL_Z * side,
                },
            });
        }

        createMesh({
            geometry: zone,
            tint: '#4a2d1c',
            transform: {
                x: DECK.x * side,
                y: 0.004,
                z: DECK.z * side,
            },
        });
    }
};
```

`geometry/poses.ts`:

```ts
import type { TPose } from '../components/card';
import { DECK, HAND_Z } from '../components/field';

export const inDeck = (n: number): TPose => ({
    x: DECK.x,
    y: 0.01 + n * 0.012,
    z: DECK.z,
    yaw: 0,
    tilt: 0,
    flip: 0,
});

/** The hand, fanned and leaning towards you so the pictures can be read. */
export const inHand = (i: number, count: number): Partial<TPose> => {
    const offset = i - (count - 1) / 2;

    return {
        x: offset * 0.82,
        y: 0.7,
        z: HAND_Z,
        yaw: -offset * 0.06,
        tilt: 0.75,
        flip: 1,
    };
};
```

`scenes/demo.ts`:

```ts
import { createScene, useCamera3d, useDirectionalLight, useSpawn } from 'nacatamalon';

import { DuelTable } from '../components/duel';

export const Duel = () => {
    useCamera3d({
        projection: 'perspective',
        fov: 42,
        transform: {
            y: 6.1,
            z: 7.5,
            rotationX: -0.74
        },
    });
    useDirectionalLight({
        color: '#fff6ea',
        intensity: 0.9,
        ambient: 0.45,
        transform: {
            rotationX: -1.1
        },
    });

    useSpawn(DuelTable)();

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 640;
export const HEIGHT = 480;
// A duel in the style of the card game everybody knows: draw five, summon one face up, set a
// monster face down and sideways, set a trap, then change position, flip-summon and spring the
// trap. Click when it is over to gather the cards and deal again.
//
// Every card does the same single thing, move(), from one pose to another: a pose is where it
// lies, which way it points on the table (yaw), how far it leans towards you (tilt) and which face
// is up (flip). Attack is upright, defence is a quarter turn, set is face down. The positions of
// the game are just numbers in that pose.
export const TCG = '/example-assets/assets/tcg/';
export const FRONTS = [1, 2, 3].flatMap((colour) => [1, 2, 3].flatMap((version) => [1, 2].map((pic) =>
    `${TCG}Cards_color${colour}/Halflings_color${colour}_version${version}/Halflings_color${colour}_version${version}_pic${pic}.png`)));
export const BACK = `${TCG}Cards_color1/Halflings_color1_back/Halflings_color1_back.png`;
export const QUARTER = Math.PI / 2;
```
