Skip to content

Last time, I promised we’d finally create the JavaScript Mahjong game. The backend did its part. We can request a board from the server and get a JSON response with 144 tiles arranged in a certain layout. But the backend only returns a JSON object with the full board configuration. It’s our frontend’s job to turn this configuration into a playable game.

If you’re just joining the series, there are a few tutorials that you should probably read before this one since they go over certain topics that we will use here:

  1. We made the tile and drew its face and edges in Scalable Mahjong Tiles with CSS and SVG.
  2. We worked out how to stack those tiles and made the owl shape in Creating a Mahjong Board Layout with JSON.
  3. We turned that shape into a solvable board configuration in The PHP Backend.

So now, in this final tutorial of the series, we will create the rest of the game. We’ll cover the HTML, CSS, and JavaScript needed for it. We will combine everything we learned in the previous tutorials in this series to create a playable Mahjong game.

If you want to check out the game itself, just visit the game demo. To see the full source code, you can download the ZIP.

As mentioned in the PHP backend tutorial, to run the demo files you will need a PHP server. This is still true, since the PHP backend is part of the game and is included in our downloadable ZIP file. If you need a reminder of the server options, check out the sections on running the downloaded code.

You don’t need to have a vast knowledge of web development in order to follow this tutorial, but it will be best if you:

  • Know some HTML
  • Know a bit of CSS
  • Know basic JavaScript

A quick requirements reminder

Let’s quickly go over the game’s requirements, focusing mainly on the game client.

The needs:

  • Show a board of tiles.
  • Let the player interact with the tiles.
  • Playing a turn
    • Matched tiles leave the board.
    • Failed matches reset selection
  • Win condition: Empty board
  • Responsive and accessible interface

The wants:

  • Giving the player a better chance:
    • Hints
    • Shuffling the board
  • Picking a layout
  • Making sure the board is solvable (Already done in the backend)
  • Tracking the available moves

The nice-to-have:

  • A bit of sound
  • A bit of animation
  • Dark/Light mode support

If we can cover all of these requirements in our little game, I think it has a chance to be quite enjoyable.

Ready to get started? Let’s dive in.

Showing a board of tiles

Previously, when we built the backend, we provided a way to get a configured board in a JSON response. Now it’s time we use that response and turn it into a playable board. You know, one that the player can actually see.

Requesting a new board

Before we can handle the response, we need to request a new board.

async function loadBoard(playSound = true) {
    const previousFocus = document.activeElement;
    resetForNewGame(playSound);
    setBoardPendingState(true);

    if (pendingRequest) {
        pendingRequest.abort();
    }

    const query = prepareQueryString();
    const request = new AbortController();
    pendingRequest = request;
    try {
        const response = await fetch(`backend.php?${query}`, {
            signal: request.signal,
            cache: 'no-store',
        });
        const data = await response.json();
        if (!response.ok) {
            throw new Error(
                data.error ?? 'The board could not be loaded.'
            );
        }
        if (pendingRequest !== request) {
            return;
        }
        await prepareDeckStyles(data.deck, request);
        if (pendingRequest === request) {
            await renderBoard(data);
        }
    } catch (error) {
        if (pendingRequest !== request || error.name === 'AbortError') {
            return;
        }
        cancelTileAnimations();
        status.textContent =
            error.message || 'The board could not be loaded.';
    } finally {
        if (pendingRequest === request) {
            pendingRequest = null;
            setBoardPendingState(false);
            restoreBoardFocus(previousFocus);
        }
    }
}

When preparing to send a request to the backend, we first need to handle the current state. It’s not really needed when we just enter the game. However, after the game interface loads, the player might decide they want a new board. Maybe they want to switch layout, or don’t like the deck. Since we don’t want to write the same code twice with slight differences, we just add some handling:

  • resetForNewGame() – Stop actions that won’t make sense when starting a new game, like any animation or sound that originated from another action. It also resets several game variables, such as moves made, stats display, and more.
  • setBoardPendingState() – Disables controls that shouldn’t be used mid-action, such as requesting a new board while already requesting one. It also tells screen readers that the board is currently busy.

The loadBoard() function also sets some guards. It uses the AbortController to cancel requests and to save the current one so we can verify we got the correct response, and not a response to an older request (which we aborted).

Yes, I know we already disabled the button, so how can a request for a new board be made while the button is disabled? We keep the abort controller as a defensive safeguard in case another part of the code starts a new request. The AbortController.signal also lets us add a timeout later, so a slow request can end with a useful message and a chance to retry.

We call prepareQueryString() since requesting a board can have a couple of parameters:

  • The layout chosen, or ask for a random layout if not chosen.
  • The deck chosen. Well, this is more for us, since the player doesn’t have a way to choose a deck yet.

Once we get a response from the backend, we also check it to see if there was an error or if everything is alright. The finally block tells JavaScript that even if what we tried to do failed, it should still run what is in this block. Imagine running into an error, and the board never gets released from a pending state. It can (and often does) frustrate everyone.

Assuming everything worked as it should, we got a JSON with the new board configuration. We first prepare the deck for it, and display (render) the board. You probably saw that we use await to call for the style change. We will see why in a bit. Since we know there might be a small delay, we make sure again that we are running our request.

Doing things in style

So how do we prepare the deck style? And why can it take some time?

function prepareDeckStyles(deck, request) {
    const oldStyle = document.getElementById('deck-style');
    const stylesheet = new URL(deck.stylesheet, window.location.href)
        .href;
    const baseStylesheet = document.getElementById('base-tokens').href;
    const activeStylesheet = oldStyle?.href ?? baseStylesheet;
    if (stylesheet === activeStylesheet) {
        return Promise.resolve();
    }
    if (stylesheet === baseStylesheet) {
        oldStyle?.remove();
        window.svgRecoloring.reset();
        return Promise.resolve();
    }

    return new Promise((resolve, reject) => {
        const style = document.createElement('link');
        style.rel = 'stylesheet';
        style.href = stylesheet;
        style.media = 'not all';
        const loading = {
            style,
            oldStyle,
            request,
            deckLabel: deck.label,
            resolve,
            reject,
        };
        loading.cancel = () => cancelDeckStyleLoad(loading);
        request.signal.addEventListener('abort', loading.cancel, {
            once: true,
        });
        style.addEventListener(
            'load',
            () => handleDeckStyleLoad(loading),
            {once: true}
        );
        style.addEventListener(
            'error',
            () => handleDeckStyleError(loading),
            {once: true}
        );
        document.head.append(style);
    });
}

As you can see, the prepareDeckStyles() function loads a CSS file based on the board deck. The CSS is needed since it includes the drawings for the different tiles. We ask the browser to load the needed CSS file. The browser will do that for us, but in its own time, and asynchronously, so it won’t block the browser. So, we patiently await its return. We load a new link with media = 'not all' so the new rules can download without taking over in the middle.

function handleDeckStyleLoad(loading) {
    const {style, request, cancel, resolve} = loading;
    if (pendingRequest !== request) {
        style.remove();
        request.signal.removeEventListener('abort', cancel);
        resolve();
        return;
    }
    style.media = 'all';

    window.requestAnimationFrame(() => {
        window.requestAnimationFrame(() => activateDeckStyle(loading));
    });
}

Once the current request’s sheet has loaded, we activate it and give the browser a chance to apply the rules. Then we remove the old link and reset the SVG recoloring helper. Otherwise, an inline image left by the last deck could still win over the new CSS.

You probably noticed the nested requestAnimationFrame() calls. We wait across two animation frames to give the browser a chance to render before reading the new CSS values. This helps us avoid a stale values issue we encountered in WebKit while programming this game demo. It’s a bit of an ugly workaround, so if you ever want to use this code in a production environment you should probably look into changing it.

So we’ve loaded the board configuration and applied the style, but we still don’t have a board with tiles. Let’s get to that part of the code.

Rendering the board

If you remember, in loadBoard(), after preparing the deck, we call renderBoard():

async function renderBoard(data) {
    const generation = arrangementGeneration;
    const turnSoundGeneration = soundGeneration;

    rootStyle = window.getComputedStyle(document.documentElement);
    const geometry = readTileGeometry(rootStyle);
    applyTileGeometry(geometry);
    initializeBoardState(data);
    const tilePositions = calculateTilePositions();
    const dimensions = calculateBoardDimensions(tilePositions);

    beginArrangement();
    board.dataset.arrangement = 'deal';
    paintTiles(tilePositions);
    initializeBoardLayout(data.layoutLabel, dimensions);
    status.textContent = 'Dealing tiles…';
    fitBoardToViewport();
    if (await animateTiles('deal', generation)) {
        finishArrangement(turnSoundGeneration);
    }
}

renderBoard() coordinates the setup, painting, fitting, and dealing of the board tiles. This results in what we have been waiting for: a board with tiles.

Since a deck has a CSS file loaded into the game, it can do more than just replace the drawings. It gives the game graphics a lot of flexibility. For example, the deck CSS file can also affect tile size.

In our case, size does matter. Tile and board size are important because they let us control the layout of the page and the board. There are a few places that handle the sizes:

One board, one scaleAt 75 percent scale, the board, tile sizes, and tile positions all shrink together. The layout itself stays the same.One board, one scaleThe layout stays the same as it shrinks.Natural board20 rem wideScale: 1Fits at 75%15 rem wideScale: 0.75Tile sizes and positions use the same scale.Scale limits: 0.5 to 1. Scroll if needed.

function remToken(style, propertyName) {
    const value = style.getPropertyValue(propertyName).trim();

    if (!value.endsWith('rem')) {
        throw new Error(`${propertyName} must use rem units.`);
    }

    return Number.parseFloat(value);
}

function readTileGeometry(style) {
    return {
        widthRem: remToken(style, '--tile-width'),
        heightRem: remToken(style, '--tile-height'),
        depthXRem: remToken(style, '--tile-depth-x'),
        depthYRem: remToken(style, '--tile-depth-y'),
        columnStepRem: remToken(style, '--tile-column-step'),
        rowStepRem: remToken(style, '--tile-row-step'),
    };
}

function readTileGeometry(style) {
    return {
        widthRem: remToken(style, '--tile-width'),
        heightRem: remToken(style, '--tile-height'),
        depthXRem: remToken(style, '--tile-depth-x'),
        depthYRem: remToken(style, '--tile-depth-y'),
        columnStepRem: remToken(style, '--tile-column-step'),
        rowStepRem: remToken(style, '--tile-row-step'),
    };
}

function calculateBoardDimensions(tilePositions) {
    let furthestRight = 0;
    let furthestBottom = 0;
    let nearestTop = Infinity;

    tilePositions.forEach(({left, top}) => {
        furthestRight = Math.max(furthestRight, left + tileWidthRem);
        furthestBottom = Math.max(furthestBottom, top + tileHeightRem);
        nearestTop = Math.min(nearestTop, top);
    });

    const boardWidthRem = Math.max(
        furthestRight,
        36 * columnStepRem + layerCount * layerOffsetXRem
    );

    const verticalWhitespace =
        nearestTop === Infinity ? 0 : nearestTop / 2;
    const boardHeightRem = Math.max(
        furthestBottom,
        16 * rowStepRem + layerCount * layerOffsetYRem
    );
    return {
        width: boardWidthRem,
        height: boardHeightRem,
        top: -verticalWhitespace,
    };
}

function initializeBoardLayout(layoutLabel, dimensions) {
    board.dataset.layoutLabel = layoutLabel;
    board.setAttribute(
        'aria-label',
        `${layoutLabel} Mahjong board, ${remainingIds.size} tiles`
    );
    boardDimensions = dimensions;
}

function fitBoardToViewport() {
    if (boardDimensions === null) {
        return;
    }
    const viewport = boardViewport;
    const viewportStyle = window.getComputedStyle(viewport);
    const remPixels = Number.parseFloat(
        window.getComputedStyle(document.documentElement).fontSize
    );
    const horizontalPadding =
        Number.parseFloat(viewportStyle.paddingLeft) +
        Number.parseFloat(viewportStyle.paddingRight);
    const verticalPadding =
        Number.parseFloat(viewportStyle.paddingTop) +
        Number.parseFloat(viewportStyle.paddingBottom);
    const availableWidth = viewport.clientWidth - horizontalPadding;

    const boardTop =
        viewport.getBoundingClientRect().top + window.scrollY;
    const availableHeight = Math.max(
        0,
        window.innerHeight - boardTop - remPixels - verticalPadding
    );
    const scale = Math.max(
        MINIMUM_BOARD_SCALE,
        Math.min(
            1,
            availableWidth / (boardDimensions.width * remPixels),
            availableHeight / (boardDimensions.height * remPixels)
        )
    );
    applyBoardScale(scale);
    centerBoard();
}

function applyBoardScale(scale) {
    const width = `${boardDimensions.width * scale}rem`;
    const height = `${boardDimensions.height * scale}rem`;
    board.style.setProperty('--board-scale', scale);
    Object.assign(board.style, {
        top: `${boardDimensions.top * scale}rem`,
        width,
        height,
    });
    Object.assign(boardStage.style, {width, height});
}

function centerBoard() {
    const viewport = boardViewport;

    window.requestAnimationFrame(() => {
        viewport.scrollLeft =
            (viewport.scrollWidth - viewport.clientWidth) / 2;
    });
}
  • remToken() – Make sure the size values are in rem.
  • readTileGeometry() – Returns the deck’s natural tile sizes, depths, and spacing.
  • applyTileGeometry() – Stores those measurements and sets up scalable tile CSS values.
  • createTileButton() – Calculates each tile’s position from its row, column, and layer (We will go over that one in a bit).
  • calculateBoardDimensions() – Calculates the natural board bounds using those positions and tile sizes.
  • initializeBoardLayout() – Stores the natural board dimensions.
  • fitBoardToViewport() – Measures the available space and chooses a scale.
  • applyBoardScale() – Applies the scale and board dimensions.
  • centerBoard() – Adjusts horizontal scrolling to center the board.

renderBoard() coordinates that flow. We also have a resize listener that calls fitBoardToViewport() again when the available space changes.

If you think we could have used CSS more and removed some of the work from the JavaScript code, you are right. CSS Grid could handle the tile placement too. However, since our JavaScript already has the board’s coordinates,  I decided to stick mostly to JavaScript for now.

If you want, a nice exercise would be to use more of the CSS special sizing and positioning powers. Each layer in the layout could be an absolutely positioned CSS grid. Using half-tile-sized cells, each tile would span two columns and two rows. That would support the offset placements we use in the JSON layouts. We could then offset each layer slightly to show the tile depth and use z-index to stack them. There would still need to be some translation of the JSON-supplied data and the CSS. It will need to follow the display requirements we covered in this and the previous tutorials I mentioned at the start.

Let’s get back to our current code. We do a lot of calculations to set the board display. The board is ready.

Coming up next: diving deeper into the tiles and actually coding the gameplay.

One tile has a spot, a picture, and a rule

Here’s one tile from a WDP deck JSON file. The actual values will differ in each response, but the structure is the same.

{
    "id": "0-12-8",
    "layer": 0,
    "row": 12,
    "column": 8,
    "face": "dots-1",
    "match": "face:dots-1",
    "label": "1 triangle"
}

The ID names the spot. The face tells us which picture to draw. The label is ready to read aloud, right down to “1 triangle” and “2 triangles.” We can use the text as it comes. If you remember, in the backend tutorial we saw that the deck JSON configuration file includes the tile labels. Otherwise, trying to make a name out of dots-1 would give the player a rather odd description of a triangle (in the case of the WDP deck).

And the matching rule? Two copies of that triangle share face:dots-1. But if we look at one of the special groups like flower tiles, rose and orchid have different pictures but the same matching key: group:flowers. Remember those flowers. They’ll save us from writing a very plausible bug when we handle the second click.

In renderBoard(), we call initializeBoardState(). In that function, we give each piece of state a small job:

function initializeBoardState(data) {
    board.dataset.deck = data.deck.name;
    tiles = new Map(data.tiles.map((tile) => [tile.id, tile]));
    remainingIds = new Set(tiles.keys());
    selectedId = null;
    matchCount = 0;
    history = [];
    shufflesLeft = GAME_SETTINGS.shufflesPerBoard;
    layerCount = data.layers;
    if (data.layouts) {
        updateLayoutChoices(data.layouts);
        layoutChoicesLoaded = true;
    }
}

The tiles Map lets us look up a tile by its ID. The remainingIds Set holds each ID that is still in play, once. At the start, they’re all there. When a pair comes off, we can drop two IDs from the set and still look up both tiles. That will be handy when the player reaches for Undo, but more about that in a bit.

Give the tile a button

A tile is an interactive component. The player clicks on it, and something happens on the page. The most suitable HTML element for this is a <button>.

Let’s see how we are creating a tile as a button.

function createTileButton({tile, left, top}) {
    if (
        typeof tile.face !== 'string' ||
        !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(tile.face)
    ) {
        throw new Error('The deck contains an invalid tile ID.');
    }
    const tileImageProperty = `--svg-image-${tile.face}`;
    if (!rootStyle.getPropertyValue(tileImageProperty).trim()) {
        throw new Error(
            `The deck is missing the ${tileImageProperty} CSS token.`
        );
    }


    const zIndex = tileZIndex(tile);
    const button = document.createElement('button');
    button.type = 'button';
    button.className = 'tile';
    button.dataset.tileId = tile.id;
    button.dataset.tileFace = tile.face;
    button.dataset.tileLayer = tile.layer;
    button.setAttribute('aria-label', `${tile.label}, blocked`);
    button.setAttribute('aria-disabled', 'true');
    button.setAttribute('aria-pressed', 'false');
    button.disabled = true;
    button.style.setProperty('--tile-left', `${left}rem`);
    button.style.setProperty('--tile-top', `${top}rem`);
    button.style.setProperty('--tile-z', zIndex);
    button.style.setProperty(
        '--tile-image',
        `var(${tileImageProperty})`
    );

    const cover = document.createElement('span');
    cover.className = 'tile-cover';
    cover.setAttribute('aria-hidden', 'true');
    button.append(cover);

    return button;
}

The parameter for the createTileButton({}) function is a bit interesting. The function expects an object that has 3 properties: tile, left, and top. The object can have more properties, but those are the only ones this function cares about. The same function could have been written as createTileButton(tile, left, top).

Since we always like to check our input, we start by validating the tile face property with a regex. If you want to learn more about using regular expressions, check out this Regular Expressions guide from MDN. If no such CSS token exists, the drawing on the tile won’t be displayed. Therefore, we need to check that it exists in the CSS.

When we create the button, we use its dataset property to set and later read its data-* attributes. The dataset basically gives us a standard way to access non-standard attributes. These let us attach data to the element, such as the tile’s layer. We shouldn’t rely on them to provide information to assistive technology or search engines, so the button also gets an accessible label (aria-label). Like other data in the browser, these values can be inspected and changed through developer tools. dataset.tileLayer will appear in the HTML as data-tile-layer.

The call to tileZIndex() is simple, but also very important.

function tileZIndex(tile) {
    const depth = tile.row + tile.column;
    return tile.layer * 100000 + depth * 100 + tile.row;
}

Yes, I know, we went a bit overboard with the z-index value. Let’s say that it reflects the importance of the setting. The tiles have visual depth, so their edges overlap when we place them directly next to each other. We use z-index to control which tile gets painted on top of which. The layer wins first. Within a layer, tiles farther down and right paint later, and the row breaks a tie along a diagonal. If we leave that order to the browser’s defaults, some edges can cover the wrong tiles. The board will look pretty weird. By the way, the large gaps between the numbers also serve a purpose. They keep the layer, depth, and row contributions from interfering with each other within the layouts we support.

The tile button starts disabled until we know the tiles are organized on the board and it’s ready. Don’t worry, we will do a quick check later and enable the free buttons.

But what actually adds the button to the board?

If you are with me so far, you might have noticed that I skipped the paintTiles() function that renderBoard() is calling.

function paintTiles(tilePositions) {
    const fragment = document.createDocumentFragment();
    tilePositions.forEach((position) => {
        fragment.append(createTileButton(position));
    });
    board.replaceChildren(fragment);
}

We’re adding 144 tile buttons to the board. We still need to create each one, but we can gather them in a document fragment before putting them on the page. Think of it as preparing the full shopping list before handing it over. Once the tiles are ready, we pass the fragment to replaceChildren(). That replaces the board’s existing contents with our new buttons in one call. The fragment itself stays behind, empty. It gives us a clear way to build the new board and then put it in place.

Deal them face down

Did you see that when we created the <button> for the tile, we also created a little <span> element inside of it?

Each button has one extra span, a plain cover over the artwork. It’s hidden from screen readers. Before we arrange the board, we collect the distinct image URLs and ask the browser to decode them. Four tiles with one picture can share the same cached image. The face is already underneath when we lift the cover.

Dealing in style

To add a little flair, we animate the tiles when we arrange the board. We want the faces to appear together, even though the tiles leave the corner one after the other.

If we can “deal” tiles, we would probably want to “collect” as well. So, for these two actions, we have two animation phases. During deal, the tiles travel from the corner to their places. During collect, they travel back to the corner.

Let’s start with the function that coordinates it all.

async function animateTiles(phase, generation) {
    board.dataset.arrangement = phase;

    if (phase === 'deal') {
        await prepareTileImages();
    }

    if (generation !== arrangementGeneration) {
        return false;
    }

    if (reducedMotion.matches) {
        return generation === arrangementGeneration;
    }

    await new Promise(window.requestAnimationFrame);
    if (generation !== arrangementGeneration) {
        return false;
    }

    if (reducedMotion.matches) {
        return true;
    }

    const corner = readBoardAnimationCorner();
    const buttons = getTileAnimationButtons(phase);

    const positions = buttons.map((button) =>
        button.getBoundingClientRect()
    );

    const timing = {
        stagger: Math.min(
            18,
            (phase === 'collect' ? 300 : 650) /
                Math.max(1, buttons.length - 1)
            ),
        startTime: document.timeline.currentTime,
    };

    const animations = startTileTravel(
        buttons,
        positions,
        corner,
        phase,
        timing
    );

    if (phase !== 'collect') {
        animations.push(...startTileReveals(buttons, timing));
    }

    await Promise.all(
        animations.map((animation) =>
            animation.finished.catch(() => {})
        )
    );

    return generation === arrangementGeneration;
}

We set the board’s data-arrangement attribute so that the CSS can prepare the tiles for the phase. For example, the dealing rules hide the tiles before their individual animations take over. The board is already locked by beginArrangement(), which we call in renderBoard(). We don’t want to let the player pick a tile while it is still flying into place. That would make for an interesting game, but probably a different one.

Before dealing, prepareTileImages() gathers the face images and waits for them to be decoded. Decoding turns the image data into something the browser can display. We keep an Image object for each distinct URL in tileImageCache, so copies of the same face share that preparation. If an image fails to decode, we catch the error and still let the board become usable. You can read more about this step in MDN’s guide to the image decode() method.

The rest of animateTiles() follows this order:

  1. Checks whether this is still the current arrangement and whether the player wants reduced motion.
  2. Waits for a rendering frame, then checks those conditions again.
  3. Finds the corner, puts the tiles in order, and measures where they belong.
  4. Starts the travel animations and, when dealing, the face reveals.
  5. Waits for those animations to settle and reports whether the arrangement is still current.

There are quite a few details in that list. Let’s go over them while our tiles patiently wait in the corner.

Is this still our board?

We pass generation into animateTiles(). It is the value of arrangementGeneration saved by the caller before the animation work starts. When we cancel an arrangement, we increase arrangementGeneration. Any older call can compare its saved number with the current one and return false if its work is out of date.

This matters around an await. While we wait for images or a frame, other work can run. So we check again after waiting. An old animation should finish its work quietly if another board has taken its place. Its caller only runs finishArrangement() when the returned value is true.

For accessibility, we also check reducedMotion.matches. That comes from window.matchMedia('(prefers-reduced-motion: reduce)'). If the player has asked for less motion, we can return true for the current arrangement and let the caller make the board ready to play straight away. We still prepared the images and put the tile buttons in place.

The call to requestAnimationFrame() gives the queued board-centering callback a chance to run before we take our measurements. Its callback is scheduled before a repaint. The separate image-preparation promise handles image readiness.

Where do the tiles travel from?

function readBoardAnimationCorner() {
    const viewport = boardViewport.getBoundingClientRect();
    const viewportStyle = window.getComputedStyle(boardViewport);

    return {
        left:
            viewport.left + boardViewport.clientLeft +
            Number.parseFloat(viewportStyle.paddingLeft),
        top:
            viewport.top + boardViewport.clientTop +
            Number.parseFloat(viewportStyle.paddingTop),
    };
}

getBoundingClientRect() gives us the board viewport’s position and size in CSS pixels, relative to the browser viewport. We add the left or top border and padding to reach its inner corner. If the board is scrolled sideways, we still use the corner the player can see. Each tile’s resting rectangle is measured in the same coordinate system, so we can subtract one position from the other.

We also need to decide which tile leaves first.

function getTileAnimationButtons(phase) {
    const buttons = Array.from(board.querySelectorAll('.tile')).sort(
        (first, second) =>
            Number(first.style.getPropertyValue('--tile-z')) -
            Number(second.style.getPropertyValue('--tile-z'))
    );
    if (phase === 'collect') {
        buttons.reverse();
    }
    return buttons;
}

We sort the buttons by the --tile-z value we already assigned when creating them. Tiles with lower paint priorities leave first when dealing. For collection, we reverse that order. Taking the top tiles away first looks a little more natural than pulling a tile out through the ones resting on it.

Back in animateTiles(), we read every button’s resting rectangle before starting any movement. That gives us a consistent set of positions. It also keeps those layout reads together, before the animations start changing the tiles’ appearance.

Give them the same clock

The timing object has two values. stagger is the delay between one tile leaving and the next. We cap it at 18 milliseconds and also limit the total spread of departures. With 144 tiles, the dealing spread is 650 milliseconds. Each tile takes 420 milliseconds to travel, so the last one lands about 1,070 milliseconds after the shared start. For collection, the travel duration and the maximum departure spread are both 300 milliseconds.

The Math.max(1, buttons.length - 1) part avoids dividing by zero when there is only one tile. There is one fewer gap between departures than there are tiles. Three tiles have two gaps, just like three people standing in a line. At least we don’t need to ask the tiles to leave some personal space.

document.timeline.currentTime gives us a time on the document’s animation timeline. We save it once and use it as the startTime of every travel and reveal animation. The individual delays still apply. They all count from the same point, so the last arrival and the reveal can line up.

Making a tile move

Now we get to the actual Web Animations API. We describe the states we want and give the browser the timing. The browser works out the values in between. Calling an element’s animate() method creates an Animation object and starts playback. We keep that object so we can wait for it, finish it, or cancel it later.

function startTileTravel(buttons, positions, corner, phase, timing) {
    const collecting = phase === 'collect';
    return buttons.map((button, index) => {
        const position = positions[index];
        const offsetX = corner.left - position.left;
        const offsetY = corner.top - position.top;
        const cornerTransform =
            `translate(${offsetX}px, ${offsetY}px) scale(0.85) rotate(-8deg)`;
        const frames = collecting
            ? [
                {transform: 'none', opacity: 1},
                {opacity: 1, offset: 0.75},
                {transform: cornerTransform, opacity: 0},
            ]
            : [
                {transform: cornerTransform, opacity: 0},
                {opacity: 1, offset: 0.12},
                {transform: 'none', opacity: 1},
            ];
        const animation = button.animate(frames, {
            duration: collecting ? COLLECT_DURATION : DEAL_DURATION,
            delay: index * timing.stagger,
            easing: collecting
                ? 'cubic-bezier(0.4, 0, 0.8, 0.4)'
                : 'linear',
            fill: 'both',
        });
        animation.startTime = timing.startTime;
        tileAnimations.add(animation);
        return animation;
    });
}

The tile’s normal CSS already puts it in its place on the board. offsetX and offsetY measure the distance from that place to the corner. If the corner is 300 pixels to the left, offsetX is negative. The translate() moves the painted tile that far, while scale(0.85) makes it a bit smaller and rotate(-8deg) gives it a slight tilt. Returning the transform to none leaves the tile at its normal CSS position and size.

The objects in frames are keyframes. Each describes some of the CSS values at a point in the animation. For the deal, the three frames give us the following states.

  • At the start, the tile is at the corner and fully transparent.
  • At offset 0.12, its opacity has reached 1, so it is fully visible.
  • At the end, the transform is none, and the tile is still visible.

An offset is a fraction from 0 to 1. Which means 0.12 is 12% of the animation’s progress. Since our deal uses linear easing, that is also 12% of its travel duration. The middle frame only sets opacity. The transform continues between the corner and the final position, using the values supplied in the first and last frames. MDN shows both supported keyframe formats and how offsets work.

For collection, the tile starts in place, stays opaque through most of the effect, and ends at the corner with zero opacity. We use offset: 0.75 for that opacity checkpoint. Collection has its own easing curve, so the checkpoint’s progress doesn’t correspond to exactly 75% of elapsed time.

The second argument to button.animate() supplies the playback settings.

  • duration is how long one tile’s movement lasts, in milliseconds.
  • delay is how long this tile waits after the shared start. The first tile has an index of zero and leaves straight away.
  • easing controls how progress changes over time. linear gives the deal a steady pace. The cubic-bezier curve gives the collection phase its own pace.
  • fill: 'both' applies the starting values during the delay and keeps the final values after playback ends.

That last setting matters. A delayed tile needs to wait at the corner. A tile that has landed needs to stay visible while the rest arrive. The animation keeps supplying those values until we release it.

After starting each animation, we give it the shared startTime and add it to tileAnimations. That’s how we reach all active tile effects later. The returned array is used by this call to animateTiles() to wait for its own effects.

Lift the covers together

We now have tiles arriving one after another. But we said their faces should appear together. For that, we animate the little .tile-cover spans we added earlier.

function startTileReveals(buttons, timing) {
    const landingTime =
        DEAL_DURATION + (buttons.length - 1) * timing.stagger;
    return buttons.map((button) => {
        const reveal = button.querySelector('.tile-cover').animate(
            {opacity: [1, 0]},
            {
                duration: landingTime,
                easing: 'steps(1, end)',
                fill: 'both',
            }
        );
        reveal.startTime = timing.startTime;
        tileAnimations.add(reveal);
        return reveal;
    });
}

landingTime includes both the last tile’s delay and its movement duration. All covers use the same duration and start time. There is no per-tile delay on these reveal animations.

The {opacity: [1, 0]} syntax is another way to supply keyframes. It sets the property’s starting and ending values. With a smooth easing, the covers would gradually fade. We use steps(1, end) to hold the first value and make one jump at the end. The covers stay opaque until the shared landing point, then become transparent. With CSS steps() easing, the browser can update the travel and reveal effects from the same timeline. We don’t need to wait for a JavaScript callback to tell each cover that its turn has come.

The drawings are already painted underneath the covers. We prepared them earlier, so lifting the covers reveals what is there. That’s a little less dramatic than 144 pictures deciding to load just as they land, which is exactly what we want.

One clock, one revealIn this four-tile example, A starts at 0 ms, B at 18 ms, C at 36 ms, and D at 54 ms. Each moves for 420 ms. Their covered waits after landing are 54, 36, 18, and 0 ms. At 474 ms, D lands and every face is revealed together. The landed sections are widened to fit their labels; their widths do not represent elapsed time.One clock, one revealThe last tile sets the shared reveal time.Wait to startMovingLanded0 ms474 msFaces stay coveredA: 0 msLandedWait: 54 msB: 18 msLandedWait: 36 msC: 36 msLandedWait: 18 msD: 54 msLandedWait: 0 msReveal allat 474 msLast tile D: 54 ms + 420 ms = 474 ms.Landed bars are widened for labels.D lands and reveals at the same moment.

Knowing when the deal is done

At the end of animateTiles(), we collect each animation’s finished promise and pass them to Promise.all(). The await resumes once every animation has finished, or its cancellation has been handled by the catch() below. Here, the group includes both the tile travel and the cover reveals.

You probably noticed the empty catch() on each promise. Canceling a running animation rejects its finished promise. We expect that to happen when a new arrangement replaces the old one. Catching the rejection lets our function reach the final generation check and return false for the outdated arrangement.

If the generation still matches, the caller can finish the current arrangement.

function finishArrangement(turnSoundGeneration) {
    delete board.dataset.arrangement;
    releaseTileAnimations();
    board.classList.remove('is-arranging');
    board.inert = false;
    boardIsLocked = false;
    board.setAttribute('aria-busy', 'false');
    newGame.disabled = false;
    layoutChoice.disabled = false;
    layoutToggle.disabled = false;
    updateFreeTiles(true, turnSoundGeneration);
}

First, we remove data-arrangement. That removes the CSS rule that kept the dealing tiles hidden. Then we release the animation effects. While the board still has is-arranging, CSS transitions stay disabled, so this handoff doesn’t accidentally start another fade.

After that, we remove the arranging class, restore interaction, and mark the board as ready. updateFreeTiles() checks the actual board and enables the tiles the player can pick. The turnSoundGeneration value also makes sure a canceled sound request doesn’t come back to celebrate an old result.

Two small helpers handle releasing and canceling the effects.

function releaseTileAnimations() {
    tileAnimations.forEach((animation) => animation.cancel());
    tileAnimations.clear();
}
function cancelTileAnimations() {
    arrangementGeneration += 1;
    releaseTileAnimations();
    board.classList.remove('is-arranging');
    delete board.dataset.arrangement;
    board.inert = false;
}

releaseTileAnimations() calls cancel() on the animation objects and clears the set. That removes their effects, including the final values held by fill: 'both'. The regular CSS takes over. On a completed deal, we already prepared that CSS in finishArrangement().

cancelTileAnimations() also increases the arrangement generation. That tells any older asynchronous work to stop when it next checks the number. We call this when starting a new board or a shuffle. During a shuffle, we keep the collection’s final frames until the collected buttons have been replaced. Then we release those old effects and deal the new buttons.

What if the player wants less motion?

Some players might get motion sickness from watching the tiles move like this. So we need to check the reduced motion preference before starting travel. We also listen for changes while the game is open.

reducedMotion.addEventListener('change', () => {
    animateHintReveal();
    if (reducedMotion.matches) {
        stopSound(sounds.shuffle);
        tileAnimations.forEach((animation) => animation.finish());
    }
});

If reduced motion is turned on during travel, finish() takes each active tile animation directly to its end, making the board ready. Any later phase sees the preference and skips its travel too. animateHintReveal() handles the hint button’s own effect, and we stop the collection or dealing sound. You can learn more about the animation API in the Animation.finish() and reduced-motion references.

So we have our tiles on the board. They are arranged in a known layout, and their faces are showing. It’s Time to finally let the player play.

Game time

To let the player play, we need to add some interactions.

  • Show the available pairs count.
  • Hovering over the tiles
  • Selecting a tile
  • Clearing a matched pair from the board
  • Make mistakes
  • Shuffle the board
  • Ask for a hint
  • Undoing a move
  • Win
  • Lose

Let’s see how we can do all of these.

Show the available pairs count

We can add a non-interactive area in the interface to show the count and update it every time a pair is removed. To do that, we first need to keep track of the free tiles and possible matches.

We already have our tiles map and remainingIds set. The map lets us find a tile’s data by ID. The set tells us which tiles are still on the board. We need both when deciding whether a tile is free.

function tileIsFree(tile) {
    let leftIsBlocked = false;
    let rightIsBlocked = false;

    for (const otherId of remainingIds) {
        if (otherId === tile.id) {
            continue;
        }

        const other = tiles.get(otherId);

        if (
            other.layer > tile.layer &&
            Math.abs(other.row - tile.row) <= 1 &&
            Math.abs(other.column - tile.column) <= 1
        ) {
            return false;
        }

        if (
            other.layer === tile.layer &&
            Math.abs(other.row - tile.row) <= 1
        ) {
            leftIsBlocked ||= other.column === tile.column - 2;
            rightIsBlocked ||= other.column === tile.column + 2;
        }
    }

    return !leftIsBlocked || !rightIsBlocked;
}

The rules probably look familiar from the PHP backend tutorial. A tile needs a clear top and at least one open horizontal side. We used those rules when preparing a solvable deal. Now the browser needs to apply them to the tiles the player has left.

We go over the remaining IDs and skip the tile we’re checking. A tile on a higher layer can cover us. Since our layout coordinates are half-tile steps, even a one-step difference in row or column can mean an overlap. So we return false as soon as we find a tile covering any part of ours.

On the same layer, we track the two sides separately. A neighbor two column steps away is one full tile width to the left or right. It can block that side if its row also overlaps ours. We use an interesting shorthand here: ||=. The official name is: Logical OR assignment operator. It’s the same as writing:

if (!leftIsBlocked) {
  leftIsBlocked = (other.column === tile.column - 2);
}

Meaning:

  • If leftIsBlocked is true, do nothing.
  • If leftIsBlocked is false, check whether `other.column` is equal to tile.column - 2. If it is, leftIsBlocked becomes true.

The same logic applies to the line below it, with rightIsBlocked. Then we just return true if either side is blocked.

This helper gives us the current free tiles as an array.

function findFreeTiles() {
    return Array.from(remainingIds, (id) => tiles.get(id)).filter(
        tileIsFree
    );
}

Array.from() turns the remaining IDs into their tile objects. Then filter(tileIsFree) keeps the objects whose positions pass the check. With those tiles, we can count the available pairs.

function countAvailablePairs(freeTiles) {
    const matchesByFace = new Map();

    freeTiles.forEach((tile) => {
        matchesByFace.set(
            tile.match,
            (matchesByFace.get(tile.match) ?? 0) + 1
        );
    });

    return Array.from(matchesByFace.values()).reduce(
        (total, count) => total + Math.floor(count / 2),
        0
    );
}

We check for matching pairs using the tile.match rule. An orchid and a rose can have different drawings and the same matching key (“match”: “group:flowers”). Counting the faces would miss that pair.

We increase the count for each matching key. ?? 0 supplies zero the first time we see one. Then we divide each count by two and round down with Math.floor().

For example, three free flower tiles give us one pair and one leftover flower. Four give us two pairs we can remove. We’re counting how many pairs can be formed without reusing a tile. The count can change after every move, since taking one pair may free the pieces underneath it.

We bring the results together in updateFreeTiles().

function updateFreeTiles(
    showResults = true,
    turnSoundGeneration = soundGeneration
) {
    const freeTiles = findFreeTiles();
    const freeIds = new Set(freeTiles.map((tile) => tile.id));
    const pairCount = countAvailablePairs(freeTiles);

    remainingIds.forEach((id) => {
        const isFree = freeIds.has(id);
        const tile = tiles.get(id);
        const button = board.querySelector(
            `[data-tile-id="${CSS.escape(id)}"]`
        );
        button.classList.toggle('is-free', isFree);
        button.disabled = !isFree || boardIsLocked;
        button.setAttribute('aria-disabled', String(button.disabled));
        button.setAttribute(
            'aria-label',
            `${tile.label}, ${isFree ? 'free' : 'blocked'}`
        );
    });

    availablePairs.textContent = pairCount;
    availablePairs.setAttribute(
        'aria-label',
        `Available pairs: ${pairCount}`
    );
    board.setAttribute(
        'aria-label',
        `${board.dataset.layoutLabel} Mahjong board, ${remainingIds.size} tiles`
    );
    updateControls(pairCount);

    if (showResults && remainingIds.size === 0) {
        showResult(
            'You cleared the board!',
            `All ${matchCount} pairs were matched.`,
            sounds.boardCleared,
            turnSoundGeneration
        );
    } else if (showResults && pairCount === 0 && !boardIsLocked) {
        showResult(
            'No pairs are available',
            'Close this message to undo a move or shuffle the remaining tiles, or start a new board.',
            sounds.gameOver,
            turnSoundGeneration
        );
    } else if (!boardIsLocked) {
        status.textContent =
            selectedId === null
                ? 'Choose any free tile.'
                : 'Now choose a matching free tile.';
    }
}

The freeIds set gives us a quick way to check each button. We add or remove the is-free class, update its disabled state, and give it a label that includes whether it is free or blocked. The visible count goes into the #available-pairs element in index.html. Its label and the board’s label also update.

updateControls(pairCount) keeps the action buttons in sync. We’ll go over those controls as we add each feature.

There are also a couple of result checks near the bottom of this function. We need to detect an empty board before checking for zero pairs. An empty board has zero pairs too, but that is a very good zero. We’ll get back to both cases in the Win and Lose sections.

We call this updater after a deal, after a completed turn, and after restoring or shuffling the board. Each call works from the current state, so newly exposed tiles become available straight away.

Hovering over the tiles

Now we know which tiles can be picked. We should also let the player see that. A free tile gets a pointer cursor and a stronger color treatment when hovered. The same treatment applies to keyboard focus, selection, and hints.

.tile.is-free {
    cursor: pointer;
}

.tile.is-free:focus-visible,
.tile.is-removing {
    z-index: 1000000;
}

.tile.is-free:hover,
.tile.is-free:focus-visible,
.tile.is-free:active,
.tile.is-selected,
.tile.is-hinted {
    filter: saturate(6);
    transform: none;
}

.tile.is-free:focus-visible {
    outline: 0.125rem solid var(--tile-focus);
    outline-offset: -0.375rem;
}

The:focus-visible rules are especially useful. They give the focused tile an outline and raise its paint order so neighboring tile edges won’t hide it. We keep the normal interaction treatment in place, without shifting the tile’s position when the player points at it.

What about moving through 144 buttons with a keyboard? That sounds like a lot of Tab presses. We can keep the stops down to the tiles that can actually be played.

In updateFreeTiles(), button.disabled = !isFree || boardIsLocked sets the real HTML disabled state. Disabled buttons are skipped in the normal Tab order. The aria-disabled attribute describes the state too, but the native disabled property drives browser behavior.

Among the tile buttons, the player can Tab forward or use Shift+Tab to go back through the free ones. Enter or Space activates the focused button. The controls and the scrollable board viewport remain part of the page’s keyboard navigation as well. We use the normal button behavior here. An arrow-key board navigator would need its own implementation.

Which tiles can take focus?Of four tiles in a row, A and D have an open side and no tile above. B is blocked on both sides, and C is covered. Among these four lower-layer buttons, Tab stops at A and D. Other free tiles and page controls also take focus.Which tiles can take focus?Four tile buttons on the lower layer.ABCDUpper tileOpensideBothblockedTileaboveOpensideTabTab skips the blocked tile buttons.Other free tiles and controls also take focus.

After removing the focused pair, we also need somewhere sensible to put focus.

function focusFreeTile() {
    board
        .querySelector('.tile.is-free')
        ?.focus({preventScroll: true});
}

This finds the first button currently marked free and focuses it. The optional ?. means the call is skipped if there is no such button. preventScroll keeps that focus move from also making the page jump. We’ll call it after a successful match, unless a result dialog has opened.

These choices follow the same practical goal as the accessibility post. A player should be able to tell which tile is active and use the game with the input they have.

Selecting a tile

The player has found a free tile. Let’s let them pick it. We attach one click listener to the board.

board.addEventListener('click', (event) => {
    const button = event.target.closest('.tile.is-free');
    if (button && board.contains(button) && !button.disabled) {
        selectTile(button);
    }
});

Clicks bubble up through the DOM, so the board can handle clicks from its tile buttons. closest() finds the free tile containing the clicked element, and we make sure it belongs to this board and is enabled. This also keeps working after Undo or Shuffle replaces the buttons. We don’t need to attach a fresh listener to every tile.

The listener calls selectTile(). That function handles the first pick, a matching second pick, and a mismatched second pick. We’ll look at its body in those parts. The following code starts immediately inside the function, where button is the tile we just activated.

Two picks, two outcomesAfter two free tiles are selected, their match keys decide the result. A match removes both tiles. A mismatch shakes them and clears the selection, leaving both tiles on the board.Two picks, two outcomesA wrong pair stays on the board.Pick a free tilePick another free tileSame match key?YesNoMATCHRemove both tilesRecount free tiles144 tiles -> 142MISMATCHShake both tilesClear the selection144 tiles -> 144A mismatch changes no tile positions.

if (boardIsLocked) {
    return;
}
playSoundEffect(sounds.tileClick);

const tileId = button.dataset.tileId;
clearHints();

if (selectedId === tileId) {
    clearSelection();
    updateFreeTiles();
    return;
}

if (selectedId === null) {
    selectedId = tileId;
    button.classList.add('is-selected');
    button.setAttribute('aria-pressed', 'true');
    updateFreeTiles();
    return;
}

const firstId = selectedId;
const firstTile = tiles.get(firstId);
const secondTile = tiles.get(tileId);
const firstButton = board.querySelector(
    `[data-tile-id="${CSS.escape(firstId)}"]`
);

boardIsLocked = true;
updateControls();
const turnSoundGeneration = soundGeneration;

We first check boardIsLocked. A quick third click can arrive while we’re still dealing with the second one. The lock makes that extra activation harmless. We also clear an old hint highlight, since the player has now made a choice.

If there is no selection, we save the tile’s ID, give it the is-selected class, and set aria-pressed to true. The CSS makes the selection visible. The pressed state also gives assistive technology information about the button’s selection.

Clicking the same tile again clears that choice. It’s a small freedom, but an important one. I would rather let the player change their mind than make them pick another tile just to escape the first one.

function clearSelection() {
    if (selectedId !== null) {
        const button = board.querySelector(
            `[data-tile-id="${CSS.escape(selectedId)}"]`
        );
        button.classList.remove('is-selected');
        button.setAttribute('aria-pressed', 'false');
    }

    selectedId = null;
}

With a different second tile, we look up both objects and the first button. We then lock the board, update the controls, and keep the current sound generation. The rest of selectTile() decides what happens to the pair.

Clearing a matched pair from the board

We compare the two match values. That one comparison works for both identical faces and special groups such as flowers. Here’s the matching branch, continuing inside selectTile() with the variables from the previous excerpt.

if (firstTile.match === secondTile.match) {
    playSoundEffect(sounds.match);
    rememberMove();
    selectedId = null;
    matchCount += 1;
    [firstButton, button].forEach((element) =>
        element.classList.add('is-removing')
    );
    status.textContent = `Matched ${firstTile.label}.`;

    turnTimer = window.setTimeout(
        () => {
            remainingIds.delete(firstId);
            remainingIds.delete(tileId);
            firstButton.remove();
            button.remove();
            boardIsLocked = false;
            updateFreeTiles(true, turnSoundGeneration);
            if (!resultDialog.open) {
                focusFreeTile();
            }
        },
        reducedMotion.matches ? 0 : REMOVE_DURATION
    );
    return;
}

We play the match effect, call rememberMove(), and increase the match count. The saved move will matter when we get to Undo. For now, we can clear the selection and apply the is-removing class to both buttons.

.tile.is-removing {
    pointer-events: none;
    filter: brightness(1.18) saturate(1.12);
    opacity: 0;
    transform: translateY(-24px) rotate(4deg) scale(0.72);
    transition: filter 180ms ease,
                opacity 280ms ease,
                transform 280ms cubic-bezier(0.2, 0.75, 0.25, 1.12);
}

The class fades and lifts the matched tiles out of view. pointer-events: none also prevents either of those departing buttons from receiving pointer input. Meanwhile, the JavaScript lock prevents another turn from starting.

The removal timer waits 280 milliseconds, matching the CSS opacity and transform transitions. If the player prefers reduced motion, we use a zero delay. A zero-delay timer still schedules its callback, but we can skip the extra wait for the visual effect.

Inside the callback, we remove the pair from both places that track it. We delete their IDs from remainingIds and remove their buttons from the DOM. The tile objects stay in the tiles map, ready if Undo needs them.

Updating the state and the page together matters. An invisible tile still in remainingIds could keep blocking its neighbor. A button left on the page after its ID is removed could appear playable even though the game has stopped counting it.

Now we unlock the board and call updateFreeTiles() again. The gap may have exposed another tile. If no result dialog opened, we focus a free tile so the keyboard player can keep going.

Make mistakes

Sometimes the second tile just isn’t the one we thought it was. Maybe that owl looked like the other owl. It happens. The last branch of selectTile() handles the failed match.

playSoundEffect(sounds.mismatch);
[firstButton, button].forEach((element) =>
    element.classList.add('is-mismatch')
);
status.textContent =
    'The selected tiles do not match. Try another pair.';

turnTimer = window.setTimeout(
    () => {
        [firstButton, button].forEach((element) => {
            element.classList.remove('is-mismatch', 'is-selected');
            element.setAttribute('aria-pressed', 'false');
        });
        selectedId = null;
        boardIsLocked = false;
        updateFreeTiles();
    },
    reducedMotion.matches ? 0 : MISMATCH_DURATION
);

We play the mismatch effect, mark both buttons, and put a message in the status area. The tiles are still on the board. We briefly shake them to show which pair failed, then restore their usual appearance.

.tile.is-mismatch {
    animation: mismatch 480ms ease;
}

@keyframes mismatch {
    0%,
    100% {
        transform: translateX(0);
    }
    25% {
        transform: translateX(-5px);
    }
    50% {
        transform: translateX(5px);
    }
    75% {
        transform: translateX(-3px);
    }
}

The CSS shake lasts 480 milliseconds. The JavaScript waits 520 milliseconds before clearing it, giving the feedback a little room to finish. Then it removes the mismatch and selection classes, resets the pressed states, and clears selectedId.

The tile IDs, board contents, and match count stay the same. We unlock play and update the free-tile display, ready for another choice. The reduced-motion rules shorten the CSS animation, and the timer uses zero delay when that preference is active.

The written status message is there whether sound is enabled or not. If audio playback is blocked or the player has muted the game, the buttons and text still explain what happened.

Shuffle the board

Here’s one way we can help a stuck player. Shuffle should rearrange the tiles still on the board. It should keep the layout, the empty gaps, and the number of tiles we’ve already removed.

async function shuffleTiles() {
    if (boardIsLocked || remainingIds.size <= 2 || shufflesLeft === 0) {
        return;
    }
    stopAllSounds();
    playSoundEffect(sounds.shuffle);
    cancelTileAnimations();
    const generation = arrangementGeneration;
    const turnSoundGeneration = soundGeneration;
    rememberMove();
    clearSelection();
    clearHints();
    beginArrangement();
    status.textContent = 'Collecting tiles…';
    if (!(await animateTiles('collect', generation))) {
        return;
    }
    const positions = Array.from(remainingIds, (id) => tiles.get(id));
    const shuffled = [...positions];

    for (let index = shuffled.length - 1; index > 0; index -= 1) {
        const otherIndex = Math.floor(Math.random() * index);
        [shuffled[index], shuffled[otherIndex]] = [
            shuffled[otherIndex],
            shuffled[index],
        ];
    }
    positions.forEach((position, index) => {
        const {face, match, label} = shuffled[index];
        tiles.set(position.id, {...position, face, match, label});
    });
    shufflesLeft -= 1;
    board.dataset.arrangement = 'deal';
    paintTiles(calculateTilePositions());
    status.textContent = 'Dealing tiles…';

    releaseTileAnimations();
    if (!(await animateTiles('deal', generation))) {
        return;
    }
    finishArrangement(turnSoundGeneration);
    if (!resultDialog.open) {
        status.textContent =
            'Tiles shuffled into the occupied positions.';
        focusFreeTile();
    }
}

We start by checking the lock, the remaining tile count, and the shuffle allowance. A board gets one shuffle, set by GAME_SETTINGS.shufflesPerBoard. With only two tiles left, swapping their identities won’t help them match, so we disable that option.

Before moving anything, we stop old sounds and animations, save the current arrangement generation, and remember the move. We clear the selection and hints, lock the board, and use the collection animation we already built. If it returns false, a newer arrangement has taken over, and this call can stop.

After collection, positions holds the tile objects for the occupied positions. Here, that variable contains complete tile objects. Our earlier calculateTilePositions() produces the separate display coordinates used when painting buttons.

We copy the list into shuffled, then mix up that copy. The random index is always smaller than the current index. For example, when the index is 3, the other index can be 0, 1, or 2. It can’t pick 3 and swap the item with itself.

This is Sattolo’s algorithm. It creates a single cycle through the entries, so every entry ends at a different position. Two copies of the same picture may still exchange places, which can make a perfectly real swap rather hard to spot.

For each occupied position, we take the new face, match, and label together. {...position, face, match, label} creates a new tile object while preserving the position’s ID and coordinates. A flower should keep its picture, its matching rule, and its name together. Otherwise we could make a very confusing game, and I think Mahjong already has enough ways to confuse me.

Shuffle faces, keep the gapsA simplified board has four tiles and two gaps. After a shuffle, each tile face moves to a different occupied slot. The two gaps stay empty, and the total number of each face stays the same.Shuffle faces, keep the gapsFour tiles remain in this small example.Before1 triangleGap1 triangleRoseOrchidGapAfterOrchidGapRose1 triangle1 triangleGapThe occupied slots stay in place.Face, match key, and label move together.

Then we update the number of shuffles left, repaint the remaining tiles, release the old collection effects, and deal the new buttons. The earlier animation helpers handle that whole visual part.

There is a limit to what this shuffle promises. The backend arranged the original deal along a legal removal plan. Here we redistribute the remaining faces over the remaining shape. We may open up a pair, but the result can still get stuck. Guaranteeing a rescue would require more solving work for the board in its current state.

Ask for a hint

A hint is another way to help the player. And if the player has already chosen a tile, we should respect that choice before suggesting a completely different pair.

function showHint() {
    const freeTiles = findFreeTiles();
    if (
        boardIsLocked ||
        Date.now() < hintReadyAt ||
        countAvailablePairs(freeTiles) === 0
    ) {
        return;
    }
    clearHints();
    let hintedTiles = [];
    if (selectedId !== null) {
        const selected = tiles.get(selectedId);
        const partner = freeTiles.find(
            (tile) =>
                tile.id !== selectedId && tile.match === selected.match
        );
        if (partner) {
            hintedTiles = [partner];
        } else {
            clearSelection();
        }
    }
    if (hintedTiles.length === 0) {
        for (const tile of freeTiles) {
            const partner = freeTiles.find(
                (other) =>
                    other.id !== tile.id && other.match === tile.match
            );
            if (partner) {
                hintedTiles = [tile, partner];
                break;
            }
        }
    }
    hintedTiles.forEach((tile) => {
        const button = board.querySelector(
            `[data-tile-id="${CSS.escape(tile.id)}"]`
        );
        button.classList.add('is-hinted');
        button.setAttribute(
            'aria-description',
            'Hinted matching tile.'
        );
    });

    hintReadyAt = Date.now() + GAME_SETTINGS.hintCooldownMs;
    updateControls();
    animateHintReveal();
    finishHintCooldown();
    status.textContent = `Hint: ${hintedTiles.map((tile) => tile.label).join(' and ')} highlighted. Another hint will be available in one minute.`;
}

First, we get the current free tiles and check whether a hint is available. The board must be unlocked, the hint should be ready and not on cooldown, and there must be a pair to suggest.

If selectedId has a value, we look for a free partner with a different ID and the same matching key. When we find one, we highlight just that partner. The player’s first tile stays selected. That’s the useful answer to the question they were already asking.

If that tile has no free partner, we clear the selection and find a pair elsewhere. With no selection at all, we take that same search path and highlight both members of the pair. The find() callback also excludes the tile itself. A tile sharing its own matching key is true, but it wouldn’t be much of a hint.

Hints respect the first pickWithout a selection, highlight both tiles in a free pair. With a selected tile that has a partner, keep the selection and highlight only its partner. If the selected tile has no partner, clear it and highlight a free pair elsewhere.Hints respect the first pickThree ways to suggest a free pair.No tile selectedHighlight both tilesin a free pair.First pick has a partnerKeep the first pick.Show its partner.First pick has no partnerClear the first pick.Find a pair elsewhere.SelectedHintedDifferent flowers can form a matching pair.

Each hinted button gets the is-hinted class and an accessible description. The status message also names the suggested tiles. The hint leaves the actual move to the player.

This is a hint for a legal pair in the current position. It doesn’t search for a complete winning route. A pair can be available now and still lead to trouble later, just as we saw with the backend’s initial solution and the player’s freedom to choose other moves.

We also put the hint button on cooldown to make the player wait one minute before asking again. hintReadyAt = Date.now() + GAME_SETTINGS.hintCooldownMs saves an absolute deadline. Undo, and new boards leave that deadline in place. Here’s the function that checks when the wait is over.

function finishHintCooldown() {
    window.clearTimeout(hintTimer);
    const remaining = hintReadyAt - Date.now();
    if (remaining > 0) {
        hintTimer = window.setTimeout(finishHintCooldown, remaining);
    } else {
        updateControls();
    }
}

A timer callback may run late, especially when the tab has been in the background. We compare the deadline with the current time, and if there’s still time left, we schedule another check. The deadline is what controls availability. The animation shows the player how the wait is going.

function animateHintReveal() {
    hintAnimation?.cancel();
    hintAnimation = null;
    const remaining = hintReadyAt - Date.now();
    if (remaining <= 0 || reducedMotion.matches) {
        return;
    }
    hintAnimation = hintReveal.animate(
        [
            {clipPath: 'inset(100% 0 0)'},
            {clipPath: 'inset(0% 0 0)'},
        ],
        {
            duration: GAME_SETTINGS.hintCooldownMs,
            easing: 'linear',
            fill: 'both',
        }
    );

    hintAnimation.currentTime =
        GAME_SETTINGS.hintCooldownMs - remaining;
}

This animates a clipped copy of the Hint button’s label and icon. The copy is inside the real button and has aria-hidden="true", so it adds a visual effect without adding another name or keyboard stop. Its CSS supplies the enabled foreground and background colors. Revealing both together keeps the intended contrast as the edge moves upward.

inset(100% 0 0) clips the copy completely from the top. Animating it to inset(0% 0 0) reveals it from the bottom. We use the same animation API as before, then set currentTime to the progress already made. Returning to the tab should show where the minute has reached.

The visibility listener refreshes that deadline check and the visible progress when needed.

document.addEventListener('visibilitychange', () => {
    finishHintCooldown();
    if (!document.hidden) animateHintReveal();
});

Reduced motion hides this moving reveal. The timer still runs, and the real button is enabled when the deadline has passed. The label also says when the hint is recharging, so the visual effect carries extra feedback rather than the game rule itself.

Undoing a move

We want to let the player undo a move. That means we need to remember the board before changing it. Both a successful match and a shuffle call the same helper.

function rememberMove() {
    history.push({
        tiles: new Map(tiles),
        remainingIds: new Set(remainingIds),
        matchCount,
        shufflesLeft,
    });
}

A whole-board snapshot is small enough for this demo. We save the map, remaining IDs, match count, and shuffle allowance. The history array acts as a stack. push() adds the latest snapshot, and pop() will take that one back first.

There is an important detail in new Map(tiles). It copies the map’s entries into a new container, but the tile objects are still shared. That works because the game creates new tile objects when it shuffles faces. It doesn’t change the old objects saved in previous snapshots. If we started changing those objects in place, we would need to revisit the snapshot design.

Now we can restore the most recent state.

function undoMove() {
    if (boardIsLocked || history.length === 0) {
        return;
    }
    stopAllSounds();
    const previous = history.pop();
    tiles = previous.tiles;
    remainingIds = previous.remainingIds;
    matchCount = previous.matchCount;
    shufflesLeft = previous.shufflesLeft;
    selectedId = null;
    paintTiles(calculateTilePositions());
    updateFreeTiles(false);
    status.textContent =
        'Move undone. The previous board and shuffle allowance are restored.';
    if (history.length === 0) {
        focusFreeTile();
    }
}

After checking the lock and history, we pop the latest snapshot and restore its values. We clear the current selection, calculate the tile positions, and repaint. The normal tile creation code gives us the correct pictures and positions again.

updateFreeTiles(false) refreshes the board and controls without opening another result dialog. We put our own Undo message in the status area. If we’ve just used the last saved move, the Undo button becomes disabled. Moving focus to a free tile gives the keyboard player an available control to continue with.

Restoring shufflesLeft also returns the shuffle allowance. Try shuffling and then undoing it. You get the old faces back in the old spots, and you can use that shuffle again. The hint deadline stays where it was. A hint didn’t move a tile, so it has its own timing rule.

Undo restores the snapshotA snapshot before a shuffle records the tile state, four remaining tiles, 70 matched pairs, and one shuffle left. Shuffling uses that allowance. Undo restores the previous tiles and counters. The hint deadline is separate.Undo restores the snapshotThe saved board includes its counters.Saved before the shuffle4Tiles left70Pairs matched1Shuffles leftAfter the shuffle4Tiles left70Pairs matched0Shuffles leftAfter Undo4Tiles left70Pairs matched1Shuffles leftShuffleUndoThe hint deadline keeps its own timing.

We now have all three recovery controls. This is the updater we have been calling to keep their disabled states in sync.

function updateControls(
    pairCount = countAvailablePairs(findFreeTiles())
) {
    undo.disabled = boardIsLocked || history.length === 0;
    shuffle.disabled =
        boardIsLocked || remainingIds.size <= 2 || shufflesLeft === 0;

    const isCooling = Date.now() < hintReadyAt;
    const hintLabel = isCooling
        ? 'Hint recharging: one hint per minute'
        : 'Hint';
    hint.disabled = boardIsLocked || pairCount === 0 || isCooling;
    hint.classList.toggle('is-cooling', isCooling);
    if (!isCooling) {
        hintAnimation?.cancel();
        hintAnimation = null;
    }
    hint.setAttribute('aria-label', hintLabel);
    hint.title = hintLabel;
}

The event listeners connect each button to its handler.

undo.addEventListener('click', undoMove);
shuffle.addEventListener('click', shuffleTiles);
hint.addEventListener('click', showHint);

Disabling a button helps the player see what is available. Each handler also checks its conditions, so the board lock and allowances are enforced when the action actually runs.

Win

After the last pair is removed, remainingIds.size is zero. We already check that first in updateFreeTiles(). We send the title, message, and result sound to a shared function.

function showResult(title, message, sound, turnSoundGeneration) {
    document.querySelector('#result-title').textContent = title;
    document.querySelector('#result-message').textContent = message;
    status.textContent = `${title} ${message}`;

    if (!resultDialog.open) {
        resultDialog.showModal();
        if (turnSoundGeneration === soundGeneration) {
            stopAllSounds();
            playSoundEffect(sound);
        }
    }
}

We put the text into both the dialog and the persistent status area. showModal() opens the HTML <dialog> with modal behavior, including moving focus into it and making the surrounding document inert. The browser saves us the work and does it for us. The title and message are connected through aria-labelledby and aria-describedby in the markup.

<dialog
 id="result-dialog"
 class="result-dialog"
 aria-labelledby="result-title"
 aria-describedby="result-message"
>
 <h2 id="result-title">Board complete</h2>
 <p id="result-message"></p>
 <div class="dialog-actions">
  <button id="dialog-new-game" class="button" type="button">
   <svg class="icon" aria-hidden="true">
    <use href="#icon-new" />
   </svg>
   Play a new board
  </button>
  <button
   id="close-dialog"
   class="button button-secondary"
   type="button"
  >
   <svg class="icon" aria-hidden="true">
    <use href="#icon-close" />
   </svg>
   Close
  </button>
 </div>
</dialog>

The resultDialog.open check avoids opening the same dialog again while it’s already displayed. Before playing the result sound, we also compare the saved sound generation with the current one. Muting while the final pair is disappearing should stay quiet, even when its delayed callback finishes.

We connect the dialog’s two buttons like this.

document
    .querySelector('#dialog-new-game')
    .addEventListener('click', () => {
        resultDialog.close();
        loadBoard();
    });
document
    .querySelector('#close-dialog')
    .addEventListener('click', () => resultDialog.close());

Play a new board closes the dialog and calls the loadBoard() function we covered earlier. Close dismisses the message and leaves the current board available for recovery controls. That second choice is useful for our other result too.

Lose

We can still have tiles on the board and no free matching pair. That’s the second result check in updateFreeTiles(). It runs when results are enabled, the pair count is zero, and the board is unlocked. We show the same dialog with a different title and message.

This is a dead end for the current arrangement. Picking a different first tile won’t produce a matching free pair, because we counted all of them. The player can close the message and use Undo, use Shuffle if its allowance and tile count permit it, or request a new board.

We keep those choices available rather than wiping the board as soon as the player gets stuck. The backend gave the initial deal a legal route to an empty board, but the player can choose pairs that close off that route. Finding a good order is part of the game. A shuffle may help with the current position, and Undo lets us try another choice.

Try getting a board into a tight spot, closing the message, and undoing the last pair. The old buttons return, the free edges are recalculated, and the pair count follows the restored board. All the little pieces we added are now working together.

Final words

That brings us to the end of this Mahjong tutorial series. We started with a tile, built a layout, created a backend to prepare a board configuration, and turned its response into a playable board. Now we can choose pairs, make mistakes, ask for help, and even admit that our last move might have been a bad idea. Undo is a very understanding button.

In our next game tutorial, we’ll have a little character that the player can control and move around, movable objects, and collisions. In the meantime, download the full source code and play with the demo. Try changing some things around. Perhaps create new layouts and test them, let the player choose a deck, or reward them with a new shuffle allowance after a certain number of successful matches. That will also give you an excuse to play the game some more. For testing purposes, of course.

Be the first to comment

Name, email, and comment are required. Your email address will not be published.