Skip to content
ToanLB
Go back

Scaling 500 Puzzle Levels in One Week: Data-Driven Pipeline, Parametric Variation, and Automated Validators

~16 min read
Scaling 500 Puzzle Levels in One Week: Data-Driven Pipeline, Parametric Variation, and Automated Validators

In mobile puzzle and hybrid-casual game studios, rapid content expansion is a weekly reality. When a title enters marketability testing or scales up for Live-ops, engineering teams routinely face a stark operational challenge: how do you produce 500 playable levels in a single week without destroying game quality?

Treating this purely as a manual labor problem usually leads to rallying the team to assemble hundreds of Unity Scenes or duplicate Prefabs one cell at a time. That approach immediately hits three walls: engineers become the content bottleneck because Game Designers cannot safely author levels alone, hard-coded Scene data bloats install size while causing constant Git merge conflicts, and QA gets buried playtesting hundreds of potentially broken boards.

Production experience in puzzle development proves that level velocity does not come from having more hands clicking inside the Inspector. It comes from building a robust Content Creation Pipeline. For a Unity engineer, solving that challenge requires four architectural layers: locking down a schema contract with Game Design, storing levels as pure data-driven configs, multiplying layouts via Parametric Variation, and enforcing quality with Editor tooling and an automated Level Validator.


1. Four Pillars of a Scalable Level Production Pipeline

Rather than jumping straight into building a drawing window or writing an uncontrolled random level generator, a reliable pipeline progresses sequentially from data contracts to automated validation:

flowchart LR
    subgraph SG_DESIGN["1. Schema & Data-Driven Model"]
        direction TB
        S1["Align Contract with Game Design<br/>(Objects, Obstacles, Win Rules, Knobs)"]
        S2["Decouple Levels from Scenes<br/>(Extensible JSON / DTO configs)"]
        S1 --> S2
    end
    subgraph SG_SCALE["2. Multiplication & Quality Gates"]
        direction TB
        S3["Parametric Variation<br/>(Tune MaxStackHeight, colors, density)"]
        S4["Editor Tool & Level Validator<br/>(Author, Preview, Block Deadlocks)"]
        S3 --> S4
    end
    S2 -->|"Feed into variant pipeline"| S3

Pillar 1: Align on the “Level Contract” with Game Design First

The most critical step happens before writing any code: sitting down with Game Design to establish an explicit definition of what a level actually contains:

Pillar 2: Extensible Data-Driven Models

A common trap in puzzle games is coupling gameplay rules tightly to level layouts: every time Game Design introduces a new obstacle or rule, developers end up refactoring core gameplay scripts. To avoid this, teams need to focus on decoupling configuration so Game Designers can iterate without calling developers and carefully weigh choosing between Prefabs, JSON, and ScriptableObjects.

Levels must never be hard-coded inside .unity Scene files. Instead, each level is represented as lightweight pure data (JSON or compact DTOs) describing the board state, while the runtime engine interprets those definitions via extensible rule and obstacle descriptors. This discipline of controlling dependencies and structuring game data at scale lets teams add new mechanics without invalidating hundreds of already-shipped levels.


2. Case Study: Parametric Variation on a Stacked-Cube Matrix Puzzle

To see how much leverage a clean data model provides, consider a real puzzle game architecture built around a stacked matrix mechanic.

The upper playfield consists of a 2D grid of cubes. However, the board is not strictly flat: each grid cell holds a visible top cube, while additional cubes can be stacked underneath it in vertical layers. Players can only interact with the cube currently exposed at the top of each stack; clearing the top cube reveals the cube beneath it.

Once this board is stored as data separate from visual rendering, the team no longer needs to craft all 500 levels from a blank canvas. Starting from a curated set of base matrix layouts authored by Game Design, adjusting just a few parameters produces distinct levels with noticeably different pacing and difficulty:

  1. Adjusting Maximum Stack Height (MaxStackHeight):
    • Lowering MaxStackHeight (for example, capping cells at 1 or 2 layers): Keeps the board visually clean, exposes most targets immediately, and minimizes hidden dependencies. These variants work well for early onboarding levels or breather stages between difficulty spikes.
    • Increasing MaxStackHeight (for example, raising stacks to 4 - 6 layers): Using the exact same grid silhouette, depth complexity rises sharply. The board becomes denser, harder to scan at a glance, and forces players to plan multi-step unblocking sequences.
  2. Tuning Color Diversity and Obstacle Distribution:
    • Raising the distinct color count (from 4 colors to 7) increases temporary tray pressure and raises challenge naturally.
    • Swapping selected top or mid-stack positions with conditional obstacles or special spawn rules generates fresh gameplay twists across level packs.

Crucially, this is controlled variation on top of handcrafted designer layouts, not blind procedural noise. From a few dozen strong base templates, the pipeline produces hundreds of varied levels while preserving deliberate visual pacing.


3. Editor Tooling & Automated Level Validator: Guarding Quality at Scale

Accelerating production to 500 levels a week turns into a liability without the second half of the equation: self-serve Designer tooling and an Automated Level Validator.

To remove engineers from the content bottleneck, Game Designers need a visual tool (such as a custom Unity EditorWindow or external web editor exporting JSON) covering four steps in one loop: Create - Visual Layer Preview - Edit - Automated Validate.

Among these, Validation determines whether QA survives the 500-level surge. A production-grade Level Validator enforces three automated gates before a level file can be exported:

flowchart TD
    Input["Authored or Generated Level Data"] --> V1{"1. Structural Check<br/>(Matrix bounds & MaxStackHeight)"}
    V1 -->|"Out of bounds / Stack overflow"| E1["Reject Save: Report structural error"]
    V1 -->|"Valid structure"| V2{"2. Parity & Resource Check<br/>(Each color divisible by MatchGroupSize?)"}
    V2 -->|"Remainder cubes / Missing keys"| E2["Reject Save: 100% Unsolvable board"]
    V2 -->|"Valid parity"| V3{"3. Solvability Heuristic Check<br/>(Simulate tray capacity & obstacle locks)"}
    V3 -->|"Early tray overflow or permanent lock"| E3["Flag Deadlock warning to Game Designer"]
    V3 -->|"Simulation cleared"| Pass["Approved: Export JSON & Difficulty Score"]

By writing both the Validator and VariantGenerator as Pure C# classes decoupled from UnityEngine.Object and UnityEditor, the exact same validation suite runs in two environments:


4. Production C# Implementation & Automated NUnit Verification

To see this pipeline in code, consider a mobile Stacked-Cube Match-3 puzzle. Players pick exposed top cubes from matrix stacks into a temporary holding tray with TrayCapacity = 7; whenever 3 matching cubes (MatchGroupSize = 3) accumulate in the tray, they clear automatically.

To scale content safely without introducing unsolvable boards, we structure the pipeline around the following pure C# data models and components:

  1. CubeCellData, PuzzleLevelData, and LevelVariationParams: Data models representing each cell’s vertical cube stack, obstacle state, global board rules, and parametric variation settings (TargetMaxStackHeight, MaxDistinctColors, Seed).
  2. ParametricLevelVariantGenerator: Generates new level variants from a base board by clamping stack heights, remapping color counts, and deterministically rebalancing cube totals so every color remains strictly divisible by MatchGroupSize.
  3. StackedCubeLevelValidator and LevelValidationReport: Performs 3-tier verification: Tiers 1 and 2 emit hard Errors for matrix/stack integrity and color parity (Count % MatchGroupSize == 0), while Tier 3 runs a greedy heuristic simulation that separates permanent obstacle locks (Errors) from tray overflow warnings (Warnings) so Designers can inspect edge-case difficulty without false-positive rejections.

Below is the complete implementation and its NUnit [TestFixture] suite:

using System;
using System.Collections.Generic;
using NUnit.Framework;

public enum ObstacleType
{
    None = 0,
    LockedUntilAdjacentCleared = 1,
    PermanentBlocker = 2
}

public sealed class CubeCellData
{
    public int X { get; }
    public int Y { get; }
    public ObstacleType Obstacle { get; }
    // Last element (Count - 1) is the top-most exposed cube in the stack
    public List<int> StackColors { get; }

    public CubeCellData(int x, int y, List<int> stackColors, ObstacleType obstacle = ObstacleType.None)
    {
        X = x;
        Y = y;
        Obstacle = obstacle;
        StackColors = stackColors ?? new List<int>();
    }
}

public sealed class PuzzleLevelData
{
    public string LevelId { get; }
    public int Width { get; }
    public int Height { get; }
    public int MaxStackHeight { get; }
    public int MatchGroupSize { get; }
    public int TrayCapacity { get; }
    public List<CubeCellData> Cells { get; }

    public PuzzleLevelData(
        string levelId,
        int width,
        int height,
        int maxStackHeight,
        int matchGroupSize,
        int trayCapacity,
        List<CubeCellData> cells)
    {
        LevelId = levelId ?? throw new ArgumentNullException(nameof(levelId));
        Width = width;
        Height = height;
        MaxStackHeight = maxStackHeight;
        MatchGroupSize = matchGroupSize;
        TrayCapacity = trayCapacity;
        Cells = cells ?? throw new ArgumentNullException(nameof(cells));
    }
}

public sealed class LevelVariationParams
{
    public string VariantLevelId { get; }
    public int TargetMaxStackHeight { get; }
    public int MaxDistinctColors { get; }
    public int Seed { get; }

    public LevelVariationParams(string variantLevelId, int targetMaxStackHeight, int maxDistinctColors, int seed)
    {
        VariantLevelId = variantLevelId ?? throw new ArgumentNullException(nameof(variantLevelId));
        TargetMaxStackHeight = targetMaxStackHeight;
        MaxDistinctColors = maxDistinctColors;
        Seed = seed;
    }
}

public sealed class LevelValidationReport
{
    public bool IsValid => Errors.Count == 0;
    public List<string> Errors { get; } = new List<string>();
    public List<string> Warnings { get; } = new List<string>();
    public int TotalCubes { get; set; }
    public int MaxObservedStackHeight { get; set; }
    public float EstimatedDifficultyScore { get; set; }
}

/// <summary>
/// Generates deterministic level variants from a base matrix by adjusting stack height,
/// color diversity, and seeded distribution while preserving MatchGroupSize divisibility.
/// </summary>
public sealed class ParametricLevelVariantGenerator
{
    public PuzzleLevelData GenerateVariant(PuzzleLevelData baseLevel, LevelVariationParams variation)
    {
        if (baseLevel == null) throw new ArgumentNullException(nameof(baseLevel));
        if (variation == null) throw new ArgumentNullException(nameof(variation));
        if (baseLevel.MatchGroupSize <= 0) throw new ArgumentOutOfRangeException(nameof(baseLevel.MatchGroupSize));
        if (variation.TargetMaxStackHeight <= 0) throw new ArgumentOutOfRangeException(nameof(variation.TargetMaxStackHeight));
        if (variation.MaxDistinctColors <= 0) throw new ArgumentOutOfRangeException(nameof(variation.MaxDistinctColors));

        var random = new System.Random(variation.Seed);
        var clonedCells = new List<CubeCellData>(baseLevel.Cells.Count);
        var colorPositions = new List<(int cellIndex, int stackIndex)>();

        for (int i = 0; i < baseLevel.Cells.Count; i++)
        {
            CubeCellData src = baseLevel.Cells[i];
            if (src == null)
            {
                continue;
            }

            if (src.Obstacle == ObstacleType.PermanentBlocker)
            {
                clonedCells.Add(new CubeCellData(src.X, src.Y, new List<int>(), src.Obstacle));
                continue;
            }

            // Clamp stack layers to the target MaxStackHeight
            int keptCount = Math.Min(src.StackColors.Count, variation.TargetMaxStackHeight);
            var trimmedStack = new List<int>(keptCount);
            for (int s = 0; s < keptCount; s++)
            {
                trimmedStack.Add(src.StackColors[s]);
                colorPositions.Add((clonedCells.Count, s));
            }

            clonedCells.Add(new CubeCellData(src.X, src.Y, trimmedStack, src.Obstacle));
        }

        // Trim any remainder cubes so total cube count stays strictly divisible by MatchGroupSize
        int groupSize = baseLevel.MatchGroupSize;
        int remainder = colorPositions.Count % groupSize;
        for (int r = 0; r < remainder; r++)
        {
            int removeIdx = colorPositions.Count - 1;
            var pos = colorPositions[removeIdx];
            clonedCells[pos.cellIndex].StackColors.RemoveAt(clonedCells[pos.cellIndex].StackColors.Count - 1);
            colorPositions.RemoveAt(removeIdx);
        }

        int totalValidCubes = colorPositions.Count;
        if (totalValidCubes == 0)
        {
            throw new InvalidOperationException("Not enough cubes remain to form at least one MatchGroupSize after trimming stack layers.");
        }

        // Rebalance colors in exact MatchGroupSize triplets and shuffle deterministically
        var balancedColors = new List<int>(totalValidCubes);
        int groupCount = totalValidCubes / groupSize;
        for (int g = 0; g < groupCount; g++)
        {
            int colorId = (g % variation.MaxDistinctColors) + 1;
            for (int k = 0; k < groupSize; k++)
            {
                balancedColors.Add(colorId);
            }
        }

        for (int i = balancedColors.Count - 1; i > 0; i--)
        {
            int swapIdx = random.Next(i + 1);
            (balancedColors[i], balancedColors[swapIdx]) = (balancedColors[swapIdx], balancedColors[i]);
        }

        for (int i = 0; i < colorPositions.Count; i++)
        {
            var pos = colorPositions[i];
            clonedCells[pos.cellIndex].StackColors[pos.stackIndex] = balancedColors[i];
        }

        return new PuzzleLevelData(
            variation.VariantLevelId,
            baseLevel.Width,
            baseLevel.Height,
            variation.TargetMaxStackHeight,
            baseLevel.MatchGroupSize,
            baseLevel.TrayCapacity,
            clonedCells);
    }
}

/// <summary>
/// 3-tier automated validator: Hard Errors for structural integrity, parity, and permanent locks;
/// Warnings when a single-pass greedy heuristic triggers tray overflow.
/// </summary>
public sealed class StackedCubeLevelValidator
{
    private static readonly int[] Dx = { 1, -1, 0, 0 };
    private static readonly int[] Dy = { 0, 0, 1, -1 };

    public LevelValidationReport Validate(PuzzleLevelData level)
    {
        if (level == null)
        {
            throw new ArgumentNullException(nameof(level));
        }

        var report = new LevelValidationReport();

        // Tier 1: Structural bounds and MaxStackHeight checks
        if (level.Width <= 0 || level.Height <= 0 || level.MatchGroupSize <= 0 || level.TrayCapacity < level.MatchGroupSize)
        {
            report.Errors.Add("Invalid grid dimensions, MatchGroupSize, or TrayCapacity.");
            return report;
        }

        var occupiedCoords = new HashSet<(int x, int y)>();
        var colorCounts = new Dictionary<int, int>();

        for (int i = 0; i < level.Cells.Count; i++)
        {
            CubeCellData cell = level.Cells[i];
            if (cell == null)
            {
                report.Errors.Add($"Cell at index {i} is null.");
                continue;
            }

            if (cell.X < 0 || cell.X >= level.Width || cell.Y < 0 || cell.Y >= level.Height)
            {
                report.Errors.Add($"Cell ({cell.X},{cell.Y}) is out of grid bounds {level.Width}x{level.Height}.");
            }

            if (!occupiedCoords.Add((cell.X, cell.Y)))
            {
                report.Errors.Add($"Duplicate cell coordinates at ({cell.X},{cell.Y}).");
            }

            if (cell.Obstacle == ObstacleType.PermanentBlocker && cell.StackColors.Count > 0)
            {
                report.Errors.Add($"PermanentBlocker cell ({cell.X},{cell.Y}) cannot contain cubes.");
            }

            if (cell.StackColors.Count > level.MaxStackHeight)
            {
                report.Errors.Add($"Cell ({cell.X},{cell.Y}) stack height {cell.StackColors.Count} exceeds MaxStackHeight ({level.MaxStackHeight}).");
            }

            if (cell.StackColors.Count > report.MaxObservedStackHeight)
            {
                report.MaxObservedStackHeight = cell.StackColors.Count;
            }

            for (int s = 0; s < cell.StackColors.Count; s++)
            {
                int color = cell.StackColors[s];
                if (color <= 0)
                {
                    report.Errors.Add($"Cube color ID at ({cell.X},{cell.Y}) layer {s} must be positive.");
                    continue;
                }

                colorCounts.TryGetValue(color, out int currentCount);
                colorCounts[color] = currentCount + 1;
                report.TotalCubes++;
            }
        }

        if (report.TotalCubes == 0)
        {
            report.Errors.Add("Level contains zero cubes.");
            return report;
        }

        // Tier 2: Color parity check against MatchGroupSize
        foreach (KeyValuePair<int, int> kv in colorCounts)
        {
            if (kv.Value % level.MatchGroupSize != 0)
            {
                report.Errors.Add($"Color {kv.Key} has {kv.Value} cubes, which is not divisible by MatchGroupSize ({level.MatchGroupSize}) - Unsolvable.");
            }
        }

        // Tier 3: Heuristic solvability simulation (separating permanent obstacle locks from greedy tray overflow warnings)
        if (report.Errors.Count == 0)
        {
            SimulateGreedyClear(level, report);
        }

        report.EstimatedDifficultyScore = report.MaxObservedStackHeight * 1.5f + colorCounts.Count * 1.2f;
        return report;
    }

    private static void SimulateGreedyClear(PuzzleLevelData level, LevelValidationReport report)
    {
        var stacks = new List<List<int>>(level.Cells.Count);
        var cellMap = new Dictionary<(int x, int y), int>(level.Cells.Count);
        int remainingCubes = 0;

        for (int i = 0; i < level.Cells.Count; i++)
        {
            CubeCellData c = level.Cells[i];
            stacks.Add(new List<int>(c.StackColors));
            cellMap[(c.X, c.Y)] = i;
            remainingCubes += c.StackColors.Count;
        }

        var tray = new Dictionary<int, int>();
        int totalInTray = 0;
        int safetySteps = remainingCubes * 2 + 10;

        while (remainingCubes > 0 && safetySteps-- > 0)
        {
            int bestCellIdx = -1;
            int bestScore = int.MinValue;

            for (int i = 0; i < level.Cells.Count; i++)
            {
                List<int> stack = stacks[i];
                if (stack.Count == 0) continue;

                if (level.Cells[i].Obstacle == ObstacleType.LockedUntilAdjacentCleared &&
                    !HasClearedAdjacentCell(level.Cells[i], level.Cells, stacks, cellMap))
                {
                    continue;
                }

                int topColor = stack[stack.Count - 1];
                tray.TryGetValue(topColor, out int inTrayCount);

                int score = (inTrayCount == level.MatchGroupSize - 1) ? 100 : (inTrayCount > 0 ? 20 + inTrayCount : 1);
                if (score > bestScore)
                {
                    bestScore = score;
                    bestCellIdx = i;
                }
            }

            if (bestCellIdx == -1)
            {
                report.Errors.Add("Deadlock detected: No valid accessible cell remains (permanent obstacle lock).");
                return;
            }

            List<int> chosenStack = stacks[bestCellIdx];
            int pickedColor = chosenStack[chosenStack.Count - 1];
            chosenStack.RemoveAt(chosenStack.Count - 1);
            remainingCubes--;

            tray.TryGetValue(pickedColor, out int count);
            count++;
            totalInTray++;

            if (count >= level.MatchGroupSize)
            {
                int left = count - level.MatchGroupSize;
                totalInTray -= level.MatchGroupSize;
                if (left == 0) tray.Remove(pickedColor);
                else tray[pickedColor] = left;
            }
            else
            {
                tray[pickedColor] = count;
            }

            if (totalInTray >= level.TrayCapacity && remainingCubes > 0)
            {
                // Single-pass greedy without backtracking can false-positive on hard boards -> emit Warning
                report.Warnings.Add($"Deadlock Warning (Heuristic): Tray overflowed at {totalInTray}/{level.TrayCapacity} slots during greedy simulation.");
                return;
            }
        }

        if (remainingCubes > 0)
        {
            report.Warnings.Add("Simulation Warning: Exceeded maximum safe simulation steps.");
        }
    }

    private static bool HasClearedAdjacentCell(
        CubeCellData target,
        List<CubeCellData> cells,
        List<List<int>> stacks,
        Dictionary<(int x, int y), int> cellMap)
    {
        for (int d = 0; d < 4; d++)
        {
            if (cellMap.TryGetValue((target.X + Dx[d], target.Y + Dy[d]), out int neighborIdx))
            {
                if (cells[neighborIdx].Obstacle != ObstacleType.PermanentBlocker && stacks[neighborIdx].Count == 0)
                {
                    return true;
                }
            }
        }

        return false;
    }
}

[TestFixture]
public sealed class PuzzleLevelPipelineTests
{
    private static PuzzleLevelData CreateSampleStackedBaseLevel(int maxStackHeight)
    {
        var cells = new List<CubeCellData>();
        // 3x2 matrix, 4 cube layers per cell (24 cubes total -> divisible by 3)
        int colorToggle = 0;
        for (int y = 0; y < 2; y++)
        {
            for (int x = 0; x < 3; x++)
            {
                var stack = new List<int>();
                for (int h = 0; h < 4; h++)
                {
                    stack.Add((colorToggle % 4) + 1);
                    colorToggle++;
                }
                cells.Add(new CubeCellData(x, y, stack));
            }
        }

        return new PuzzleLevelData("Level_Base", 3, 2, maxStackHeight, matchGroupSize: 3, trayCapacity: 7, cells);
    }

    [Test]
    public void ParametricVariantGenerator_ProducesValidEasyAndHardVariants_FromSingleBaseLayout()
    {
        PuzzleLevelData baseLevel = CreateSampleStackedBaseLevel(maxStackHeight: 4);
        var generator = new ParametricLevelVariantGenerator();
        var validator = new StackedCubeLevelValidator();

        // Easy variant: cap MaxStackHeight at 2 and reduce to 2 distinct colors
        var easyVariant = generator.GenerateVariant(
            baseLevel,
            new LevelVariationParams("Level_002_Easy", targetMaxStackHeight: 2, maxDistinctColors: 2, seed: 42));

        // Hard variant: keep MaxStackHeight at 4 and expand to 4 distinct colors
        var hardVariant = generator.GenerateVariant(
            baseLevel,
            new LevelVariationParams("Level_099_Hard", targetMaxStackHeight: 4, maxDistinctColors: 4, seed: 42));

        LevelValidationReport easyReport = validator.Validate(easyVariant);
        LevelValidationReport hardReport = validator.Validate(hardVariant);

        Assert.IsTrue(easyReport.IsValid, string.Join(" | ", easyReport.Errors));
        Assert.IsTrue(hardReport.IsValid, string.Join(" | ", hardReport.Errors));
        Assert.AreEqual(2, easyReport.MaxObservedStackHeight);
        Assert.AreEqual(4, hardReport.MaxObservedStackHeight);
        Assert.IsTrue(hardReport.EstimatedDifficultyScore > easyReport.EstimatedDifficultyScore);
    }

    [Test]
    public void Validator_DetectsOddColorParity_AsUnsolvableLevel()
    {
        var cells = new List<CubeCellData>
        {
            // Color 1 has 4 cubes, Color 2 has 2 cubes -> neither is divisible by MatchGroupSize = 3
            new CubeCellData(0, 0, new List<int> { 1, 1, 2 }),
            new CubeCellData(1, 0, new List<int> { 1, 1, 2 })
        };

        var brokenLevel = new PuzzleLevelData("Broken_Parity", 2, 1, 3, matchGroupSize: 3, trayCapacity: 7, cells);
        var validator = new StackedCubeLevelValidator();

        LevelValidationReport report = validator.Validate(brokenLevel);

        Assert.IsFalse(report.IsValid);
        Assert.IsTrue(report.Errors.Exists(e => e.Contains("MatchGroupSize")));
    }

    [Test]
    public void Validator_DetectsPermanentLockDeadlock_AsHardError()
    {
        var cells = new List<CubeCellData>
        {
            // Both cells are locked waiting for an empty neighbor, leaving no valid opening move
            new CubeCellData(0, 0, new List<int> { 1, 1, 1 }, ObstacleType.LockedUntilAdjacentCleared),
            new CubeCellData(1, 0, new List<int> { 2, 2, 2 }, ObstacleType.LockedUntilAdjacentCleared)
        };

        var deadlockedLevel = new PuzzleLevelData("Locked_Deadlock", 2, 1, 3, matchGroupSize: 3, trayCapacity: 7, cells);
        var validator = new StackedCubeLevelValidator();

        LevelValidationReport report = validator.Validate(deadlockedLevel);

        Assert.IsFalse(report.IsValid);
        Assert.IsTrue(report.Errors.Exists(e => e.Contains("Deadlock")));
    }

    [Test]
    public void Validator_FlagsGreedyTrayOverflow_AsWarningInsteadOfHardError()
    {
        // Balanced parity (3 cubes each for colors 1, 2, 3), but TrayCapacity = 3 and mismatched exposed top cubes
        var cells = new List<CubeCellData>
        {
            new CubeCellData(0, 0, new List<int> { 1, 1, 2 }),
            new CubeCellData(1, 0, new List<int> { 2, 2, 3 }),
            new CubeCellData(2, 0, new List<int> { 3, 3, 1 })
        };

        var tightTrayLevel = new PuzzleLevelData("Tight_Tray", 3, 1, 3, matchGroupSize: 3, trayCapacity: 3, cells);
        var validator = new StackedCubeLevelValidator();

        LevelValidationReport report = validator.Validate(tightTrayLevel);

        Assert.IsTrue(report.IsValid);
        Assert.AreEqual(0, report.Errors.Count);
        Assert.IsTrue(report.Warnings.Exists(w => w.Contains("Heuristic")));
    }

    [Test]
    public void Validator_RejectsStackHeightOverflow_AndOutOfBoundsCoordinates()
    {
        var cells = new List<CubeCellData>
        {
            new CubeCellData(0, 0, new List<int> { 1, 1, 1, 1 }), // 4 > MaxStackHeight (2)
            new CubeCellData(5, 0, new List<int> { 2, 2 })        // X=5 exceeds Width=2
        };

        var invalidStructure = new PuzzleLevelData("Invalid_Struct", 2, 1, maxStackHeight: 2, matchGroupSize: 3, trayCapacity: 7, cells);
        var validator = new StackedCubeLevelValidator();

        LevelValidationReport report = validator.Validate(invalidStructure);

        Assert.IsFalse(report.IsValid);
        Assert.IsTrue(report.Errors.Exists(e => e.Contains("MaxStackHeight")));
        Assert.IsTrue(report.Errors.Exists(e => e.Contains("out of grid bounds")));
    }

    [Test]
    public void Pipeline_WithNullOrInvalidBoundaryInputs_ThrowsExpectedExceptions()
    {
        var validator = new StackedCubeLevelValidator();
        var generator = new ParametricLevelVariantGenerator();

        Assert.Throws<ArgumentNullException>(() => validator.Validate(null));
        Assert.Throws<ArgumentNullException>(() => generator.GenerateVariant(null, new LevelVariationParams("v1", 2, 2, 1)));
        Assert.Throws<ArgumentNullException>(() => generator.GenerateVariant(CreateSampleStackedBaseLevel(4), null));

        // Boundary case: invalid MatchGroupSize <= 0 or trimming below one full MatchGroupSize
        var invalidRuleLevel = new PuzzleLevelData("Bad_Rule", 1, 1, 2, matchGroupSize: 0, trayCapacity: 7, new List<CubeCellData>
        {
            new CubeCellData(0, 0, new List<int> { 1, 2 })
        });
        Assert.Throws<ArgumentOutOfRangeException>(() => generator.GenerateVariant(invalidRuleLevel, new LevelVariationParams("v_bad", 1, 2, 1)));

        var tinyGrid = new PuzzleLevelData("Tiny", 2, 1, 2, matchGroupSize: 3, trayCapacity: 7, new List<CubeCellData>
        {
            new CubeCellData(0, 0, new List<int> { 1, 1 }),
            new CubeCellData(1, 0, new List<int> { 1 })
        });
        Assert.Throws<InvalidOperationException>(() => generator.GenerateVariant(tinyGrid, new LevelVariationParams("v_empty", targetMaxStackHeight: 1, maxDistinctColors: 1, seed: 1)));
    }
}

5. Engineering Trade-offs Across Level Production Approaches

Under a tight 500-level deadline, picking the wrong authoring workflow compounds technical debt across the entire project. Below is how the three common approaches compare:

Comparison Dimension100% Manual Scenes / PrefabsPure Unconstrained PCGData-Driven + Parametric Variation + Validator
Time to 500 LevelsVery slow; bound strictly by manual Dev and Designer hoursInstant (seconds), but requires heavy post-filteringFast: expands dozens of curated base layouts into hundreds of controlled stages
Pacing & Level QualityHigh if crafted carefully, degrades rapidly under crunchLow: feels noisy with erratic difficulty spikesConsistent: preserves designer intent while flexing difficulty per knob
Deadlock / Broken Level RiskHigh without manual QA across all 500 levelsVery high unless paired with a heavy solverLow: structural, parity, and deadlock failures are caught automatically on save
Team BottleneckEngineers dragged into manual level assemblyEngineers stuck tuning complex generation heuristicsEngineers invest upfront in pipeline; Designers own content production
Binary Footprint & Git MergeHeavy binary bloat; frequent .unity and .prefab merge conflictsMinimal (seed-only), but hard to hand-edit individual levelsLean (compact JSON/DTO), clean Git diffs, and remote Live-ops ready

6. Production Takeaways

Scaling a puzzle game to hundreds of levels in a week is not solved by brute-force overtime, but by investing in the underlying content architecture:

  1. Levels are Data, not Scenes: Decouple matrix geometry, stack depths, obstacles, and win rules completely from .unity Scene files so the gameplay engine simply consumes and executes data.
  2. Eliminate the Dev Bottleneck with Tooling and Validators: Equip Game Designers with visual Editor tools to create, preview, and edit levels independently, backed by an Automated Validator covering structure, parity, and deadlock simulation.
  3. Leverage Parametric Variation on Curated Templates: Adjusting purposeful parameters such as MaxStackHeight, color diversity, and obstacle distribution across well-designed base layouts strikes the right balance between rapid content scale and handcrafted puzzle feel.

Share this post:
Lương Bảo Toàn

Luong Bao Toan

I work in HMI Automotive and Game development, sharing knowledge, hands-on experience, and stories I find interesting throughout my journey.

Did this article bring you value?

If this article helped your work, or you simply enjoyed it and want to support me, you can

Buy me a coffee

Related Articles

Comments & Discussions

Powered by Giscus

Get New Posts via Email

Subscribe to stay updated and never miss new posts from me.

* No spam. You can unsubscribe at any time with a single click.