Your cat is not available now, please call back later
CAT'S BLOG

Yet another 2048

icon

It was a very long 10-hours-long flight and I watched all seasons of Severance that I had on my phone and read all comic books.

Being too bored, I started writing a 2048-inspired game that I wanted to do for a very long time just because I always wanted to dynamically choose the field size and play it on absurdly large board size (like 16x16). Now i know, that it's not that funny, but anyway.

TL;DR

2048-inspored game with variable grid size, works on both: mobile and desktop.

You can play here: 2048.x96.dev.

Game overview

Game logic is very simple and breaks down into several statements: - Each step 1-2 new cells are generated (if there is empty space on grid) - Used swipes up / down / left / right - When there is empty space, cells move towards the empty space - When there is no empty space but cell with the same value, cells can be merged - Once user can not make cells merge or move (grid is stuck), game is over

Notes (for simplicity, swipe up from down to up): - Cells are processed starting from top to bottom - Each cell moves up until there is empty cell or cell with the same value - Cell can not be merged with cell that appeared as a result of previous cell merge

Here how it works with 2 swipes up:

stacking

In my case, score is added up every time two cells are merged and incremented by value of one of two cells.

Coding

I will write a stream of thoughts and try to reproduce history by code from commits and leaking memory and provide listings of code to explain how it works.

Prototype

It started as an idea to play 2048 on some absurd resolutions, like 2x2, 3x3, 16x16 and other possible and I had too much free time without internet and books, so i opened my microlaptop (used to write microservices) and started writing frontend based on experience of writing a 1010 clone for web.

It all started with making a simple grid in plain HTML:

<body>
    <div class="center-horisontal">
        <div class="center-vertical">
            <div class="game">
                <div class="board">
                    <div class="row">
                        <div class="cell">9</div>
                        <div class="cell">7</div>
                        <div class="cell">709</div>
                        <div class="cell">30969</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

And a tiny pile of CSS:

:root {
    --background: #141414;
    --board-background: #ededed;
    --board-cell-color-base: #141414;

    --unit: min(1vw, 1vh, 1rem);

    --board-size: calc(var(--unit) * 50);
    --board-padding: calc(var(--unit) * 2);
    --board-cell-size: calc(var(--unit) * 10);
    --board-cell-gap: calc(var(--unit) * 2);
}

* {
    box-sizing: border-box;
}

html,
body {
    padding: 0;
    margin: 0;

    background-color: var(--background);
}

.center-vertical {
    width: 100%;
    height: 100%;

    display: flex;

    flex-direction: row;
    align-items: center;
    justify-content: center;
}

.center-horisontal {
    width: 100%;
    height: 100%;

    display: flex;

    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.game {
    .board {
        width: var(--board-size);
        height: var(--board-size);

        background-color: var(--board-background);

        padding: var(--board-padding);

        border-radius: 1rem;
        border: none;

        .row {
            display: flex;
            flex-direction: row;
            align-items: start;
            justify-content: center;

            gap: var(--board-cell-gap);

            .cell {
                width: var(--board-cell-size);
                height: var(--board-cell-size);

                background-color: var(--board-cell-color-base);

                border-radius: 0.51rem;
            }
        }
    }
}

And that's how it looks:

screenshot

Btw, I use global variables defined inside :root css section - later I can style colors as I want and add custom themes like dark/light theme switch (obviously, I'm too lazy to do it), and nested css classes - they're really cool.

After making a single row, add 12 more cells and look at the result:

screenshot

Perfect grid. Time to javascript.

Game state

There are several things to keep in memory. They are primarily used for faster access to game state and less modifications to DOM.

app.config = {
    size: ..., // - board size from URL
}

app.board = {
    size: ..., // - board size from app.config.size
    cells: [ // - 2D Array of cells to store all game board cells state
        ...,
        [
            {
                value: ..., // - current cell value integer, for ease of use
                element: { // - collection of HTML elements
                    cell: ..., // - cell element itself, used to modify color,
                               //   outline and other things
                    text: ..., // - cell text element, with text content of cell,
                               //   used to display text itself and scale it
                               //   based on number string length
                },
                row: ..., // - cell row index
                column: ..., // - cell column index
            }
        ]
        ...,
    ]
}

Game Config

During initial setup, options are parsed using parse_query_params:

// Defaults for config and post-processing function used to parse parameters
const CONFIG = {
    size: {
        value: 4,
        converter: (v) => Math.max(2, parseInt(v)),
    },
};

function parse_query_params(defaults) {
    const query_string = window.location.search;
    const params = new URLSearchParams(query_string.startsWith('?') ? query_string.slice(1) : query_string);
    const result = {};

    for (const [key, default_value] of Object.entries(defaults)) {
        const query_value = params.get(key);

        if (query_value !== null) {
            try {
                result[key] = (
                    default_value.converter
                    ? default_value.converter(query_value)
                    : query_value
                );
            } catch (error) {
                result[key] = default_value.value;
            }
        } else {
            result[key] = default_value.value;
        }
    }

    return result;
};

This function was mostly vibe-coded (ok, just a good textual prompt, description of input, expected output, structure of defaults object and fixes).

Early Init and Game Flow

Game starts when board is created, and this is how it works

function create_board(app) {
    function create_cell() {
        var cell = document.createElement("div");
        cell.classList.add("cell");

        var cell_text = document.createElement("div");
        cell_text.classList.add("text");

        cell.appendChild(cell_text);

        var element = {
            cell: cell,
            text: cell_text,
        }

        return element;
    }

    var board_grid = [];

    for (let row = 0; row < app.config.size; ++row) {
        var board_row = [];
        board_grid.push(board_row);

        var row_element = document.createElement('div');
        row_element.classList.add('row');
        app.board_element.appendChild(row_element);

        for (let column = 0; column < app.config.size; ++column) {
            board_row.push({
                row: row,
                column: column,
                element: create_cell(),
                value: 0,
            });
            row_element.appendChild(board_row[column].element.cell);
        }
    }

    // Tweak styles
    document.documentElement.style.setProperty('--board-cell-size', `calc(${ BASE_UNIT} * ${ BASE_CELL_SIZE / app.config.size })`);
    document.documentElement.style.setProperty('--board-cell-margin', `calc(${ BASE_UNIT} * ${ BASE_CELL_MARGIN / app.config.size })`);
    document.documentElement.style.setProperty("--pop-size", `calc(var(--unit) * ${ BASE_CELL_POP_SIZE / app.config.size })`);

    app.board = {
        root: app.board_element,
        size: app.config.size,
        cells: board_grid,
    };
};

Important thing is setting values of global css variables which are used to change size of cells and game board. Also, pop animation when cells are merged.

Next, we need to define functions used to initialize game state, board and score. These functions should clear the board, clear score, initialize board with random cells like in original game:

// Called restart, but used to initialize at start and at restart
function restart_game(app) {
    // Clear board
    for (let row = 0; row < app.board.size; ++row) {
        for (let column = 0; column < app.board.size; ++column) {
            set_cell_value(
                app,
                row,
                column,
                0,
            );
        }
    }

    // Spawn some cells
    spawn_cells(app, Math.floor(app.config.size / 2));
    set_score(app, 0);

    // Clear flag
    app.is_over = false;

    // Hide elements
    app.game_over_element.style.display = 'none';
    app.restart_element.style.display = 'none';
};

Using magic set_cell_value function, it sets values of each cell. Function set_cell_value does: - Set integer value of cell - Set text of cell text element - Compute color based on log2 of cell value - Add cell outline for future animation (and to cancel animation of empty cells)

function set_cell_value(app, row, column, value) {
    function scale_font_css(app, value) {
        var base_size = BASE_CELL_TEXT_SIZE / app.board.size;
        var text = `${ value }`;

        if (text.length <= BASE_CELL_TEXT_THRESHOLD) {
            return `calc(var(--unit) * ${ base_size })`;
        }

        var size = base_size * BASE_CELL_TEXT_THRESHOLD / text.length;
        return `calc(var(--unit) * ${ size })`;
    }

    app.board.cells[row][column].value = value;
    app.board.cells[row][column].element.text.textContent = `${ value }`;
    app.board.cells[row][column].element.text.style.fontSize = scale_font_css(app, value);

    if (value === 0) {
        app.board.cells[row][column].element.text.textContent = "";

        // Pop animation
        app.board.cells[row][column].element.cell.style.outlineColor = null;

        // Color change
        app.board.cells[row][column].element.cell.style.backgroundColor = null;
        app.board.cells[row][column].element.text.style.color = null;
    } else {
        app.board.cells[row][column].element.text.textContent = `${ value }`;

        var color_index = Math.floor(Math.log2(value)) - 1;
        color_index = Math.min(Math.max(color_index, 1), COLORS.length);

        // Pop animation
        app.board.cells[row][column].element.cell.style.outlineColor = COLORS[color_index];
        // Color change
        app.board.cells[row][column].element.cell.style.backgroundColor = COLORS[color_index];
        app.board.cells[row][column].element.text.style.color = CELL_ACTIVE_TEXT_COLOR;
    }
}

Here I use a color palette that was generated using gemma3, but I don't like it and probably will rewrite it by myself later.

It took at least 5 attempts to generate a palette with feeding screenshots of palette back to LLM

screenshot

Gradient that gradien't

const COLORS = [
    "#9EC79E",
    "#A9D3A9",
    "#BBD9B7",
    "#C8D6C4",
    "#D4E2D8",
    "#E0EDD3",
    "#EBD8CD",
    "#F4EACF",
    "#F9F1D3",
    "#FCE6B7",
    "#FBB982",
    "#FFA76F",
    "#FF946A",
    "#FF8070",
    "#FFAB98",
    "#FFB3C1",
    "#E5B3CC",
    "#D8B2D2",
    "#C5A3D1",
    "#B390CD",
    "#9B80B0",
    "#8F9DB5",
    "#B3C1D0",
    "#D1D9E1",
];
const DEBUG_COLORS = false;

Also, here is a nice debug flag DEBUG_COLORS that can draw a R A I N B O W at the bottom of the page

palette

And function used to generate random cell values with pre-defined probability:

const RANDOM_VALUES = [
    { value: 2, probability: 0.9 },
    { value: 4, probability: 0.09 },
    { value: 8, probability: 0.01 },
];

function get_random_cell_value() {
    const total_probability = RANDOM_VALUES.reduce((sum, item) => sum + item.probability, 0);

    let random_number = Math.random();
    let cumulative_probability = 0;

    for (let i = 0; i < RANDOM_VALUES.length; i++) {
        cumulative_probability += RANDOM_VALUES[i].probability;
        if (random_number < cumulative_probability) {
            return RANDOM_VALUES[i].value;
        }
    }


    return RANDOM_VALUES[values.length - 1].value;
};

function spawn_cells(app, amount) {
    const free_cells = [];

    for (let row = 0; row < app.board.size; row++) {
        for (let column = 0; column < app.board.size; column++) {
            if (app.board.cells[row][column].value === 0) {
                free_cells.push({
                    row: row,
                    column: column,
                });
            }
        }
    }

    if (free_cells.length === 0) {
        return;
    }

    for (let index = 0; index < amount; index++) {
        const random_index = Math.floor(Math.random() * free_cells.length);
        const { row, column } = free_cells[random_index];

        set_cell_value(
            app,
            row,
            column,
            get_random_cell_value(),
        );

        free_cells.splice(random_index, 1);
    }
};

Following the game logic, it spawns random cells with random values only if there are empty cells to be filled. Each value has certain probability of being spawned and can be tweaked to change game difficulty (yes, there is difficulty in game that is based on pure random).

Pop Animations

To make it look a bit better, I've added pop animations:

@keyframes animation-pop-outline {
    0% {
        outline-width: 0;
        outline-offset: 0;
        outline-style: none;
    }
    50% {
        outline-width: var(--pop-size);
        outline-offset: calc(var(--pop-size) * -0.1);
        outline-style: solid;
    }
    100% {
        outline-width: 0;
        outline-offset: 0;
        outline-style: none;
    }
}

.game {
    /* ... */

    .board {
        /* ... */

        .row {
            /* ... */

            .pop {
                outline-offset: 0;

                animation: animation-pop-outline 0.25s ease-in-out forwards;
            }
        }
    }
}

Plan is to add pop class to cell when it has been changed and remove after animation ends using setTimeout.

Gameplay Controls

function register_event_handlers(handler) {

    // Controls

    let is_dragging = false;
    let is_dragged = false;
    let start_x, start_y;
    let swipe_timeout;

    function handle_arrow_keys(event) {
        const key = event.key;

        switch (key) {
            case "ArrowUp": {
                handler(0, +1);
                break;
            }
            case "ArrowDown": {
                handler(0, -1);
                break;
            }
            case "ArrowLeft": {
                handler(-1, 0);
                break;
            }
            case "ArrowRight": {
                handler(+1, 0);
                break;
            }
        }
    };

    function handle_touch_start(event) {
        if (is_dragging)
            return;

        if (is_dragged)
            return;

        start_x = event.touches[0].clientX;
        start_y = event.touches[0].clientY;
        is_dragging = true;
    };

    function handle_touch_move(event) {
        if (!is_dragging)
            return;

        if (is_dragged)
            return;

        const current_x = event.touches[0].clientX;
        const current_y = event.touches[0].clientY;

        const delta_x = current_x - start_x;
        const delta_y = current_y - start_y;

        const abs_delta_x = Math.abs(delta_x);
        const abs_delta_y = Math.abs(delta_y);

        if (abs_delta_x > SWIPE_THRESHOLD && abs_delta_y <= abs_delta_x / 2) {  // swipe horizontal
            is_dragged = true;

            if (delta_x > 0) {
                handler(+1, 0);
            } else {
                handler(-1, 0);
            }
        } else if (abs_delta_y > SWIPE_THRESHOLD && abs_delta_x <= abs_delta_y / 2) { // swipe vertical
            is_dragged = true;

            if (delta_y > 0) {
                handler(0, -1);
            } else {
                handler(0, +1);
            }
        }
    }

    function handle_touch_end(event) {
        is_dragging = false;
        is_dragged = false;
    };

    document.addEventListener("keydown", handle_arrow_keys);

    document.addEventListener("touchstart", handle_touch_start);
    document.addEventListener("touchmove", handle_touch_move);
    document.addEventListener("touchend", handle_touch_end);

    document.addEventListener('touchmove', function(event) { event.preventDefault(); }, { passive: false });


    // Restart button

    function restart(event) {
        restart_game(app);
    };

    app.restart_element.addEventListener('click', restart);
};

This game supports desktop and mobile, so on desktop you can use arrow keys and touch gestures on mobile. Touch swipes are triggered only by threshold to prevent accidental shift when user barely touches the screen. Both gestures trigger same function with direction vector.

I won't list the entire main logic function because there are lots of core duplicates.

function wrap_main(app) {
    // Stop animation when cell is removed
    function cell_remove(cell) {
        if (cell.pop_timeout) {
            clearTimeout(cell.pop_timeout);
            cell.element.cell.classList.remove('pop');
        }
    };

    // Start animation when cell is inserted or moved
    function cell_change(cell) {
        if (cell.pop_timeout) {
            clearTimeout(cell.pop_timeout);
            cell.element.cell.classList.remove('pop');
        }

        cell.element.cell.classList.add('pop');
        cell.pop_timeout = setTimeout(() => {
            cell.element.cell.classList.remove('pop');
        }, 250);
    };

    function cell_move(cell_from, cell_to) {
        let old_value = cell_from.value;

        set_cell_value(
            app,
            cell_from.row,
            cell_from.column,
            0,
        );
        cell_remove(cell_from);

        set_cell_value(
            app,
            cell_to.row,
            cell_to.column,
            old_value,
        );
        cell_change(cell_to);
    };

    function cell_merge(cell_from, cell_to) {
        let old_value = cell_from.value;

        set_cell_value(
            app,
            cell_from.row,
            cell_from.column,
            0,
        );
        cell_remove(cell_from);

        set_cell_value(
            app,
            cell_to.row,
            cell_to.column,
            old_value * 2,
        );
        add_score(app, old_value);

        cell_change(cell_to);
    };

    function shift_up() {
        for (let column = 0; column < app.config.size; ++column) {
            let min_row = 0;

            // Start with 1 row because 0 can not be moved above
            for (let row = 1; row < app.config.size; ++row) {

                // If cell is occupied, move it above
                if (app.board.cells[row][column].value !== 0) {
                    let seek = row;

                    // Find target cell
                    while (seek > 0 && seek > min_row) {
                        // Can move to cell with zero value
                        if (app.board.cells[seek - 1][column].value === 0) {
                            --seek;
                            continue;
                        }

                        // Can move to cell with same value
                        else if (app.board.cells[row][column].value === app.board.cells[seek - 1][column].value) {
                            --seek;
                            continue;
                        }

                        break;
                    }

                    // No movement
                    if (seek === row) {
                        continue;
                    }

                    // Process movement
                    if (app.board.cells[seek][column].value === 0) {
                        cell_move(
                            app.board.cells[row][column],
                            app.board.cells[seek][column],
                        );

                        min_row = seek;
                    } else if (app.board.cells[row][column].value === app.board.cells[seek][column].value) {
                        cell_merge(
                            app.board.cells[row][column],
                            app.board.cells[seek][column],
                        );

                        min_row = seek;
                    }
                }
            }
        }
    };

    function shift_down() {
        // ...
    };

    function shift_right() {
        // ...
    };

    function shift_left() {
        // ...
    };

    function check_shift_possible() {
        // Either board has any empty cell
        for (let row = 0; row < app.board.size; row++)
            for (let column = 0; column < app.board.size; column++)
                if (app.board.cells[row][column].value === 0)
                    return true;

        // Or at least one of board cells has adjacent cell with the same value
        for (let row = 0; row < app.board.size; row++) {
            for (let column = 0; column < app.board.size; column++) {
                const current_value = app.board.cells[row][column].value;
                if (row > 0 && app.board.cells[row - 1][column].value === current_value)
                    return true;
                if (row < app.board.size - 1 && app.board.cells[row + 1][column].value === current_value)
                    return true;
                if (column > 0 && app.board.cells[row][column - 1].value === current_value)
                    return true;
                if (column < app.board.size - 1 && app.board.cells[row][column + 1].value === current_value)
                    return true;
            }
        }

        return false;
    }

    function main(dx, dy) {
        // Check game over
        if (app.is_over || !check_shift_possible()) {
            app.is_over = true;
            show_game_over(app);
            return;
        }

        // Cell movement
        if (dy === 1)
            shift_up();
        else if (dy === -1)
            shift_down();

        if (dx === 1)
            shift_right();
        else if (dx === -1)
            shift_left();

        // Cell generation
        spawn_cells(app, 1);
    };

    return main;
};

Function shift_up implements this logic used to shift cells upwards and merge them when possible. Shifts in other directions are almost the same as up.

At first, I was too lazy to write it by myself and tried to prompt gemma3 to generate it, but after 3 attempts of detailed explaination of what I want, I just wrote it by myself.

Next, I needed a shift_down function and tried to write using prompt to gemma3, and... it worked fine:

This function implements cell shift logic for my game. Implement the same logic for shift down.

```
function shift_up() {
    // ...
};
```

Now I have shift_down function, but next attempt to merge these two functions failed, so I moved next because It was almost midnight and I wanted a working prototype already. Time to make a shift_left function and try to use LLM again.

This is function that performs cell shift logic in my game. It shifts from bottom to top.
Implement function with the same logic for shift from right to left.

```
function shift_up() {
    // ...
};
```

It failed and I just swapped row and column and everything works. Trick to make it invert direction using gemma3 worked again and finally I have all 4 functions and basic working prototype. Attempt to ask gemma3 to merge all 4 functions was a bad idea because it messed up with rows, columns and directions and ended up by random shuffling the game board.

Score Manipulation

Changing, setting, loading and saving game score is implemented by these simple functions:

function set_max_score(app, score) {
    const expiration_date = new Date();
    expiration_date.setFullYear(expiration_date.getFullYear() + 100);
    const cookie_name = `${COOKIE_NAME}-${app.board.size}`;

    document.cookie = `${cookie_name}=${encodeURIComponent(score)}; expires=${expiration_date.toUTCString()}; path=/`;
};

function get_max_score(app) {
    const cookies = document.cookie.split(';');
    const cookie_name = `${COOKIE_NAME}-${app.board.size}`;

    for (let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i].trim();
        if (cookie.startsWith(cookie_name + '=')) {
            const decodedScore = decodeURIComponent(cookie.substring(cookie_name.length + 1));
            const score = parseFloat(decodedScore);
            if (!isNaN(score)) {
                return score;
            } else {
                return 0;
            }
        }
    }

    return 0;
};

function set_score(app, score) {
    app.score = score;

    if (!app.max_score) {
        app.max_score = get_max_score(app);
    }

    if (app.score > app.max_score) {
        app.max_score = app.score;
        set_max_score(app, app.max_score);
    }

    app.score_element.textContent = `${ app.score } / ${ app.max_score }`;
};

function add_score(app, score) {
    set_score(app, app.score + score);
};

Game is using cookies to store max score value and using separate cookies for each board size (2x2, 3x3, 4x4, e.t.c).

Yes, This Website Is Using Cookies To Improve User Experience

Now I can sell this data to advertisement companies and they will target ads based on the size of board you've been playing and max score. Probably, they will target selling popit to you or idk.

toadster

Demo

Step 0: Game Selection

screenshot

Step 1: Game Starts

screenshot

Step 2: Game Games

screenshot

Step 3: Game Gamen't

screenshot

Step 4: Try Yourself

You can play here: 2048.x96.dev. Or right on this page (I guess, UX is horrible).

Notes

  • While writing LLM prompts, you sometimes find a solution to a task (hello, rubberduck) - most of the times, task is simplier than you think
  • CSS+HTML can do almost everything in game visuals and JS only used for logic
  • LLM are good for boilerplate generation (like "write me a javascript function that selects numbers from array with predefined probabilities")
  • It is still not good idea to outsource everything to LLM because grow your skills, not yout prompt length
  • I have a popit

128x128 is just fine

128x128

UPD 2025-11-18

  • Added mouse swipe gestures

>^~^<

Last modified at 2026-01-20 23:53:26 UTC