Skip to content

Headless Puzzle

Headbreaker provides a Puzzle object which allows you to fully manipulate its model and individual Pieces. Since Puzzles are not coupled to any visual representation, they can be loaded in headless environments like a Node.js server.

// ES module import
import { Puzzle, Tab, Slot, vector } from 'headbreaker-ts';
// Or CommonJS
// const { Puzzle, Tab, Slot, vector } = require('headbreaker-ts');
// Create a puzzle
const puzzle = new Puzzle();
puzzle
.newPiece({right: Tab})
.locateAt(0, 0);
puzzle
.newPiece({left: Slot, right: Tab})
.locateAt(3, 0);
puzzle
.newPiece({left: Slot, right: Tab, down: Slot})
.locateAt(6, 0);
puzzle
.newPiece({up: Tab})
.locateAt(6, 3);
// Connect puzzle's nearby pieces
puzzle.autoconnect();
// Translate puzzle
puzzle.translate(10, 10);
// Shuffle pieces
puzzle.shuffle(100, 100);
// Relocate pieces to fit into a bounding box
// while preserving their relative positions, if possible
puzzle.reframe(vector(0, 0), vector(20, 20));
// Directly manipulate pieces
const [a, b, c, d] = puzzle.pieces;
// Drag a piece 10 steps right and 5 steps down
a.drag(10, 5);
// Connect two pieces (if possible)
a.tryConnectWith(b);
// Add custom metadata to pieces
a.metadata.flavour = "chocolate";
a.metadata.sugar = true;
b.metadata.flavour = "chocolate";
b.metadata.sugar = false;
c.metadata.flavour = "vainilla";
c.metadata.sugar = false;
d.metadata.flavour = "vainilla";
d.metadata.sugar = true;
// Require pieces to match a given condition in
// order to be connected
puzzle.attachConnectionRequirement(
(one, other) => one.metadata.flavour === other.metadata.flavour
);
// Alternatively, set individual requirements for horizontal
// and vertical connections
puzzle.attachVerticalConnectionRequirement(
(one, other) => one.metadata.flavour === other.metadata.flavour
);
puzzle.attachHorizontalConnectionRequirement(
(one, other) => one.metadata.sugar !== other.metadata.sugar
);
// Remove all connection requirements
puzzle.clearConnectionRequirements();
// Export and import puzzle
const dump = puzzle.export();
const otherPuzzle = Puzzle.import(dump);