The second add-on for BlockCraft, my Minecraft-style game for the kids’ Fire tablets (the first was airplanes and helicopters). The kids asked for different kinds of castles with different treasure: diamonds, gold, silver, jewels, apples and other fruit, healing and power-up potions, diamond pickaxes and swords, and diamond shoes. All of it is now in the game, mostly to be found or earned. This post covers what the add-on does and how to add it to an existing BlockCraft. Every block has a Copy button.
What it adds
Five kinds of castles to explore
Castles are part of the land, like trees and ore, so every world has them, old worlds too (in land nobody has changed yet). Walking through the gate says “You found a Desert Palace!” Each castle has a golden treasure chest in the keep (the house in the middle), filled the first time anyone opens it. Rarer castles hold better treasure.
| Castle | Where | Looks like | Treasure |
|---|---|---|---|
| Wooden Fort | grassland and forest | log and plank walls, green flags | apples and other fruit, iron, torches, arrows, a healing potion, sometimes iron boots or silver |
| Stone Castle (the original) | grassland and forest, the most common | stone bricks and mossy bricks, red flags | diamonds, iron, gold, apples, torches, arrows, maybe a diamond sword or a diamond block, now also silver and a healing potion |
| Royal Castle (rare) | grassland and forest | stone bricks with gold battlements, purple flags | the best: 8 to 14 diamonds, every kind of jewel, golden apples, strength, shield, regeneration and healing potions, a diamond pickaxe or diamond sword, a diamond armor piece and a diamond block |
| Desert Palace | deserts | sandstone with gold battlements, orange flags | gold, silver, rubies, emeralds, oranges, bananas, grapes, a speed potion, healing potions, maybe a golden apple, a gold armor piece |
| Ice Castle | snowy land | ice bricks and snow with silver battlements, blue flags | diamonds, sapphires, amethysts, silver, watermelon, water breathing and night vision potions, often diamond boots |
The Stone Castles that were already in the family world are exactly where they were, and look the same (only their chest now has the golden treasure chest look). The new kinds show up in places that had no castle before.
Castle kits: earn your own castle
Make a kit at a crafting table in Survival, hold it and tap: the whole castle builds itself just in front of you (its gate faces north). It belongs to you: in the family world it flies a flag in your own colour (the same colour as your airplane) and has your name floating over it (“Layla’s Royal Castle”). Nobody else can break or add blocks in it or open its treasure chest; they can still open and close the doors to visit. Explosions can’t damage it either. Its treasure chest starts empty: it is yours to fill. Castles can’t be built right next to someone else’s.
| Kit | Made from |
|---|---|
| Wooden Fort Kit | 40 logs, 4 glass, 8 torches |
| Stone Castle Kit | 64 stone bricks, 16 glass, 4 iron ingots |
| Desert Palace Kit | 64 sandstone, 4 gold blocks, 8 glass |
| Ice Castle Kit | 64 glass, 4 sapphires, 16 silver ingots |
| Royal Castle Kit | 64 stone bricks, 8 gold blocks, 2 diamond blocks, 4 rubies |
A kit castle has no gold or silver battlements, so it can’t be mined for more than it cost.
Treasure
- Silver: silver ore deep underground (below height 30, needs an iron pickaxe). Smelt it into silver ingots. 9 silver ingots make a silver block, and 9 gold ingots make a gold block.
- Jewels: ruby, emerald, sapphire and amethyst. Find them in treasure chests, or dig jewel ore very deep (below height 14, needs an iron pickaxe), which drops one jewel at random.
- Fruit: apples, pears, cherries and grapes sometimes drop from leaves; oranges, bananas and watermelon come from treasure chests. A golden apple (1 apple + 8 gold ingots) fills you up, heals 3 hearts and gives 10 seconds of regeneration.
- Silver Sword (2 silver ingots and a stick): a bit weaker than diamond, but does double damage to zombies and skeletons.
Potions
Make a glass bottle (3 from 1 glass), then mix it with something special at a crafting table. Tap a potion to drink it; you get the bottle back. Running potions are listed in pink in the top-left corner with the seconds left.
| Potion | Made from bottle + | What it does |
|---|---|---|
| Healing | 2 apples | +4 hearts straight away |
| Regeneration | 1 golden apple | heals over 30 seconds |
| Strength | 1 ruby | your hits do double damage for 90 seconds |
| Speed | 1 sapphire | run 60% faster for 90 seconds |
| Jump | 1 emerald | jump much higher, and longer falls don’t hurt, for 90 seconds |
| Shield | 1 amethyst + 1 iron ingot | monsters hurt you half as much for 90 seconds |
| Night Vision | 1 glowstone | caves and nights look lit up for 2 minutes |
| Water Breathing | 2 grapes | no drowning for 2 minutes |
Armor
Iron, gold and diamond helmets, chestplates, leggings and boots, made at a crafting table (5, 8, 7 and 4 of the metal). Tap armor to put it on, or open the bag: the new WEARING row shows the four pieces; tap a piece in the bag and then a WEARING slot to put it on, and tap a worn piece to take it off. Blue diamonds next to the hearts show how protected you are, and the bag says how much less monsters hurt you. Armor helps against monsters, arrows and explosions: a full diamond set stops 80%. Diamond Boots also mean no fall damage at all.
Earned, not free
Jewels, potions, golden apples, diamond armor, castle kits and the treasure chest block are left out of the Creative block list, like the airplanes, so they have to be found in castles or crafted in Survival.
How it works
- The castle types are a table in the shared game rules (
engine.js): which blocks make the walls, floors, walkways and roofs, the flag colour and (for natural castles only) the gold or silver battlements. Which castle appears where comes from the same seed-based luck as before, so the original Stone Castles keep their exact spots, and the new kinds use regions that had no castle. - Each castle type has its own treasure list. The amounts come from the seed too, so the same castle always holds the same treasure, and it is put in the chest the first time anyone opens it.
- A castle kit sends one message (
kit) to the server (or, in single player, the page’s own simulation). The server builds the castle block by block exactly like a natural one, notes who owns it, and tells everyone. From then on it refuses block changes, chest opening and explosions inside that castle from anyone but the owner, and puts back any block a tablet tried to change. Kit castles are saved in theownedlist of/opt/blockcraft/data/world.json. - Potions, golden apples and armor run on each tablet (that is where health is kept). Armor and the shield potion shrink the damage the server sends for monster hits, arrows and explosions. The night vision potion raises the darkest light level the 3D drawing uses. Worn armor is saved with each player’s bag.
Containers involved
| Container | Role | LAN IP |
|---|---|---|
| CT 127 (blockcraft) | Node.js game server; gets the new game files | x.x.0.193 (DHCP) |
| CT 108 (Caddy reverse proxy) | Unchanged: already routes /blockcraft* to CT 127 |
x.x.0.122 |
No new container, port, DNS name or Caddy route is needed.
Where to run each command
- Proxmox host shell: in the Proxmox web UI click pve → Shell (or SSH to the host as root).
- Everything below is run there.
Add it to an existing BlockCraft
This assumes BlockCraft is already built from the main BlockCraft post, with its files in /root/blockcraft/ on the host and 04-push.sh there. The files below also contain the airplanes and helicopters add-on, so this brings a BlockCraft without either add-on fully up to date. If you are building BlockCraft from scratch, the main post already has these same files, so you can skip this section.
1. Go to the working folder
cd /root/blockcraft
2. Replace the five changed files
Paste each block into the Proxmox host shell. Each one overwrites one file in /root/blockcraft/. The game files are long; let each paste finish before the next.
engine.js: the shared game rules. New: silver ore, jewel ore, gold and silver blocks, ice bricks, the treasure chest, all the new items and recipes, the five castle types and their treasure, castle kits and owned-castle protection.
cat > /root/blockcraft/engine.js <<'EOF'
// BlockCraft shared engine: blocks, items, recipes, world generation, physics and the
// game simulation (mobs, arrows, explosions, chests, time of day). The same file runs in the
// browser (single-player runs the simulation in the page) and in Node on CT 127 (multiplayer).
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory();
else root.BC = factory();
})(typeof self !== 'undefined' ? self : this, function () {
'use strict';
const CS = 16, CH = 64, SEA = 24, DAY_SECONDS = 600;
// ---------------------------------------------------------------- textures (drawn by the client)
const TILES = ('grass_top grass_side dirt stone cobble planks log_side log_top leaves sand gravel water glass ' +
'coal_ore iron_ore gold_ore diamond_ore bedrock snow snow_side cactus_side cactus_top table_top table_side ' +
'table_front furnace_front furnace_side furnace_top chest_front chest_side chest_top torch door_bottom door_top ' +
'bed_top bed_side tnt_side tnt_top tnt_bottom bricks stone_bricks bookshelf flower_red flower_yellow tall_grass ' +
'wool_white wool_red wool_orange wool_yellow wool_lime wool_blue wool_purple wool_black wool_pink glowstone ' +
'sandstone_side sandstone_top slab_side slab_top snow_block ladder ' +
'zombie_face zombie_skin zombie_shirt zombie_pants skeleton_face bone creeper_face creeper_skin spider_face ' +
'spider_body pig_face pig_skin cow_face cow_skin sheep_face sheep_wool player_face player_hair player_skin ' +
'player_shirt player_pants arrow_tex tnt_lit diamond_block mossy_bricks trex_skin trex_face raptor_skin raptor_face ' +
'trike_skin trike_face brachio_skin brachio_face paint0 paint1 paint2 paint3 paint4 paint5 paint6 paint7 plane_wing metal cockpit rotor ' +
'silver_ore gem_ore gold_block silver_block ice_bricks treasure_front treasure_side treasure_top ' +
'stairs_down stairs_up stairs_side cat_skin cat_face dog_skin dog_face ' +
'story_top story_side gate thorns golden_ball straw_top straw_side wheel ginger icing candy pebbles rose slipper ' +
'quilt quilt_side shoes basket musicians braid bird frog portal home_top goat mother_goat goose dshoes snail leaves_silver leaves_gold leaves_diamond ' +
'trampoline trampoline_side slide swing merry_top merry_side heart_block heart_front heart_top wolf_skin wolf_face').split(' ');
const T = {}; TILES.forEach((n, i) => { T[n] = i; });
// ---------------------------------------------------------------- blocks
// shape: cube | cross | torch | door | slab | bed | cactus | water | ladder
// tex: [top, bottom, side] or [top, bottom, north, south, east, west]
const BLOCKS = [];
function B(id, name, o) {
const d = Object.assign({ id, name, solid: true, opaque: true, shape: 'cube', hard: 1, tool: '', lvl: 0,
drop: id, cutout: false, light: 0, h: 1, stack: 64, color: '#888' }, o);
if (d.tex && d.tex.length === 1) d.tex = [d.tex[0], d.tex[0], d.tex[0]];
BLOCKS[id] = d; return d;
}
const t = n => T[n];
B(0, 'Air', { solid: false, opaque: false, shape: 'none', drop: 0 });
B(1, 'Grass Block', { tex: [t('grass_top'), t('dirt'), t('grass_side')], hard: 0.6, tool: 'shovel', drop: 2, color: '#5d9c3a' });
B(2, 'Dirt', { tex: [t('dirt')], hard: 0.5, tool: 'shovel', color: '#86603f' });
B(3, 'Stone', { tex: [t('stone')], hard: 1.5, tool: 'pick', lvl: 1, drop: 4, color: '#7d7d7d' });
B(4, 'Cobblestone', { tex: [t('cobble')], hard: 2, tool: 'pick', lvl: 1, color: '#6e6e6e' });
B(5, 'Planks', { tex: [t('planks')], hard: 2, tool: 'axe', color: '#a8844f' });
B(6, 'Log', { tex: [t('log_top'), t('log_top'), t('log_side')], hard: 2, tool: 'axe', color: '#6b5130' });
B(7, 'Leaves', { tex: [t('leaves')], hard: 0.2, opaque: false, cutout: true, drop: -1, color: '#3d7a26' });
B(8, 'Sand', { tex: [t('sand')], hard: 0.5, tool: 'shovel', color: '#dccf9a' });
B(9, 'Gravel', { tex: [t('gravel')], hard: 0.6, tool: 'shovel', color: '#8a8380' });
B(10, 'Water', { tex: [t('water')], solid: false, opaque: false, shape: 'water', hard: -1, drop: 0, color: '#3f6fd8' });
B(11, 'Glass', { tex: [t('glass')], hard: 0.3, opaque: false, cutout: true, drop: 0, color: '#c8e4ec' });
B(12, 'Coal Ore', { tex: [t('coal_ore')], hard: 3, tool: 'pick', lvl: 1, drop: 101, color: '#5f5f5f' });
B(13, 'Iron Ore', { tex: [t('iron_ore')], hard: 3, tool: 'pick', lvl: 2, color: '#8f7d6e' });
B(14, 'Gold Ore', { tex: [t('gold_ore')], hard: 3, tool: 'pick', lvl: 3, color: '#a39461' });
B(15, 'Diamond Ore', { tex: [t('diamond_ore')], hard: 3, tool: 'pick', lvl: 3, drop: 104, color: '#6fa4a6' });
B(16, 'Bedrock', { tex: [t('bedrock')], hard: -1, drop: 0, color: '#333' });
B(17, 'Snowy Grass', { tex: [t('snow'), t('dirt'), t('snow_side')], hard: 0.6, tool: 'shovel', drop: 2, color: '#f0f4f4' });
B(18, 'Cactus', { tex: [t('cactus_top'), t('cactus_top'), t('cactus_side')], hard: 0.4, opaque: false, shape: 'cactus', color: '#3f7f2a' });
B(19, 'Crafting Table', { tex: [t('table_top'), t('planks'), t('table_front'), t('table_side'), t('table_front'), t('table_side')], hard: 2.5, tool: 'axe', color: '#9a6e3e' });
B(20, 'Furnace', { tex: [t('furnace_top'), t('furnace_top'), t('furnace_front'), t('furnace_side'), t('furnace_side'), t('furnace_side')], hard: 3.5, tool: 'pick', lvl: 1, color: '#5a5a5a' });
B(21, 'Chest', { tex: [t('chest_top'), t('chest_top'), t('chest_front'), t('chest_side'), t('chest_side'), t('chest_side')], hard: 2.5, tool: 'axe', color: '#a2702d' });
B(22, 'Torch', { tex: [t('torch')], solid: false, opaque: false, shape: 'torch', hard: 0, light: 1, cutout: true, color: '#ffd84a' });
// doors: 23-26 closed (X = panel along x, Z = panel along z; bottom/top), 27-30 open
B(23, 'Door', { tex: [t('door_bottom')], opaque: false, shape: 'door', axis: 'x', half: 0, open: false, hard: 3, tool: 'axe', drop: 115, cutout: true, color: '#8a6234' });
B(24, 'Door', { tex: [t('door_top')], opaque: false, shape: 'door', axis: 'x', half: 1, open: false, hard: 3, tool: 'axe', drop: 0, cutout: true, color: '#8a6234' });
B(25, 'Door', { tex: [t('door_bottom')], opaque: false, shape: 'door', axis: 'z', half: 0, open: false, hard: 3, tool: 'axe', drop: 115, cutout: true, color: '#8a6234' });
B(26, 'Door', { tex: [t('door_top')], opaque: false, shape: 'door', axis: 'z', half: 1, open: false, hard: 3, tool: 'axe', drop: 0, cutout: true, color: '#8a6234' });
B(27, 'Door', { tex: [t('door_bottom')], solid: false, opaque: false, shape: 'door', axis: 'x', half: 0, open: true, hard: 3, tool: 'axe', drop: 115, cutout: true, color: '#8a6234' });
B(28, 'Door', { tex: [t('door_top')], solid: false, opaque: false, shape: 'door', axis: 'x', half: 1, open: true, hard: 3, tool: 'axe', drop: 0, cutout: true, color: '#8a6234' });
B(29, 'Door', { tex: [t('door_bottom')], solid: false, opaque: false, shape: 'door', axis: 'z', half: 0, open: true, hard: 3, tool: 'axe', drop: 115, cutout: true, color: '#8a6234' });
B(30, 'Door', { tex: [t('door_top')], solid: false, opaque: false, shape: 'door', axis: 'z', half: 1, open: true, hard: 3, tool: 'axe', drop: 0, cutout: true, color: '#8a6234' });
B(31, 'Bed', { tex: [t('bed_top'), t('planks'), t('bed_side')], opaque: false, shape: 'bed', h: 0.5625, hard: 0.2, color: '#c43a3a' });
B(32, 'TNT', { tex: [t('tnt_top'), t('tnt_bottom'), t('tnt_side')], hard: 0, color: '#d44030' });
B(33, 'Bricks', { tex: [t('bricks')], hard: 2, tool: 'pick', lvl: 1, color: '#975a49' });
B(34, 'Stone Bricks', { tex: [t('stone_bricks')], hard: 1.5, tool: 'pick', lvl: 1, color: '#7a7a7a' });
B(35, 'Bookshelf', { tex: [t('planks'), t('planks'), t('bookshelf')], hard: 1.5, tool: 'axe', color: '#7d5a3a' });
B(36, 'Red Flower', { tex: [t('flower_red')], solid: false, opaque: false, shape: 'cross', hard: 0, cutout: true, color: '#d22' });
B(37, 'Yellow Flower', { tex: [t('flower_yellow')], solid: false, opaque: false, shape: 'cross', hard: 0, cutout: true, color: '#ee2' });
B(38, 'Tall Grass', { tex: [t('tall_grass')], solid: false, opaque: false, shape: 'cross', hard: 0, cutout: true, drop: 0, color: '#5d9c3a' });
const WOOL = [['White', 'wool_white', '#e8e8e8'], ['Red', 'wool_red', '#b02e26'], ['Orange', 'wool_orange', '#f07d19'],
['Yellow', 'wool_yellow', '#f8c627'], ['Lime', 'wool_lime', '#70b919'], ['Blue', 'wool_blue', '#3c44aa'],
['Purple', 'wool_purple', '#8932b8'], ['Black', 'wool_black', '#1d1d21'], ['Pink', 'wool_pink', '#f38baa']];
WOOL.forEach((w, i) => B(39 + i, w[0] + ' Wool', { tex: [t(w[1])], hard: 0.8, color: w[2] }));
B(48, 'Stone Slab', { tex: [t('slab_top'), t('slab_top'), t('slab_side')], opaque: false, shape: 'slab', h: 0.5, hard: 2, tool: 'pick', lvl: 1, color: '#a0a0a0' });
B(49, 'Glowstone', { tex: [t('glowstone')], hard: 0.3, light: 1, color: '#f4d27a' });
B(50, 'Sandstone', { tex: [t('sandstone_top'), t('sandstone_top'), t('sandstone_side')], hard: 0.8, tool: 'pick', lvl: 1, color: '#d8c98e' });
B(51, 'Snow Block', { tex: [t('snow_block')], hard: 0.2, tool: 'shovel', color: '#f6fafa' });
B(52, 'Ladder', { tex: [t('ladder')], solid: false, opaque: false, shape: 'ladder', hard: 0.4, tool: 'axe', cutout: true, color: '#9a7a48' });
B(53, 'Diamond Block', { tex: [t('diamond_block')], hard: 5, tool: 'pick', lvl: 3, color: '#5decf5' });
B(54, 'Mossy Stone Bricks', { tex: [t('mossy_bricks')], hard: 1.5, tool: 'pick', lvl: 1, color: '#6f7a62' });
B(55, 'Silver Ore', { tex: [t('silver_ore')], hard: 3, tool: 'pick', lvl: 2, color: '#9aa4ae' });
B(56, 'Jewel Ore', { tex: [t('gem_ore')], hard: 3, tool: 'pick', lvl: 3, drop: -2, color: '#8a6f9a' }); // drops a random jewel
B(57, 'Gold Block', { tex: [t('gold_block')], hard: 3, tool: 'pick', lvl: 2, color: '#f5d742' });
B(58, 'Silver Block', { tex: [t('silver_block')], hard: 3, tool: 'pick', lvl: 2, color: '#d8dee6' });
B(59, 'Ice Bricks', { tex: [t('ice_bricks')], hard: 1.5, tool: 'pick', lvl: 1, color: '#a8d8f0' });
B(60, 'Treasure Chest', { tex: [t('treasure_top'), t('treasure_top'), t('treasure_front'), t('treasure_side'), t('treasure_side'), t('treasure_side')], hard: 2.5, tool: 'axe', drop: 21, color: '#c89a2d' });
const isChest = id => id === 21 || id === 60;
// dungeon stairwells: tap to go down a floor / back up to the entrance. Unbreakable and they glow.
B(61, 'Dungeon Stairs', { tex: [t('stairs_down'), t('stairs_side'), t('stairs_side')], hard: -1, drop: 0, light: 1, color: '#8a40d0' });
B(62, 'Way Up', { tex: [t('stairs_up'), t('stairs_side'), t('stairs_side')], hard: -1, drop: 0, light: 1, color: '#40d0a0' });
// fairy tale kingdom add-on (63-91): story stones, magic gates, and the things the tale quests are about. Not in the Creative list.
const spr = (id, name, tile, o) => B(id, name, Object.assign({ tex: [t(tile)], solid: false, opaque: false, shape: 'cross', hard: -1, drop: 0, cutout: true }, o));
B(63, 'Story Stone', { tex: [t('story_top'), t('story_side'), t('story_side')], hard: -1, drop: 0, light: 1, color: '#b890e0' });
B(64, 'Story Gate', { tex: [t('gate')], opaque: false, cutout: true, hard: -1, drop: 0, light: 1, color: '#f5d742' }); // solid unless its tale is read
B(65, 'Thorn Hedge', { tex: [t('thorns')], opaque: false, cutout: true, hard: -1, drop: 0, color: '#2f5a20' });
spr(66, 'Golden Ball', 'golden_ball', { light: 1, color: '#f5d742' });
B(67, 'Straw', { tex: [t('straw_top'), t('straw_top'), t('straw_side')], hard: 0.5, drop: 0, color: '#e0c060' });
spr(68, 'Spinning Wheel', 'wheel', { color: '#8a6234' });
B(69, 'Gingerbread', { tex: [t('ginger')], hard: 0.8, drop: 0, color: '#a0602a' });
B(70, 'Icing', { tex: [t('icing')], hard: 0.5, drop: 0, color: '#fff0f4' });
B(71, 'Candy', { tex: [t('candy')], hard: 0.5, drop: 0, color: '#e04050' });
spr(72, 'White Pebbles', 'pebbles', { light: 1, color: '#eeeeee' });
spr(73, 'Rose', 'rose', { color: '#e0306a' });
spr(74, 'Golden Slipper', 'slipper', { light: 1, color: '#f5d742' });
B(75, 'Featherbed', { tex: [t('quilt'), t('planks'), t('quilt_side')], opaque: false, shape: 'bed', h: 0.5625, hard: -1, drop: 0, color: '#f4f4fa' });
spr(76, 'Tiny Shoes', 'shoes', { color: '#8a3a2a' });
spr(77, 'Basket', 'basket', { color: '#a87a40' });
spr(78, 'Town Musicians', 'musicians', { color: '#8a8a8a' });
B(79, 'Golden Braid', { tex: [t('braid')], solid: false, opaque: false, shape: 'ladder', hard: -1, drop: 0, cutout: true, color: '#f5d742' });
spr(80, 'White Bird', 'bird', { color: '#fafafa' });
spr(81, 'Frog', 'frog', { color: '#4fae3a' });
B(82, 'Story Book Portal', { tex: [t('portal')], hard: -1, drop: 0, light: 1, color: '#a060f0' });
B(83, 'Way Home', { tex: [t('home_top'), t('stairs_side'), t('portal')], hard: -1, drop: 0, light: 1, color: '#40d0a0' });
// Grimm batch 2 (84-91): goats, the golden goose, the dancing shoes, a snail shell, and the silver, gold and diamond trees
spr(84, 'Little Goat', 'goat', { color: '#f0ece0' });
spr(85, 'Mother Goat', 'mother_goat', { color: '#d8d0c0' });
spr(86, 'Golden Goose', 'goose', { light: 1, color: '#f5d742' });
spr(87, 'Dancing Shoes', 'dshoes', { light: 1, color: '#e0306a' });
spr(88, 'Snail Shell', 'snail', { color: '#c89a5a' });
const magicLeaves = (id, name, tile, color) => B(id, name, { tex: [t(tile)], opaque: false, cutout: true, hard: -1, drop: 0, color });
magicLeaves(89, 'Silver Leaves', 'leaves_silver', '#d8dee6'); magicLeaves(90, 'Gold Leaves', 'leaves_gold', '#f5d742'); magicLeaves(91, 'Diamond Leaves', 'leaves_diamond', '#5decf5');
// pets + play add-on (92-97): playground pieces (from the playground kit) and Layla's heart factory. Earned, not in the Creative list.
B(92, 'Trampoline', { tex: [t('trampoline'), t('planks'), t('trampoline_side')], hard: 0.6, bounce: true, color: '#3a8ae0' }); // jump high, no fall damage
B(93, 'Slide', { tex: [t('slide')], hard: 0.6, slide: true, color: '#f5c020' }); // whoosh: you speed up on it
spr(94, 'Swing', 'swing', { hard: 0.6, drop: 94, swing: true, color: '#c84040' }); // tap it: wheee!
B(95, 'Merry-Go-Round', { tex: [t('merry_top'), t('planks'), t('merry_side')], opaque: false, shape: 'slab', h: 0.25, hard: 0.6, spin: true, color: '#e05090' });
B(96, 'Heart Block', { tex: [t('heart_block')], hard: 0.8, color: '#f38baa' });
B(97, 'Heart Machine', { tex: [t('heart_top'), t('heart_top'), t('heart_front')], hard: -1, drop: 0, light: 1, color: '#ff4f8a' }); // tap with fruit or flowers: hearts
const NBLOCKS = BLOCKS.length;
const blk = id => BLOCKS[id] || BLOCKS[0];
const isOpaque = new Uint8Array(256), isSolid = new Uint8Array(256);
for (let i = 0; i < NBLOCKS; i++) { isOpaque[i] = BLOCKS[i].opaque ? 1 : 0; isSolid[i] = BLOCKS[i].solid ? 1 : 0; }
// ---------------------------------------------------------------- items (ids 100+)
const ITEMS = {};
function I(id, name, o) { ITEMS[id] = Object.assign({ id, name, stack: 64 }, o); }
I(100, 'Stick', {}); I(101, 'Coal', { fuel: 8 }); I(102, 'Iron Ingot', {}); I(103, 'Gold Ingot', {});
I(104, 'Diamond', {}); I(105, 'Apple', { food: 4 }); I(106, 'Raw Porkchop', { food: 3 }); I(107, 'Cooked Porkchop', { food: 8 });
I(108, 'Raw Beef', { food: 3 }); I(109, 'Steak', { food: 8 }); I(110, 'Rotten Flesh', { food: 4 }); I(111, 'Bone', {});
I(112, 'Arrow', {}); I(113, 'Gunpowder', {}); I(114, 'Leather', {}); I(115, 'Door', { places: 23 }); I(116, 'String', {});
I(117, 'Bow', { stack: 1, bow: true, dur: 384 });
const MATS = [['Wooden', 1, 60, 2], ['Stone', 2, 132, 4], ['Iron', 3, 251, 6], ['Diamond', 4, 1562, 8]];
const KINDS = [['Pickaxe', 'pick'], ['Axe', 'axe'], ['Shovel', 'shovel'], ['Sword', 'sword']];
MATS.forEach((m, mi) => KINDS.forEach((k, ki) => I(120 + mi * 4 + ki, m[0] + ' ' + k[0],
{ stack: 1, tool: k[1], tier: m[1], dur: m[2], speed: m[3], dmg: k[1] === 'sword' ? 3 + mi * 1.5 : 2 + mi })));
I(140, 'Raw Dino Meat', { food: 3 }); I(141, 'Cooked Dino Steak', { food: 10 }); I(142, 'T-Rex Tooth', {});
I(143, 'T-Rex Tooth Sword', { stack: 1, tool: 'sword', tier: 4, dur: 900, speed: 8, dmg: 10 });
I(144, 'Airplane', { stack: 1, vehicle: 'plane', earn: true }); I(145, 'Helicopter', { stack: 1, vehicle: 'heli', earn: true });
// treasure add-on: silver, jewels, fruit, potions, armor, castle kits. earn: kept out of the Creative list
I(146, 'Silver Ingot', {});
I(147, 'Ruby', { earn: true }); I(148, 'Emerald', { earn: true }); I(149, 'Sapphire', { earn: true }); I(150, 'Amethyst', { earn: true });
I(151, 'Golden Apple', { food: 10, heal: 6, fx: 'regen', secs: 10, earn: true });
I(152, 'Pear', { food: 4 }); I(153, 'Orange', { food: 4 }); I(154, 'Banana', { food: 5 }); I(155, 'Cherries', { food: 3 });
I(156, 'Grapes', { food: 3 }); I(157, 'Watermelon Slice', { food: 3 });
I(159, 'Glass Bottle', {});
const POTIONS = [[160, 'Healing Potion', 'heal', 0, '#f03a5a'], [161, 'Regeneration Potion', 'regen', 30, '#f088c8'],
[162, 'Strength Potion', 'str', 90, '#b02020'], [163, 'Speed Potion', 'speed', 90, '#7ad0f0'], [164, 'Jump Potion', 'jump', 90, '#60e060'],
[165, 'Shield Potion', 'shield', 90, '#9a7ad8'], [166, 'Night Vision Potion', 'night', 120, '#3050d0'], [167, 'Water Breathing Potion', 'water', 120, '#30a0b0']];
POTIONS.forEach(([id, name, fx, secs, color]) => I(id, name, { stack: 16, potion: fx, secs, color, earn: true }));
// armor: 170 + material * 4 + piece. pts = how much it protects (all four diamond pieces stop 80% of monster damage)
const ARMOR_MATS = [['Iron', 102, [2, 6, 5, 2]], ['Gold', 103, [2, 5, 3, 1]], ['Diamond', 104, [3, 8, 6, 3]]];
const ARMOR_PIECES = [['Helmet', 5], ['Chestplate', 8], ['Leggings', 7], ['Boots', 4]];
ARMOR_MATS.forEach(([mat, , pts], mi) => ARMOR_PIECES.forEach(([piece], pi) => I(170 + mi * 4 + pi, mat + ' ' + piece,
{ stack: 1, armor: pi, pts: pts[pi], tier: mi, earn: mi === 2 })));
I(182, 'Silver Sword', { stack: 1, tool: 'sword', tier: 3, dur: 400, speed: 6, dmg: 7, undead: 2 }); // double damage to zombies and skeletons
// castle kits: place one and the whole castle builds itself, owned by whoever placed it
const KITS = [[183, 'fort'], [184, 'stone'], [185, 'royal'], [186, 'palace'], [187, 'ice']];
// castle styles. wall: [main, other] blocks mixed by `mix`; found: foundation; walk: walkway along the walls; roof: keep roof;
// flag: wool colour; rich: blocks only natural castles get (a kit castle must not be worth more than the kit)
const CASTLES = {
fort: { name: 'Wooden Fort', wall: [6, 5], mix: 0.3, found: 4, floor: 5, walk: 5, roof: 5, flag: 43 },
stone: { name: 'Stone Castle', wall: [34, 54], mix: 0.22, found: 34, floor: 4, walk: 48, roof: 48, flag: 40 },
royal: { name: 'Royal Castle', wall: [34, 34], mix: 0, found: 34, floor: 34, walk: 48, roof: 48, flag: 45, rich: 57 },
palace: { name: 'Desert Palace', wall: [50, 50], mix: 0, found: 50, floor: 50, walk: 48, roof: 50, flag: 41, rich: 57 },
ice: { name: 'Ice Castle', wall: [59, 51], mix: 0.25, found: 59, floor: 51, walk: 48, roof: 59, flag: 44, rich: 58 },
};
KITS.forEach(([id, type]) => I(id, CASTLES[type].name + ' Kit', { stack: 1, kit: type, earn: true }));
// dungeon add-on: loot boxes (tap to open) and pet items (tap to call your pet)
const BOXES = [[190, 'Bronze', '#c87a3a'], [191, 'Silver', '#d8dee6'], [192, 'Gold', '#f5d742'], [193, 'Legendary', '#c060ff']];
BOXES.forEach(([id, tier, color], ti) => I(id, tier + ' Loot Box', { stack: 16, box: ti, color, earn: true }));
I(194, 'Kitten Basket', { stack: 1, pet: 'cat', earn: true }); I(195, 'Puppy Basket', { stack: 1, pet: 'dog', earn: true });
I(196, 'Baby Dino Egg', { stack: 1, pet: 'babydino', earn: true });
// pets + play add-on (220-226; 200-219 and 290+ belong to the fairy tale places)
I(220, 'Pet Food', { petfood: 40 }); // tap it: feeds your hungriest pet
I(221, 'Heart', { heart: true, heal: 6, earn: true }); // from the heart machine: heals you and cheers up your pets
I(222, 'Playground Kit', { stack: 1, kit: 'playground', earn: true }); I(223, 'Heart Factory Kit', { stack: 1, kit: 'heart', earn: true });
I(224, 'Fighter Jet', { stack: 1, vehicle: 'jet', earn: true }); I(225, 'Stunt Jet', { stack: 1, vehicle: 'stunt', earn: true });
I(226, 'Spy Jet', { stack: 1, vehicle: 'spy', earn: true });
const TAME_FOOD = [111, 106, 108, 140, 220]; // a wild white wolf takes bones, raw meat or pet food
const itemName = id => id < 100 ? blk(id).name : (ITEMS[id] ? ITEMS[id].name : '?');
const stackSize = id => id < 100 ? 64 : (ITEMS[id] ? ITEMS[id].stack : 64);
const isItem = id => id >= 100;
const allCreative = [];
for (let i = 1; i < NBLOCKS; i++) if (i !== 10 && i !== 16 && i < 60 && !(i >= 23 && i <= 30)) allCreative.push(i);
Object.keys(ITEMS).forEach(k => { if (!ITEMS[k].earn) allCreative.push(+k); }); // vehicles, jewels, potions, kits... have to be earned in survival
// ---------------------------------------------------------------- recipes
// st: '' anywhere, 'table' near a crafting table, 'furnace' near a furnace (uses fuel)
const R = (out, n, inp, st) => ({ out, n, inp, st: st || '' });
const RECIPES = [
R(5, 4, [[6, 1]]), R(100, 4, [[5, 2]]), R(19, 1, [[5, 4]]), R(22, 4, [[100, 1], [101, 1]]),
R(20, 1, [[4, 8]], 'table'), R(21, 1, [[5, 8]], 'table'), R(115, 1, [[5, 6]], 'table'),
R(31, 1, [[39, 3], [5, 3]], 'table'), R(32, 1, [[113, 5], [8, 4]], 'table'), R(52, 3, [[100, 7]], 'table'),
R(34, 4, [[3, 4]], 'table'), R(48, 6, [[4, 3]], 'table'), R(50, 1, [[8, 4]], 'table'), R(35, 1, [[5, 6], [114, 3]], 'table'),
R(117, 1, [[100, 3], [116, 3]], 'table'), R(112, 4, [[100, 1], [9, 1]], 'table'), R(39, 1, [[116, 4]], 'table'),
R(49, 1, [[103, 1], [101, 4]], 'table'), R(33, 1, [[2, 2], [8, 2]], 'furnace'),
R(102, 1, [[13, 1]], 'furnace'), R(103, 1, [[14, 1]], 'furnace'), R(11, 1, [[8, 1]], 'furnace'),
R(3, 1, [[4, 1]], 'furnace'), R(107, 1, [[106, 1]], 'furnace'), R(109, 1, [[108, 1]], 'furnace'), R(101, 1, [[6, 1]], 'furnace'),
R(141, 1, [[140, 1]], 'furnace'), R(53, 1, [[104, 9]], 'table'), R(104, 9, [[53, 1]]), R(143, 1, [[142, 2], [100, 1]], 'table'),
R(54, 1, [[34, 1], [7, 1]], 'table'),
// vehicles are the big goal: lots of iron plus diamonds
R(144, 1, [[102, 8], [104, 2], [5, 4], [11, 1]], 'table'), R(145, 1, [[102, 10], [104, 4], [11, 2]], 'table'),
// treasure add-on
R(146, 1, [[55, 1]], 'furnace'), R(57, 1, [[103, 9]], 'table'), R(103, 9, [[57, 1]]), R(58, 1, [[146, 9]], 'table'), R(146, 9, [[58, 1]]),
R(59, 4, [[11, 4], [146, 1]], 'table'), R(159, 3, [[11, 1]], 'table'), R(151, 1, [[105, 1], [103, 8]], 'table'),
R(160, 1, [[159, 1], [105, 2]], 'table'), R(161, 1, [[159, 1], [151, 1]], 'table'), R(162, 1, [[159, 1], [147, 1]], 'table'),
R(163, 1, [[159, 1], [149, 1]], 'table'), R(164, 1, [[159, 1], [148, 1]], 'table'), R(165, 1, [[159, 1], [150, 1], [102, 1]], 'table'),
R(166, 1, [[159, 1], [49, 1]], 'table'), R(167, 1, [[159, 1], [156, 2]], 'table'),
R(182, 1, [[146, 2], [100, 1]], 'table'),
R(183, 1, [[6, 40], [11, 4], [22, 8]], 'table'), R(184, 1, [[34, 64], [11, 16], [102, 4]], 'table'),
R(185, 1, [[34, 64], [57, 8], [53, 2], [147, 4]], 'table'), R(186, 1, [[50, 64], [57, 4], [11, 8]], 'table'),
R(187, 1, [[11, 64], [149, 4], [146, 16]], 'table'),
// pets + play add-on: pet food anywhere, kits at a table, heart blocks from hearts, beds from any colour of wool
R(220, 2, [[106, 1]]), R(220, 2, [[108, 1]]), R(220, 2, [[140, 1]]), R(220, 1, [[111, 2]]), R(96, 4, [[221, 1]]),
R(222, 1, [[5, 32], [102, 4], [39, 6], [116, 4]], 'table'), R(223, 1, [[5, 24], [11, 8], [102, 4], [47, 8]], 'table'),
...[40, 41, 42, 43, 44, 45, 46, 47].map(w => R(31, 1, [[w, 3], [5, 3]], 'table')),
];
ARMOR_MATS.forEach(([, m], mi) => ARMOR_PIECES.forEach(([, n], pi) => RECIPES.push(R(170 + mi * 4 + pi, 1, [[m, n]], 'table'))));
const toolMat = [5, 4, 102, 104];
toolMat.forEach((m, mi) => {
RECIPES.push(R(120 + mi * 4, 1, [[m, 3], [100, 2]], 'table'), R(121 + mi * 4, 1, [[m, 3], [100, 2]], 'table'),
R(122 + mi * 4, 1, [[m, 1], [100, 2]], 'table'), R(123 + mi * 4, 1, [[m, 2], [100, 1]], 'table'));
});
// dyed wool: white wool plus something colourful
[[40, [36]], [41, [36, 37]], [42, [37]], [43, [18]], [44, [11, 9]], [45, [36, 11]], [46, [101]], [47, [36, 111]]]
.forEach(([out, dyes]) => RECIPES.push(R(out, 1, [[39, 1]].concat(dyes.map(d => [d, 1])))));
const FUEL = { 101: 8, 5: 1.5, 6: 1.5, 100: 0.5, 19: 1.5, 21: 1.5 };
// ---------------------------------------------------------------- noise
function hash(x, y, z, s) {
let h = Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(z | 0, 0x1b873593) ^ Math.imul(s | 0, 0x85ebca6b);
h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d);
h = Math.imul(h ^ (h >>> 12), 0x297a2d39);
h ^= h >>> 15;
return (h >>> 0) / 4294967296;
}
const sm = f => f * f * (3 - 2 * f);
function noise2(x, z, s) {
const xi = Math.floor(x), zi = Math.floor(z), fx = sm(x - xi), fz = sm(z - zi);
const a = hash(xi, 0, zi, s), b = hash(xi + 1, 0, zi, s), c = hash(xi, 0, zi + 1, s), d = hash(xi + 1, 0, zi + 1, s);
return a + (b - a) * fx + (c - a) * fz + (a - b - c + d) * fx * fz;
}
function fbm2(x, z, s, oct) {
let v = 0, amp = 1, tot = 0, f = 1;
for (let o = 0; o < oct; o++) { v += noise2(x * f, z * f, s + o * 31) * amp; tot += amp; amp *= 0.5; f *= 2; }
return v / tot;
}
function noise3(x, y, z, s) {
const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z);
const fx = sm(x - xi), fy = sm(y - yi), fz = sm(z - zi);
const l = (a, b, f) => a + (b - a) * f;
const c = (dx, dy, dz) => hash(xi + dx, yi + dy, zi + dz, s);
return l(l(l(c(0, 0, 0), c(1, 0, 0), fx), l(c(0, 1, 0), c(1, 1, 0), fx), fy),
l(l(c(0, 0, 1), c(1, 0, 1), fx), l(c(0, 1, 1), c(1, 1, 1), fx), fy), fz);
}
// ---------------------------------------------------------------- world generation
// biome: 0 plains, 1 forest, 2 desert, 3 snowy
function biomeAt(x, z, seed) {
const temp = fbm2(x / 220, z / 220, seed + 101, 2), wet = fbm2(x / 170, z / 170, seed + 202, 2);
if (temp > 0.62) return 2;
if (temp < 0.36) return 3;
return wet > 0.52 ? 1 : 0;
}
function heightAt(x, z, seed) {
const cont = fbm2(x / 110, z / 110, seed, 3), hill = fbm2(x / 36, z / 36, seed + 50, 3);
let h = 14 + cont * 20 + Math.pow(hill, 2) * 16 + (Math.max(0, cont - 0.62) * 40);
return Math.max(3, Math.min(CH - 10, Math.floor(h)));
}
function treeAt(x, z, seed, biome, h) {
if (h <= SEA || biome === 2) return 0;
const r = hash(x, 7, z, seed);
const dens = biome === 1 ? 0.035 : biome === 3 ? 0.012 : 0.004;
if (r >= dens) return 0;
return 4 + Math.floor(hash(x, 8, z, seed) * 3);
}
// ---------------------------------------------------------------- castles
// At most one castle per 128x128 region, 21x21 blocks, built on the ground level of its centre. The type depends on
// the land and luck: grassland/forest has Stone Castles (the original ones, unchanged), Wooden Forts and rare Royal
// Castles; deserts have Desert Palaces; snowy land has Ice Castles. Castle kits build the same castles (c.kit = true).
const REG = 128, CW = 21;
function castleAt(rx, rz, seed) {
const h = hash(rx, 99, rz, seed);
if (h >= 0.7) return null;
const cx = rx * REG + 24 + Math.floor(hash(rx, 98, rz, seed) * (REG - 48)), cz = rz * REG + 24 + Math.floor(hash(rx, 97, rz, seed) * (REG - 48));
const bm = biomeAt(cx, cz, seed), base = heightAt(cx, cz, seed);
if (base <= SEA + 1 || base > CH - 18) return null;
if (Math.abs(cx) < 30 && Math.abs(cz) < 30) return null; // keep the world spawn area free
const type = bm <= 1 ? (h < 0.45 ? 'stone' : h < 0.62 ? 'fort' : 'royal') : h < 0.5 ? (bm === 2 ? 'palace' : 'ice') : null;
if (!type) return null;
return { x0: cx - 10, z0: cz - 10, base, seed, type };
}
// block id for castle-local (lx, y, lz), or -1 to leave the land alone
function castleBlock(c, lx, y, lz) {
const b = c.base, edge = lx === 0 || lx === CW - 1 || lz === 0 || lz === CW - 1, P = CASTLES[c.type || 'stone'];
const wall = () => P.mix && hash(c.x0 + lx, y, c.z0 + lz, c.seed + 5) < P.mix ? P.wall[1] : P.wall[0];
const top = () => P.rich && !c.kit ? P.rich : wall(); // battlements: gold or silver on rich natural castles
if (y < b - 6) return -1;
if (y <= b) return y === b ? (edge ? P.found : P.floor) : P.found; // foundation and courtyard floor
if (y > b + 16) return -1;
// corner towers: 5x5 rings, 8 high, ladder inside, floor and battlements on top, a flag
const tx = lx < 5 ? 0 : lx >= CW - 5 ? CW - 5 : -1, tz = lz < 5 ? 0 : lz >= CW - 5 ? CW - 5 : -1;
if (tx >= 0 && tz >= 0) {
const ix = lx - tx, iz = lz - tz, ring = ix === 0 || ix === 4 || iz === 0 || iz === 4;
const inX = tx === 0 ? 4 : 0, inZ = tz === 0 ? 4 : 0; // the ring sides facing the courtyard
if (ring) {
if (y <= b + 8) {
if (y <= b + 2 && ix === 2 && iz === inZ) return 0; // doorway from the courtyard
if (y === b + 4 && (ix === 2 || iz === 2) && !(iz === inZ || ix === inX)) return 11; // arrow slits
return wall();
}
if (y === b + 9) return (ix + iz) % 2 === 0 ? top() : 0;
return 0;
}
if (ix === 2 && iz === (inZ === 4 ? 1 : 3)) return y <= b + 8 ? 52 : 0; // ladder beside the far wall
if (y === b + 8) return 5;
if (ix === 2 && iz === 2 && (y === b + 9 || y === b + 10)) return 6; // flag pole
if (ix === 3 && iz === 2 && y === b + 10) return c.flag || P.flag; // flag (a kit castle flies its owner's colour)
if (y === b + 2 && ix === 1 && iz === 2) return 22;
return 0;
}
// outer walls with a gate in the north wall and battlements
if (edge) {
if (lz === 0 && lx >= 9 && lx <= 11 && y <= b + 3) return 0;
if (y <= b + 5) return wall();
if (y === b + 6) return (lx + lz) % 2 === 0 ? top() : 0;
return 0;
}
// walkway along the inside of the walls
if ((lx === 1 || lx === CW - 2 || lz === 1 || lz === CW - 2) && y === b + 5 && !(lz === 1 && lx >= 8 && lx <= 12)) return P.walk;
// the keep: 7x7 house in the middle with a door, windows, a slab roof, chest, table and torches
if (lx >= 7 && lx <= 13 && lz >= 9 && lz <= 15) {
const kx = lx - 7, kz = lz - 9, kwall = kx === 0 || kx === 6 || kz === 0 || kz === 6;
if (kwall) {
if (kz === 0 && kx === 3 && y === b + 1) return 23;
if (kz === 0 && kx === 3 && y === b + 2) return 24;
if (y <= b + 6) return (y === b + 3 && (kx === 3 || kz === 3) && !(kz === 0 && kx === 3)) ? 11 : wall();
if (y === b + 7) return (kx + kz) % 2 === 0 ? wall() : 0;
return 0;
}
if (y === b + 7) return P.roof;
if (y === b + 1 && kx === 3 && kz === 5) return 60; // the treasure chest
if (y === b + 1 && kx === 1 && kz === 5) return 19;
if (y === b + 1 && kx === 5 && kz === 5) return 31;
if (y === b + 3 && (kx === 1 || kx === 5) && kz === 1) return 22;
return 0;
}
if (y === b + 1 && (lx === 6 || lx === 14) && lz === 4) return 22; // courtyard torches
return 0;
}
function castleLoot(x, y, z, seed) {
const c = castleAt(Math.floor(x / REG), Math.floor((z - 4) / REG), seed); // the chest sits at the castle centre + 4 south
if (!c || x !== c.x0 + 10 || z !== c.z0 + 14 || y !== c.base + 1) return null;
// each castle type has its own treasure; rarer castles hold better things
const n = (k, a, b) => a + Math.floor(hash(x, y + k, z, seed + 61) * (b - a + 1));
const luck = (k, p) => hash(x, y + k, z, seed + 62) < p;
const s = [], add = (id, cnt, d) => { if (cnt > 0) s.push(d ? { id, n: cnt, d } : { id, n: cnt }); };
const fruit = [105, 152, 153, 154, 155, 156, 157], jewel = [147, 148, 149, 150];
switch (c.type) {
case 'fort': // simple camp supplies
add(105, n(1, 3, 6)); add(fruit[n(2, 1, 6)], n(3, 2, 4)); add(102, n(4, 2, 5)); add(22, 12); add(112, n(5, 6, 14));
add(160, 1); if (luck(1, 0.5)) add(173, 1); if (luck(2, 0.3)) add(146, n(6, 2, 4)); break;
case 'palace': // gold, silver, jewels, desert fruit
add(103, n(1, 6, 12)); add(146, n(2, 4, 8)); add(147, n(3, 1, 3)); add(148, n(4, 1, 3)); add(153, n(5, 2, 5));
add(154, n(6, 2, 5)); add(156, n(7, 2, 4)); add(163, 1); add(160, n(8, 1, 2));
if (luck(1, 0.35)) add(151, 1); add(174 + n(9, 0, 3), 1); break;
case 'ice': // diamonds, cold jewels, silver
add(104, n(1, 4, 8)); add(149, n(2, 2, 4)); add(150, n(3, 1, 3)); add(146, n(4, 4, 8)); add(157, n(5, 2, 4));
add(167, 1); add(166, 1); add(160, 1); if (luck(1, 0.5)) add(181, 1); if (luck(2, 0.3)) add(53, 1); break;
case 'royal': // the best: lots of diamonds, every jewel, strong potions, diamond tools and armor
add(104, n(1, 8, 14)); jewel.forEach((j, i) => add(j, n(10 + i, 2, 4))); add(151, n(2, 1, 2)); add(103, n(3, 4, 8));
add(162, 1); add(165, 1); add(161, 1); add(160, 2); add(luck(1, 0.5) ? 132 : 135, 1, 1562);
add(178 + n(4, 0, 3), 1); add(53, 1); break;
default: // the original Stone Castle chest, plus a little silver and a healing potion
add(104, n(1, 3, 6)); add(102, n(2, 4, 9)); add(103, n(3, 2, 5)); add(105, n(4, 2, 5)); add(22, 16); add(112, n(5, 4, 12));
if (hash(x, y, z, seed + 62) < 0.4) add(135, 1, 1562);
if (hash(x, y, z, seed + 63) < 0.5) add(53, 1);
add(146, n(6, 2, 5)); add(160, 1);
}
return s;
}
// ---------------------------------------------------------------- dungeon floors
// The dungeon is far away to the east (x from DGX), sealed in bedrock. Floor f (1, 2, ...) is a 128x128 maze of 8x8 cells,
// one room per cell, joined by corridors. Cell (0,0) is the safe room with the Way Up; the cell farthest from it is the
// boss room, where the stairs to the next floor appear once its boss has been beaten.
const DGX = 1048576, FSTEP = 512, FW = 128, FY = 10, NC = 8;
const inDungeon = x => x >= DGX - 256;
const floorAt = x => inDungeon(x) ? Math.floor((x - DGX) / FSTEP) + 1 : 0;
const mazes = new Map();
function dungeonMaze(f, seed) {
const k = f + ':' + seed; let mz = mazes.get(k);
if (mz) return mz;
const open = new Uint8Array(NC * NC); // bits: 1 = +x, 2 = -x, 4 = +z, 8 = -z
const seen = new Uint8Array(NC * NC), stack = [0]; seen[0] = 1; let step = 0;
const DIRS = [[1, 0, 1, 2], [-1, 0, 2, 1], [0, 1, 4, 8], [0, -1, 8, 4]];
while (stack.length) { // random depth-first maze, then a few extra links so it isn't one long path
const c = stack[stack.length - 1], cx = c % NC, cz = (c / NC) | 0;
const opts = DIRS.filter(([dx, dz]) => { const x = cx + dx, z = cz + dz; return x >= 0 && z >= 0 && x < NC && z < NC && !seen[z * NC + x]; });
if (!opts.length) { stack.pop(); continue; }
const [dx, dz, a, b] = opts[Math.floor(hash(f, step++, c, seed + 71) * opts.length)], n = (cz + dz) * NC + cx + dx;
open[c] |= a; open[n] |= b; seen[n] = 1; stack.push(n);
}
for (let c = 0; c < NC * NC; c++) if (hash(f, c, 5, seed + 72) < 0.12 && c % NC < NC - 1) { open[c] |= 1; open[c + 1] |= 2; }
const dist = new Int16Array(NC * NC).fill(-1), q = [0]; dist[0] = 0; let boss = 0;
while (q.length) {
const c = q.shift();
if (dist[c] > dist[boss]) boss = c;
for (const [dx, dz, a] of DIRS) if (open[c] & a) { const n = c + dz * NC + dx; if (dist[n] < 0) { dist[n] = dist[c] + 1; q.push(n); } }
}
const rooms = [];
for (let c = 0; c < NC * NC; c++) {
const big = c === 0 || c === boss, w = big ? 12 : 6 + Math.floor(hash(f, c, 1, seed + 73) * 5), d = big ? 12 : 6 + Math.floor(hash(f, c, 2, seed + 73) * 5);
const cx = (c % NC) * 16 + 8, cz = ((c / NC) | 0) * 16 + 8;
rooms.push({ x0: cx - (w >> 1), z0: cz - (d >> 1), x1: cx - (w >> 1) + w - 1, z1: cz - (d >> 1) + d - 1, cx, cz,
chest: !big && hash(f, c, 3, seed + 74) < 0.3 });
}
mz = { open, boss, rooms, ox: DGX + (f - 1) * FSTEP };
mazes.set(k, mz); if (mazes.size > 12) mazes.delete(mazes.keys().next().value);
return mz;
}
// what to stand on / where things are, in world coordinates
const floorStart = (f, seed) => { const mz = dungeonMaze(f, seed), r = mz.rooms[0]; return { x: mz.ox + r.cx + 0.5, y: FY + 1, z: r.cz + 2.5 }; };
const bossRoom = (f, seed) => { const mz = dungeonMaze(f, seed), r = mz.rooms[mz.boss]; return { x0: mz.ox + r.x0, z0: r.z0, x1: mz.ox + r.x1, z1: r.z1, cx: mz.ox + r.cx, cz: r.cz }; };
function inSafeRoom(x, z, seed) {
const f = floorAt(x); if (f < 1) return false;
const r = dungeonMaze(f, seed).rooms[0], lx = x - (DGX + (f - 1) * FSTEP);
return lx >= r.x0 - 0.3 && lx <= r.x1 + 1.3 && z >= r.z0 - 0.3 && z <= r.z1 + 1.3;
}
// block for dungeon world position (x, y, z)
function dungeonBlock(x, y, z, seed) {
if (y === 0 || y > FY + 8) return 16;
const f = floorAt(x), lx = x - (DGX + (f - 1) * FSTEP);
if (f < 1 || lx < 0 || lx >= FW || z < 0 || z >= FW) return 16;
const mz = dungeonMaze(f, seed), c = (z >> 4) * NC + (lx >> 4), r = mz.rooms[c], o = mz.open[c];
const inRoom = lx >= r.x0 && lx <= r.x1 && z >= r.z0 && z <= r.z1;
const lcx = lx & 15, lcz = z & 15;
const inHall = (lcz >= 7 && lcz <= 9 && ((o & 1 && lcx >= 8) || (o & 2 && lcx <= 8))) || (lcx >= 7 && lcx <= 9 && ((o & 4 && lcz >= 8) || (o & 8 && lcz <= 8)));
const brick = hash(x, y, z, seed + 75) < 0.25 ? 54 : 34;
if (y < FY) return brick;
if (y === FY) return inRoom && c === 0 ? 44 : inRoom && c === mz.boss ? ((lx - r.x0) % 4 === 1 && (z - r.z0) % 4 === 1 ? 49 : 46) : brick; // safe room: blue floor; boss room: black with lights
if (y === FY + 6) return inRoom && lx === r.cx && z === r.cz ? 49 : brick; // a light in every room's ceiling
if (y > FY + 6) return brick;
if (!inRoom && !inHall) return brick;
if (inRoom && c === 0) { // the safe room
if (y === FY + 1 && lx === r.cx && z === r.cz) return 62;
if (y === FY + 1 && lx === r.x0 && z === r.z0) return 19;
if (y === FY + 1 && lx === r.x1 && z === r.z0) return 31;
if (y === FY + 3 && (lx === r.x0 || lx === r.x1) && z === r.cz) return 22;
}
if (inRoom && r.chest && y === FY + 1 && lx === r.x0 && z === r.z0) return 60;
if (inRoom && c !== 0 && c !== mz.boss && y === FY + 1 && lx === r.x1 && z === r.z1 && hash(x, y, z, seed + 76) < 0.5) return 35;
return 0;
}
function dungeonLoot(x, y, z, seed) {
const f = floorAt(x); if (f < 1 || y !== FY + 1) return null;
const mz = dungeonMaze(f, seed), lx = x - mz.ox, c = (z >> 4) * NC + (lx >> 4), r = mz.rooms[c];
if (!r || !r.chest || lx !== r.x0 || z !== r.z0) return null;
const n = (k, a, b) => a + Math.floor(hash(x, y + k, z, seed + 77) * (b - a + 1)), s = [];
s.push({ id: 190 + Math.min(3, Math.floor((f - 1) / 2) + (n(1, 0, 3) === 3 ? 1 : 0)), n: 1 }); // a loot box, better on deeper floors
s.push({ id: [105, 152, 153, 154, 155][n(2, 0, 4)], n: n(3, 2, 4) }, { id: 160, n: n(4, 1, 2) }, { id: 102, n: n(5, 2, 5) + f });
if (f >= 2) s.push({ id: 104, n: n(6, 1, 2) + (f >> 1) });
if (f >= 3) s.push({ id: 147 + n(7, 0, 3), n: n(8, 1, 3) });
s.push({ id: 112, n: n(9, 6, 14) }, { id: 22, n: 8 });
return s;
}
// ---------------------------------------------------------------- fairy tale kingdom
// A storybook land far to the south (z from KZ = 32768: far enough that nobody walks there, near enough that the 3D maths stays exact), reached through the Story Book arch next to the world spawn. It has one
// hedged place per Grimm tale from ABC Books (book grimm1884). A place's gate opens for a kid once they have read every part
// of that tale in ABC Books (the page checks that; see setGateOpen). Each place has a story stone, a small quest and a reward:
// a keepsake item plus a kit that builds the same place on your own land (owned like the castle kits).
// Places are 21 x 21 (like a kit castle) with the gate in the middle of the front (lz = 0) and the story stone beside it.
// steps: what to tap, in order: at [lx, dy, lz] (dy = height above the ground), or id (any block of that kind in the place),
// n = how many different ones; say = what you hear, hint = what to do next.
const KZ = 32768, KY = 28, KZ1 = KZ + 127, PW = 21, PH = 28, PY0 = -3;
const inKingdom = z => z >= KZ - 256;
const PLAZA = { x: 0, z: KZ + 63 }, KSTART = { x: 0.5, y: KY + 1, z: KZ + 67.5 };
const TALES = [
{ id: 'elves', abc: 'The Elves', title: 'The Elves', place: "Shoemaker's Shop", keep: 'Tiny Shoes', tile: 'shoes', color: '#8a3a2a', parts: [1, 4],
ach: ['Elf Helper', 'The elves would like their shoes back now.'],
sum: 'The Elves. A kind shoemaker is so poor that he has leather for only one more pair of shoes. At night, two little elves come and sew the most beautiful shoes, and the shoemaker becomes rich. To say thank you, he and his wife make the elves tiny clothes.',
quest: 'Your quest: find the three pairs of tiny shoes the elves made, then leave little clothes on the workbench.',
steps: [{ id: 76, n: 3, hint: 'Find the tiny shoes in the shoemaker\'s shop.', say: ['A pair of tiny shoes! Two more to find.', 'Another pair of tiny shoes! One more to find.', 'The last pair of tiny shoes! Now go to the workbench.'] },
{ id: 19, hint: 'Leave little clothes on the workbench.', say: 'You left little shirts and coats on the workbench. The elves put them on and dance for joy!' }],
win: 'The elves are so happy! You earned the Tiny Shoes, and a Shoemaker\'s Shop kit to build at home.' },
{ id: 'frog', abc: 'The Frog-King, or Iron Henry', title: 'The Frog-King', place: "The Frog's Well", keep: 'Golden Ball', tile: 'golden_ball', color: '#3f9a2f', parts: [5, 5],
ach: ['Ball Diver', 'The frog says you are a very good swimmer. For a human.'],
sum: 'The Frog-King. A princess drops her golden ball into a deep well, and a frog brings it back to her. The frog wants to be her friend, and in the end he turns into a king\'s son. His faithful servant Henry is so happy that the iron bands around his heart break.',
quest: 'Your quest: the golden ball fell into the well again! Dive down and find it, then give it to the frog.',
steps: [{ at: [10, -2, 10], hint: 'Find the golden ball at the bottom of the well.', say: 'You found the golden ball! Now give it to the frog sitting on the well.' },
{ at: [12, 2, 8], hint: 'Give the ball to the frog on the edge of the well.', say: 'Ribbit! The frog says thank you!' }],
win: 'The frog is so happy! You earned the Golden Ball, and a Frog\'s Well kit to build at home.' },
{ id: 'redcap', abc: 'Little Red-Cap', title: 'Little Red-Cap', place: "Grandmother's Cottage", keep: 'Red Cap', color: '#c02020', parts: [10, 5],
ach: ["Grandmother's Visitor", 'You stayed on the path. The wolf is very disappointed.'],
sum: 'Little Red-Cap. A little girl in a red velvet cap takes cake and wine through the wood to her sick grandmother. A sly wolf tricks her, but a huntsman saves Red-Cap and her grandmother, and Red-Cap learns to stay on the path.',
quest: 'Your quest: take the basket from home, pick a flower in the wood, and visit Grandmother.',
steps: [{ at: [8, 1, 4], hint: 'Get the basket at the little house by the gate.', say: 'You have the basket with cake and wine. Now pick a flower for Grandmother.' },
{ id: 36, hint: 'Pick a red flower in the wood.', say: 'What a pretty flower! Now take it to Grandmother\'s cottage.' },
{ id: 31, hint: 'Visit Grandmother. She is in bed in her cottage.', say: 'Grandmother is so happy to see you!' }],
win: 'Grandmother feels better already! You earned the Red Cap, and a Grandmother\'s Cottage kit to build at home.' },
{ id: 'bremen', abc: 'The Bremen Town-Musicians', title: 'The Bremen Town-Musicians', place: "The Robbers' House", keep: "Donkey's Lute", color: '#7a6a5a', parts: [15, 5],
ach: ['Town Musician', 'Hee-haw! Woof! Meow! Cock-a-doodle-doo! That means bravo.'],
sum: 'The Bremen Town-Musicians. An old donkey, a dog, a cat and a rooster run away to be musicians in Bremen. In the forest they find a robbers\' house. They stand on each other\'s backs and sing at the window, and the robbers run away. The animals like the house so much that they stay there.',
quest: 'Your quest: help the animals sing at the window, then find the feast and a warm place by the fire.',
steps: [{ at: [8, 1, 7], hint: 'Find the four animals by the window.', say: 'Hee-haw! Woof! Meow! Cock-a-doodle-doo! The robbers run away!' },
{ at: [10, 2, 13], hint: 'Find the feast on the table in the house.', say: 'What a feast! The four friends eat until they are full.' },
{ id: 20, hint: 'Find the warm fire in the house.', say: 'The cat curls up by the warm fire. Good night, musicians!' }],
win: 'The musicians have a home! You earned the Donkey\'s Lute, and a Robbers\' House kit to build at home.' },
{ id: 'rumpel', abc: 'Rumpelstiltskin', title: 'Rumpelstiltskin', place: 'The Spinning Room', keep: 'Golden Thread', color: '#d0a020', parts: [20, 4],
ach: ['Name Guesser', 'Is it Bob? No? Is it Rumpelstiltskin? It is!'],
sum: 'Rumpelstiltskin. A miller boasts that his daughter can spin straw into gold, so the king locks her in a room full of straw. A strange little man spins the gold for her, but he wants a big promise. She can only keep her baby if she guesses his name, and at the very last moment she does!',
quest: 'Your quest: find the straw, the spinning wheel and the gold, then listen at the little fire to learn the little man\'s name.',
steps: [{ id: 67, hint: 'Find a pile of straw in the spinning room.', say: 'Straw, straw, so much straw!' },
{ at: [10, 1, 11], hint: 'Find the spinning wheel.', say: 'Whirr, whirr, whirr! The wheel spins the straw into gold.' },
{ id: 57, hint: 'Find the pile of gold.', say: 'Look at all that gold!' },
{ at: [6, 1, 18], hint: 'Find the little fire in the wood behind the spinning room.', say: 'Listen! The little man sings by his fire: nobody knows my name is Rumpelstiltskin!' }],
win: 'You found out his name! You earned the Golden Thread, and a Spinning Room kit to build at home.' },
{ id: 'holle', abc: 'Mother Holle', title: 'Mother Holle', place: "Mother Holle's House", keep: 'Gold Coin', color: '#e8e8f0', parts: [24, 4],
ach: ['Hard Worker', 'You shook that featherbed so hard it snowed for a week.'],
sum: 'Mother Holle. A kind, hard-working girl falls down a well into a beautiful meadow. She takes the bread out of the oven, shakes the apple tree, and shakes Mother Holle\'s featherbed so hard that it snows in the world. When she goes home, gold rains down on her. Her lazy sister does none of it, and comes home covered in pitch!',
quest: 'Your quest: work like the kind girl. Take the bread out of the oven, shake the apple tree, and shake the featherbed.',
steps: [{ id: 20, hint: 'Find the oven full of bread.', say: 'Take us out, or we shall burn! You took out all the loaves.' },
{ at: [5, 1, 13], hint: 'Find the apple tree.', say: 'Shake me, my apples are all ripe! Down fall the apples.' },
{ id: 75, hint: 'Find the featherbed in Mother Holle\'s house.', say: 'You shook the featherbed. The feathers fly, and it snows in the world!' }],
win: 'Gold falls on you like rain! You earned a Gold Coin, and a Mother Holle\'s House kit to build at home.' },
{ id: 'briar', abc: 'Briar-Rose', title: 'Briar-Rose', place: 'The Thorn-Hedge Castle', keep: 'Rose', tile: 'rose', color: '#e0306a', parts: [28, 5],
ach: ['Hundred-Year Wake-Up', 'Good morning! You missed a hundred breakfasts.'],
sum: 'Briar-Rose. One wise woman is not invited to a princess\'s birth party, and she says the princess will prick her finger on a spindle. When it happens, the whole castle falls asleep for a hundred years, and a thorn hedge grows all around it. Then a king\'s son comes, the thorns turn into flowers, and Briar-Rose wakes up.',
quest: 'Your quest: get through the thorn hedge, climb the old tower, and wake Briar-Rose.',
steps: [{ at: [10, 1, 3], hint: 'Find the rose in the thorn hedge.', say: 'The thorns turn into big, beautiful flowers and let you through!' },
{ at: [9, 9, 11], hint: 'Climb the ladder to the little room at the top of the tower.', say: 'Here is the little room at the top of the tower, with the old spinning wheel.' },
{ id: 31, hint: 'Find Briar-Rose asleep in the tower room.', say: 'Wake up, Briar-Rose! The whole castle wakes up after a hundred years!' }],
win: 'Everyone is awake again! You earned a Rose, and a Thorn-Hedge Castle kit to build at home.' },
{ id: 'rapunzel', abc: 'Rapunzel', title: 'Rapunzel', place: "Rapunzel's Tower", keep: 'Golden Braid', tile: 'braid', color: '#f5d742', parts: [33, 5],
ach: ['Braid Climber', 'Ouch, says Rapunzel. Please wipe your feet.'],
sum: 'Rapunzel. An enchantress shuts a girl with very long golden hair in a tower with no door and no stairs. To get in, she calls: Rapunzel, Rapunzel, let down your hair! A king\'s son hears it and climbs up the braid too, and after many sad years they find each other again.',
quest: 'Your quest: call to Rapunzel, climb her golden braid, and visit her in the tower room.',
steps: [{ at: [10, 1, 7], hint: 'Find the golden braid at the bottom of the tower.', say: 'Rapunzel, Rapunzel, let down your hair! Now climb up the golden braid.' },
{ at: [11, 16, 11], hint: 'Climb the braid and find the rose in Rapunzel\'s room.', say: 'You climbed all the way up! Rapunzel is so glad to have a visitor.' }],
win: 'What a climb! You earned the Golden Braid, and a Rapunzel\'s Tower kit to build at home.' },
{ id: 'cinder', abc: 'Cinderella', title: 'Cinderella', place: 'The Hazel Tree Garden', keep: 'Golden Slipper', tile: 'slipper', color: '#8fd0f0', parts: [38, 9],
ach: ['Perfect Fit', 'The prince checked a lot of feet. Yours were the right ones.'],
sum: 'Cinderella. A kind girl has to work in the kitchen and sleep by the ashes. A little white bird in her hazel tree gives her beautiful dresses for the king\'s festival. She runs away from the king\'s son three times, but he finds her with the golden slipper she left on the stairs.',
quest: 'Your quest: sort the lentils by the hearth, visit the white bird in the hazel tree, and find the golden slipper on the palace stairs.',
steps: [{ id: 20, hint: 'Find the hearth in the little kitchen.', say: 'The good ones go into the pot! The birds help you pick the lentils out of the ashes.' },
{ at: [13, 4, 6], hint: 'Find the white bird in the hazel tree.', say: 'Shiver and quiver, little tree! The bird throws down a dress of gold and silver.' },
{ at: [10, 4, 16], hint: 'Find the golden slipper on the palace stairs.', say: 'You found the golden slipper on the palace stairs! It fits perfectly.' }],
win: 'The slipper fits! You earned the Golden Slipper, and a Hazel Tree Garden kit to build at home.' },
{ id: 'hansel', abc: 'Hansel and Grethel', title: 'Hansel and Grethel', place: 'The Gingerbread House', keep: 'Gingerbread Heart', color: '#a0602a', parts: [47, 10],
ach: ['Pebble Tracker', 'You found the way home. The birds ate all the breadcrumbs anyway.'],
sum: 'Hansel and Grethel. A brother and sister are left alone in the forest. The first time, Hansel finds the way home by following the white pebbles he dropped. Later they find a little house made of bread and cake. A wicked witch lives there, but clever Grethel tricks her, and the children go home with the witch\'s pearls and jewels.',
quest: 'Your quest: follow the white pebbles to the gingerbread house, then find the treasure inside.',
steps: [{ at: [10, 1, 2], hint: 'Follow the white pebbles, starting at the gate.', say: 'The first white pebble! It shines in the moonlight. Find the next one.' },
{ at: [8, 1, 5], hint: 'Find the next white pebble.', say: 'Another white pebble! Keep going.' },
{ at: [11, 1, 7], hint: 'Find the next white pebble.', say: 'Another one! You are on the right path.' },
{ at: [9, 1, 9], hint: 'Find the next white pebble.', say: 'One more pebble to go!' },
{ at: [12, 1, 11], hint: 'Find the last white pebble.', say: 'The last pebble! Look: a little house made of bread and cake!' },
{ id: 60, hint: 'Find the treasure chest inside the gingerbread house.', say: 'Pearls and jewels! Now Hansel and Grethel can go home to their father.' }],
win: 'You found your way! You earned a Gingerbread Heart, and a Gingerbread House kit to build at home.' },
// Grimm batch 2 (ABC Books lessons 57-88, 2026-10-24)
{ id: 'wolf', abc: 'The Wolf and the Seven Little Kids', title: 'The Wolf and the Seven Little Kids', place: "The Goats' Cottage", keep: 'Goat Bell', color: '#d8d0c0', parts: [57, 4],
ach: ['Hide and Seek Champion', 'You found all seven. The clock was the best hiding place.'],
sum: 'The Wolf and the Seven Little Kids. A mother goat has seven little kids. While she is out, the wolf tricks them with a soft voice and white paws. Only the youngest, hiding in the clock-case, is not caught. Mother Goat saves them all, the wolf falls into the well, and the goats dance around it for joy!',
quest: 'Your quest: the little goats are hiding! Find the youngest one in the clock first, then find the other six, then find Mother Goat by the well.',
steps: [{ at: [13, 2, 14], hint: 'Find the youngest little goat. She is hiding in the tall clock.', say: 'Here I am, in the clock! Please help me find my brothers and sisters.' },
{ id: 84, n: 6, hint: 'Find the other six little goats. They are hiding in and around the cottage.', say: ['Found one! Five more little goats to find.', 'Found another! Four more to find.', 'Found another! Three more to find.', 'Found another! Two more to find.', 'Found another! Just one more to find.', 'You found them all! Now find Mother Goat by the well.'] },
{ id: 85, hint: 'Find Mother Goat by the well.', say: 'Mother Goat hugs all seven little goats. The wolf fell into the well, and everyone dances for joy!' }],
win: 'The little goats are safe! You earned the Goat Bell, and a Goats\' Cottage kit to build at home.' },
{ id: 'snow', abc: 'Little Snow-white', title: 'Little Snow-white', place: "The Seven Dwarfs' Cottage", keep: 'Little Mirror', color: '#3a5ac8', parts: [61, 12],
ach: ['Seventh Little Bed', 'Too long, too short... the seventh bed was just right.'],
sum: 'Little Snow-white. A queen with a magic mirror is jealous, because Snow-white is the fairest of them all. Snow-white runs into the forest and finds the little house of the seven dwarfs, who dig for gold in the mountains. The queen tricks her with a poisoned apple, but a king\'s son comes, the piece of apple falls out, and Snow-white wakes up.',
quest: 'Your quest: find the dwarfs\' little table, try the seven little beds, and visit the dwarfs in their mine.',
steps: [{ id: 19, hint: 'Find the little table in the dwarfs\' cottage.', say: 'Seven little plates and seven little cups! Snow-white eats a little bit from each plate.' },
{ id: 31, hint: 'Find the seven little beds.', say: 'This bed is too long, this one is too short, but the seventh bed is just right. Snow-white falls asleep.' },
{ id: 56, hint: 'Find the dwarfs\' mine in the mountain behind the cottage.', say: 'The seven dwarfs dig for gold in the mountain. When they come home, they find Snow-white and say she can stay!' }],
win: 'Snow-white has a new home with the dwarfs! You earned the Little Mirror, and a Seven Dwarfs\' Cottage kit to build at home.' },
{ id: 'goose', abc: 'The Golden Goose', title: 'The Golden Goose', place: 'The Golden Goose Wood', keep: 'Golden Feather', color: '#e8b830', parts: [73, 4],
ach: ['Princess Giggler', 'Seven people stuck to one goose. Even the king laughed.'],
sum: 'The Golden Goose. The youngest of three brothers, called Simpleton, shares his poor cake with a little grey man in the forest. In return he finds a goose with feathers of pure gold in the roots of an old tree. Everyone who touches the goose gets stuck to it, and the long, silly line makes a sad princess laugh, so Simpleton marries her.',
quest: 'Your quest: share your cake with the little grey man, find the golden goose in the old tree, and make the sad princess laugh.',
steps: [{ at: [8, 1, 6], hint: 'Find your basket of cake by the path.', say: 'You share your cake with the little grey man. He says: cut down the old tree, and you will find something in its roots.' },
{ id: 86, hint: 'Find the golden goose in the roots of the old tree.', say: 'A goose with feathers of pure gold! Careful: anyone who touches it gets stuck.' },
{ id: 57, hint: 'Take the goose to the castle and find the princess on her golden throne.', say: 'A long line of people is stuck to the goose! The sad princess laughs and laughs.' }],
win: 'The princess is laughing! You earned a Golden Feather, and a Golden Goose Wood kit to build at home.' },
{ id: 'shoes', abc: 'The Shoes That Were Danced to Pieces', title: 'The Dancing Shoes', place: 'The Midnight Ballroom', keep: 'Silver Twig', color: '#9a7ad8', parts: [77, 5],
ach: ['Midnight Dancer', 'Your shoes are full of holes. Totally worth it.'],
sum: 'The Dancing Shoes. Every morning, the shoes of the king\'s twelve daughters are danced to pieces, and nobody knows why. A soldier with a cloak that makes him invisible follows them at night, down secret stairs, through woods with leaves of silver, gold and diamonds, and across a lake to a castle where they dance all night. He breaks off little twigs to show the king, and the secret is out.',
quest: 'Your quest: follow the princesses through the silver wood, the golden wood and the diamond wood, then find the ballroom across the lake.',
steps: [{ id: 89, hint: 'Find the tree with leaves of silver.', say: 'Leaves of silver! You break off a little twig. Crack!' },
{ id: 90, hint: 'Find the tree with leaves of gold.', say: 'Leaves of gold! Crack! The youngest princess says: did you hear that?' },
{ id: 91, hint: 'Find the tree with leaves of diamonds.', say: 'Leaves of diamonds, sparkling in the dark! Crack!' },
{ id: 87, hint: 'Cross the lake and find the dancing shoes in the ballroom.', say: 'Music! The twelve princesses dance all night, until their shoes are full of holes.' }],
win: 'You found out the secret! You earned the Silver Twig, and a Midnight Ballroom kit to build at home.' },
{ id: 'thumb', abc: 'Thumbling', title: 'Thumbling', place: "Thumbling's Farm", keep: 'Snail Shell', tile: 'snail', color: '#8ab04a', parts: [82, 7],
ach: ['Tiny Traveller', 'A very big adventure for someone no bigger than a thumb.'],
sum: 'Thumbling. A poor farmer and his wife wish for a child, even a tiny one, and they get a boy no bigger than a thumb. Thumbling drives the cart by sitting in the horse\'s ear, gets sold to two strangers, hides in a mouse-hole and a snail shell, and is swallowed by a cow and a wolf. But he always has a clever plan, and at last he gets home to his father and mother.',
quest: 'Your quest: find where tiny Thumbling hid in the field, find the hay he slept in, and bring him home to his father and mother.',
steps: [{ id: 88, hint: 'Find the empty snail shell in the field.', say: 'Thumbling hides inside the empty snail shell. Nobody can find him in there!' },
{ id: 67, hint: 'Find the soft hay in the barn.', say: 'Thumbling falls asleep in the soft hay. Uh oh, here comes the cow!' },
{ id: 20, hint: 'Find the warm fire in the little house.', say: 'Thumbling is home again! His father and mother give him food and new clothes.' }],
win: 'Thumbling is home safe! You earned the Snail Shell, and a Thumbling\'s Farm kit to build at home.' },
// Grimm batch 3 (ABC Books lessons 89-140, 2026-10-25): built from the PLACE_TPL templates plus a few props
{ id: 'catmouse', abc: 'Cat and Mouse in Partnership', title: 'Cat and Mouse in Partnership', place: "The Cat and Mouse's House", keep: 'Little Pot', color: '#b07a50', parts: [89, 4],
tpl: 'cottage', props: [[3, 1, 9, 34], [3, 2, 9, 48], [3, 1, 10, 21], [2, 1, 9, 22], [4, 1, 9, 22]],
ach: ['Pot Keeper', 'Top-off, Half-done, All-gone. Who ate the fat? Not you!'],
sum: 'Cat and Mouse in Partnership. A cat and a mouse keep house together, and hide a pot of fat by the church altar for the winter. Three times the cat sneaks away, saying she is going to a christening, and licks up the fat: Top-off, Half-done, All-gone! When the mouse finds out, the cat gobbles her up. That is the way of the world.',
quest: 'Your quest: find the pot of fat by the little altar, find where the sneaky cat naps, and look at the empty table when winter comes.',
steps: [{ at: [3, 1, 10], hint: 'Find the pot of fat hidden in the chest by the little altar.', say: 'Here is the pot of fat, hidden by the altar to keep it safe for the winter.' },
{ id: 31, hint: 'Find the cat\'s bed in the house.', say: 'Three times the cat sneaks off and licks the fat. She calls the kittens Top-off, Half-done and All-gone!' },
{ id: 19, hint: 'Find the table in the house.', say: 'Winter comes, and the pot is empty! When the mouse finds out, the cat gobbles her up. That is the way of the world.' }],
win: 'You found out the sneaky cat! You earned the Little Pot, and a Cat and Mouse\'s House kit to build at home.' },
{ id: 'ladychild', abc: "Our Lady's Child", title: "Our Lady's Child", place: 'The Thirteen Doors', keep: 'Golden Key', color: '#7aa0e0', parts: [93, 6],
tpl: 'palace', wall: 51, props: [[14, 4, 18, 49]],
ach: ['Truth Teller', 'Thirteen doors, and you only opened the right ones.'],
sum: 'Our Lady\'s Child. The Virgin Mary takes a poor woodcutter\'s little girl up to heaven, and gives her the keys to thirteen doors, but the thirteenth door is forbidden. The girl opens it anyway, and then says no, I did not, three times. She has to leave heaven and cannot speak. A king finds her and marries her, but only when she tells the truth at last do the rain and kindness come.',
quest: 'Your quest: climb the shining stairs, find the glowing thirteenth door, visit the hollow tree, then tell the truth at the golden throne.',
steps: [{ at: [10, 3, 13], hint: 'Climb the shining stairs to the top step.', say: 'High up in heaven, the girl eats sweet cakes, drinks sweet milk, and wears clothes of gold.' },
{ at: [14, 4, 18], hint: 'Find the glowing thirteenth door inside.', say: 'She opens the forbidden thirteenth door! The light is so bright, and her finger turns to gold.' },
{ at: [4, 1, 5], hint: 'Find the old hollow tree outside.', say: 'Sent away from heaven, she lives for years in a hollow tree, until a king finds her and takes her home as his queen.' },
{ at: [10, 4, 18], hint: 'Go to the golden throne and tell the truth.', say: 'Yes, I opened the door, she says at last. Rain falls, and everything she lost is given back to her.' }],
win: 'The truth is told! You earned the Golden Key, and a Thirteen Doors kit to build at home.' },
{ id: 'shudder', abc: 'The Story of the Youth Who Went Forth to Learn What Fear Was', title: 'The Youth Who Learned Fear', place: 'The Haunted Castle', keep: 'Bucket of Little Fish', color: '#4a4a6a', parts: [99, 12],
tpl: 'castle', wall: 54, props: [[6, 1, 15, 20], [14, 1, 15, 31], [6, 1, 11, 59]],
ach: ['Not Even a Shudder', 'Black cats, rolling beds, haunted halls. Yawn.'],
sum: 'The Youth Who Learned Fear. A young man does not know what fear is, and he wants to learn to shudder. He spends three nights in a haunted castle, where very strange things happen, but nothing scares him, so he wins the king\'s daughter. At last, his wife pours a bucket of cold water full of little fish over him in bed, and he cries: Oh, now I know what shuddering is!',
quest: 'Your quest: spend the night in the haunted castle. Sit by the fire, try the rolling bed, find the king\'s gold, then find the icy cold water.',
steps: [{ id: 20, hint: 'Light the fire in the haunted hall.', say: 'Oh, if I could but shudder! says the youth by the fire. Two big black cats come to play cards with him, but he is not afraid at all.' },
{ id: 31, hint: 'Find the bed in the castle.', say: 'The bed rolls all around the castle by itself! Faster! says the youth. He is still not afraid.' },
{ at: [10, 1, 17], hint: 'Find the king\'s gold by the throne.', say: 'After three nights, he wins the gold and the king\'s daughter. But he still cannot shudder!' },
{ id: 59, hint: 'Find the bucket of icy cold water.', say: 'His wife pours cold water full of little fish over him in bed. Oh, I shudder! he cries. Now I know what shuddering is!' }],
win: 'Brrr! You earned the Bucket of Little Fish, and a Haunted Castle kit to build at home.' },
{ id: 'john', abc: 'Faithful John', title: 'Faithful John', place: 'The Golden Dome', keep: 'Golden Cup', color: '#d8a838', parts: [111, 10],
tpl: 'palace', props: [[6, 4, 17, 57], [14, 4, 16, 3], [14, 5, 16, 3]],
ach: ['Faithful Friend', 'Three ravens, three dangers, one very loyal friend.'],
sum: 'Faithful John. An old servant promises a dying king to look after his son. He helps the young king win the princess of the Golden Dome with a ship full of golden things. Three ravens tell of three dangers, and John saves the king from each one, even though it turns him to stone. In the end, the king\'s love brings faithful John back to life.',
quest: 'Your quest: climb to the golden palace, find the golden treasures, listen to the three ravens, and find the stone statue of Faithful John.',
steps: [{ at: [10, 3, 13], hint: 'Climb the stairs to the golden palace.', say: 'Faithful John brings the young king here on a ship full of golden things, to meet the princess of the Golden Dome.' },
{ at: [6, 4, 17], hint: 'Find the golden treasures inside.', say: 'The princess loves the golden cups and birds so much that she comes to see them all, and sails away to be the king\'s bride.' },
{ at: [16, 1, 5], hint: 'Listen to the three ravens in the tree outside.', say: 'Three ravens tell of three dangers. Faithful John hears them, and he saves the king every time.' },
{ at: [14, 4, 16], hint: 'Find the stone statue of Faithful John.', say: 'Faithful John turned to stone for his king. Because the king loves him so much, John comes back to life!' }],
win: 'Faithful John is back! You earned the Golden Cup, and a Golden Dome kit to build at home.' },
{ id: 'bargain', abc: 'The Good Bargain', title: 'The Good Bargain', place: 'The Frog Pond', keep: 'Lucky Coin', color: '#5a9a3a', parts: [121, 7],
tpl: 'well', props: [[12, 2, 8, 81], [15, 1, 11, 57], [15, 2, 11, 48]],
ach: ['Frog Counter', 'Aik, aik! You counted better than the farmer.'],
sum: 'The Good Bargain. A silly farmer sells his cow and walks home past a pond. The frogs cry aik, aik, and he thinks they are counting his money wrong, so he throws it all in for them to count again. He gets into one silly muddle after another, and makes the king\'s daughter, who has never laughed, laugh out loud.',
quest: 'Your quest: visit the farmer\'s little house, find the frog by the well, and find the princess\'s golden seat.',
steps: [{ id: 31, hint: 'Find the farmer\'s bed in his little house.', say: 'A farmer sells his cow for seven coins and walks home past the frog pond.' },
{ at: [12, 2, 8], hint: 'Find the frog on the edge of the well.', say: 'Aik, aik! cry the frogs. The silly farmer thinks they are counting wrong, and throws his coins into the water for them to count again!' },
{ id: 57, hint: 'Find the king\'s daughter\'s golden seat.', say: 'The king\'s daughter has never laughed in her life, but the silly farmer makes her laugh out loud!' }],
win: 'The princess is laughing! You earned the Lucky Coin, and a Frog Pond kit to build at home.' },
{ id: 'fiddler', abc: 'The Wonderful Musician', title: 'The Wonderful Musician', place: "The Fiddler's Wood", keep: 'Little Fiddle', color: '#7a5a3a', parts: [128, 4],
tpl: 'forest', props: [[15, 1, 17, 19]],
ach: ['Forest Fiddler', 'The wolf did not enjoy the concert. The woodcutter did.'],
sum: 'The Wonderful Musician. A fiddler walks alone through the forest and plays to find a friend. A wolf, a fox and a hare come, but he tricks each of them and goes on playing. Angry, they come after him, but his music brings a kind woodcutter with his axe, and the animals run away.',
quest: 'Your quest: find where the fiddler plays, find the old tree by the path, and find the woodcutter\'s bench.',
steps: [{ at: [12, 1, 17], hint: 'Find the old stump in the clearing.', say: 'A fiddler sits here and plays so sweetly that a wolf, a fox and a hare come running to listen.' },
{ at: [10, 1, 8], hint: 'Find the old tree by the path.', say: 'The fiddler tricks the wolf into putting his paws in a split tree, and goes on his way, playing.' },
{ id: 19, hint: 'Find the woodcutter\'s bench.', say: 'The fiddler plays again, and a kind woodcutter comes with his axe. The wolf, the fox and the hare run away, and the woodcutter stays to listen.' }],
win: 'What lovely music! You earned the Little Fiddle, and a Fiddler\'s Wood kit to build at home.' },
{ id: 'twelvebro', abc: 'The Twelve Brothers', title: 'The Twelve Brothers', place: "The Twelve Brothers' House", keep: 'Lily', color: '#4a6aa0', parts: [132, 7],
tpl: 'cottage', props: [[2, 1, 8, 36], [4, 1, 8, 36], [2, 1, 13, 36], [4, 1, 13, 36], [16, 1, 7, 36], [18, 1, 8, 36], [16, 1, 12, 36], [18, 1, 13, 36], [8, 1, 17, 36], [12, 1, 17, 36]],
ach: ['Twelve Lilies', 'Seven years without a word. You could not even last seven minutes.'],
sum: 'The Twelve Brothers. Twelve princes run away to a little house deep in the wood. Years later, their little sister finds them. But when she picks twelve lilies, her brothers turn into ravens! To free them, she must not speak or laugh for seven years. She keeps quiet even when a king marries her and she is in great danger, and at the very end her brothers come back.',
quest: 'Your quest: find the brothers\' little house, pick the twelve lilies, and find the sister\'s bed.',
steps: [{ id: 19, hint: 'Find the table in the little house in the wood.', say: 'Twelve brothers live in this little house deep in the wood. Their little sister finds them, and they are so happy!' },
{ id: 36, n: 12, hint: 'Pick the twelve lilies in the garden.', say: [...Array(11)].map((_, k) => 'A lily! ' + (11 - k) + ' more to pick.').concat('The twelfth lily! Oh no, the brothers turn into twelve ravens and fly away!') },
{ id: 31, hint: 'Find the sister\'s bed.', say: 'For seven years the sister does not speak or laugh. Then her brothers are set free and come home!' }],
win: 'The twelve brothers are home! You earned the Lily, and a Twelve Brothers\' House kit to build at home.' },
{ id: 'ragamuffin', abc: 'The Pack of Ragamuffins', title: 'The Pack of Ragamuffins', place: 'The Inn on the Hill', keep: 'Nutshell', color: '#c08040', parts: [139, 3],
tpl: 'cottage', roof: 40, props: [[3, 1, 10, 77]],
ach: ['Ragamuffin', 'An egg, a pin and a needle. Poor innkeeper.'],
sum: 'The Pack of Ragamuffins. A cock and a hen go up the hill to eat nuts, and build a little carriage from a nutshell. A duck pulls it, and they pick up a pin and a needle on the way. At the inn they play tricks on the innkeeper, and run off early in the morning without paying.',
quest: 'Your quest: find the nutshell carriage, find the bed at the inn, and find the fire where the tricks begin.',
steps: [{ at: [3, 1, 10], hint: 'Find the little carriage made from a nutshell.', say: 'The cock and the hen build a little carriage from a nutshell, and a duck pulls it to the inn.' },
{ id: 31, hint: 'Find the bed at the inn.', say: 'Early in the morning, the cock and the hen eat the egg and throw the shell into the fire. They stick a pin and a needle where the innkeeper will sit!' },
{ id: 20, hint: 'Find the fire at the inn.', say: 'Ouch! The eggshell flies out of the fire, the needle pricks, and the pin scratches. The ragamuffins are long gone!' }],
win: 'What a pack of ragamuffins! You earned the Nutshell, and an Inn on the Hill kit to build at home.' },
// template places, chunk 2 (ABC Books lessons 142-195, 2026-10-25)
{ id: 'brosis', abc: 'Little Brother and Little Sister', title: 'Little Brother and Little Sister', place: 'The Little House in the Wood', keep: 'Golden Collar', color: '#8a6a3a', parts: [142, 10],
tpl: 'cottage', wall: 6, props: [[2, 0, 8, 10], [3, 1, 8, 4], [2, 1, 9, 4], [3, 1, 9, 4]],
ach: ['Deer Friend', 'You did not drink from the spring. Very wise.'],
sum: 'Little Brother and Little Sister. A brother and sister run away from their wicked stepmother into the forest. She has put a spell on the springs, and when the brother drinks, he turns into a little roe-deer. The sister looks after him in a little house in the wood, a king finds them and marries her, and in the end the spell is broken.',
quest: 'Your quest: find the enchanted spring, find the little deer\'s bed, and find the table where the king finds them.',
steps: [{ at: [3, 1, 9], hint: 'Find the stones by the little spring.', say: 'Whoever drinks from me becomes a roe-deer, whispers the spring. The brother drinks, and turns into a little deer!' },
{ id: 31, hint: 'Find the soft bed in the little house.', say: 'Sister and the little deer live together in the little house in the wood. At night he sleeps with his head on her lap.' },
{ id: 19, hint: 'Find the table in the little house.', say: 'The king finds the sister and the little deer, and takes them to his palace. In the end the spell is broken, and the deer is her brother again!' }],
win: 'Brother and sister are together again! You earned the Golden Collar, and a Little House in the Wood kit to build at home.' },
{ id: 'threemen', abc: 'The Three Little Men in the Wood', title: 'The Three Little Men in the Wood', place: "The Three Little Men's House", keep: 'Ripe Strawberry', color: '#c03040', parts: [152, 7],
tpl: 'cottage', roof: 51, props: [[3, 1, 9, 51], [4, 1, 9, 51], [4, 1, 10, 36]],
ach: ['Kind Sweeper', 'Strawberries in winter. Sharing pays.'],
sum: 'The Three Little Men in the Wood. A wicked stepmother sends a girl into the snowy forest in a paper dress to look for strawberries. She shares her dry bread with three little men and sweeps the snow from their door, so they give her gifts: she grows prettier every day, gold coins fall from her mouth when she speaks, and she becomes a queen. Her rude stepsister gets toads instead!',
quest: 'Your quest: share your bread at the little men\'s table, sweep away the snow behind the house, and find the strawberries under it.',
steps: [{ id: 19, hint: 'Find the little men\'s table.', say: 'The girl shares her dry bread with the three little men, even though she is hungry herself.' },
{ at: [4, 1, 9], hint: 'Find the snow behind the house and sweep it away.', say: 'She sweeps away the snow by the back door. What is under it?' },
{ at: [4, 1, 10], hint: 'Find the strawberries under the snow.', say: 'Ripe red strawberries, in the middle of winter! And the three little men give her three wonderful gifts.' }],
win: 'Kindness wins! You earned the Ripe Strawberry, and a Three Little Men\'s House kit to build at home.' },
{ id: 'spinners', abc: 'The Three Spinners', title: 'The Three Spinners', place: 'The Flax Rooms', keep: 'Spindle', color: '#c8b070', parts: [159, 3],
tpl: 'castle', props: [[6, 1, 12, 67], [7, 1, 12, 67], [6, 2, 12, 67], [6, 1, 13, 67], [13, 1, 12, 68]],
ach: ['Flax Helper', 'Broad foot, big lip, broad thumb, and lots of flax.'],
sum: 'The Three Spinners. A girl who does not like spinning is taken to a queen, who fills three rooms with flax and says: spin it all, and you shall marry my son. Three strange women come to help: one has a broad foot, one a big lip, and one a broad thumb. They spin all the flax, and ask only to come to the wedding. When the prince sees them, he says his bride shall never spin again.',
quest: 'Your quest: find the rooms full of flax, find the spinning wheel, and go to the wedding at the throne.',
steps: [{ id: 67, hint: 'Find the flax in the castle.', say: 'Three whole rooms full of flax! Spin it all, says the queen, and you can marry my son.' },
{ id: 68, hint: 'Find the spinning wheel.', say: 'Three strange women come to help. One has a broad foot, one a big lip, and one a broad thumb. They spin all the flax!' },
{ at: [10, 1, 17], hint: 'Go to the wedding at the throne.', say: 'The three spinners come to the wedding. The prince sees how spinning changed them, and says: my bride shall never spin again!' }],
win: 'Happy wedding! You earned the Spindle, and a Flax Rooms kit to build at home.' },
{ id: 'snakeleaves', abc: 'The Three Snake-Leaves', title: 'The Three Snake-Leaves', place: 'The Royal Vault', keep: 'Three Green Leaves', color: '#3a7a3a', parts: [162, 5],
tpl: 'castle', wall: 4, props: [[12, 1, 14, 7], [13, 1, 14, 7], [14, 1, 14, 7], [7, 1, 15, 31]],
ach: ['Leaf Healer', 'Three little leaves, and everyone wakes up.'],
sum: 'The Three Snake-Leaves. A brave young soldier marries a king\'s daughter, who makes him promise that if one of them dies, the other must stay in the grave too. In the dark royal vault he sees a snake bring three green leaves to another snake, and it wakes up again. With the magic leaves he brings his wife back to life. Later she is unkind to him, but his faithful servant saves him with the same leaves.',
quest: 'Your quest: go to the king\'s throne, find the three magic snake leaves in the vault, and wake the princess.',
steps: [{ at: [10, 1, 17], hint: 'Find the king\'s throne.', say: 'A brave young soldier marries the king\'s daughter. She makes him promise: if one of us dies, the other must stay in the grave too.' },
{ at: [13, 1, 14], hint: 'Find the three green snake leaves.', say: 'In the dark vault, a snake brings three green leaves and lays them on another snake, and it wakes up! The leaves are magic.' },
{ id: 31, hint: 'Find the princess resting in the vault.', say: 'He lays the three leaves on the princess, and she wakes up, alive and well!' }],
win: 'Magic leaves! You earned the Three Green Leaves, and a Royal Vault kit to build at home.' },
{ id: 'whitesnake', abc: 'The White Snake', title: 'The White Snake', place: "The White Snake's Stream", keep: 'Apple of Life', color: '#e8e8e8', parts: [167, 6],
tpl: 'mill', props: [[10, 1, 10, 57]],
ach: ['Animal Talker', 'The fish, the ants and the ravens all say thank you.'],
sum: 'The White Snake. A servant tastes the king\'s secret dish, a white snake, and suddenly he can understand what animals say. He helps some fish, some ants and three young ravens. Later a princess gives him three hard tasks: find a ring in the sea, pick up ten sacks of spilled millet, and bring an apple from the Tree of Life. His animal friends do each task for him, and he marries the princess.',
quest: 'Your quest: find the golden ring the fish brings, find the sacks of millet in the mill, and find the tree where the ravens bring the apple of life.',
steps: [{ at: [10, 1, 10], hint: 'Find the golden ring on the bridge.', say: 'A fish he saved swims up with the golden ring from the bottom of the water!' },
{ id: 67, hint: 'Find the sacks of millet in the mill.', say: 'Ten sacks of millet are spilled in the grass. The ants he saved pick up every last grain!' },
{ at: [17, 1, 4], hint: 'Find the tree where the ravens bring the apple.', say: 'Three ravens fly over the sea and bring back an apple from the Tree of Life. He shares it with the princess!' }],
win: 'The animals helped! You earned the Apple of Life, and a White Snake\'s Stream kit to build at home.' },
{ id: 'strawcoal', abc: 'The Straw, the Coal, and the Bean', title: 'The Straw, the Coal, and the Bean', place: 'The Little Brook', keep: 'Bean', color: '#6a4a2a', parts: [173, 2],
tpl: 'mill', roof: 40, props: [[6, 0, 9, 67], [6, 0, 10, 67], [6, 0, 11, 67], [6, 1, 15, 20], [10, 1, 14, 19]],
ach: ['Black Seam', 'That is why beans have a black seam. Now you know.'],
sum: 'The Straw, the Coal, and the Bean. A straw, a burning coal and a bean escape from an old woman\'s fire and go off together. At a little brook, the straw lies across the water as a bridge. The coal walks onto it but gets scared in the middle, the straw burns through, and both fall into the water. The bean laughs so hard that she bursts, and a kind tailor sews her up with black thread.',
quest: 'Your quest: find the old woman\'s fire, find the straw bridge over the brook, and find the tailor\'s table.',
steps: [{ id: 20, hint: 'Find the old woman\'s fire in the mill house.', say: 'A straw, a coal and a bean jump away from the old woman\'s fire, and set off together.' },
{ at: [6, 0, 10], hint: 'Find the straw lying across the brook.', say: 'The straw lies across the brook as a bridge. The coal stops in the middle, the straw burns, and splash! Both fall into the water.' },
{ id: 19, hint: 'Find the tailor\'s table.', say: 'The bean laughs so hard that she bursts! A kind tailor sews her up with black thread, and that is why beans have a black seam.' }],
win: 'Ha ha! You earned the Bean, and a Little Brook kit to build at home.' },
{ id: 'fisherman', abc: 'The Fisherman and His Wife', title: 'The Fisherman and His Wife', place: "The Fisherman's Wishes", keep: 'Magic Flounder', color: '#2a6aa0', parts: [175, 11],
tpl: 'palace', props: [[2, 0, 2, 10], [3, 0, 2, 10], [2, 0, 3, 10], [3, 0, 3, 10], [4, 1, 3, 6], [16, 1, 2, 5], [17, 1, 2, 5], [16, 2, 2, 5], [17, 2, 2, 5]],
ach: ['Enough Is Enough', 'A cottage, a castle, a palace... and back to the old hut.'],
sum: 'The Fisherman and His Wife. A poor fisherman catches a flounder that is really an enchanted prince, and lets it go. His wife sends him back to wish for a cottage, then a castle, then to be king, emperor and pope. Each time she gets it, and each time the sea grows darker. When she wants to be like God himself, they are back in their little old hut.',
quest: 'Your quest: find the fishing spot by the water, find the fisherman\'s old hut, and climb to the golden throne.',
steps: [{ at: [4, 1, 3], hint: 'Find the fishing spot by the water.', say: 'The fisherman catches a big flounder. I am an enchanted prince, says the fish, so he lets it go.' },
{ at: [16, 1, 2], hint: 'Find the fisherman\'s old hut.', say: 'His wife says: go back and wish for a cottage! Then a castle! Then to be king, emperor and pope!' },
{ at: [10, 4, 18], hint: 'Climb to the golden throne in the palace.', say: 'Now she wants to be like God himself! The sea turns black and wild, and they are back in their little old hut.' }],
win: 'Back to the old hut! You earned the Magic Flounder, and a Fisherman\'s Wishes kit to build at home.' },
{ id: 'bravetailor', abc: 'The Valiant Little Tailor', title: 'The Valiant Little Tailor', place: "The Giants' Wood", keep: "Tailor's Belt", color: '#6a8a3a', parts: [186, 10],
tpl: 'forest',
ach: ['Seven at One Blow', 'Flies, giants, a unicorn and a wild boar. Not bad for a tailor.'],
sum: 'The Valiant Little Tailor. A little tailor swats seven flies on his bread and jam, and stitches Seven at One Blow on his belt. Everyone thinks he means seven men! He tricks two giants into fighting each other, catches a unicorn and a wild boar with clever plans, and wins the king\'s daughter and half the kingdom.',
quest: 'Your quest: find the tailor\'s bread and jam, find the tree where the giants sleep, and find the tree where the unicorn got stuck.',
steps: [{ at: [12, 1, 17], hint: 'Find the old stump where the tailor eats his bread and jam.', say: 'Flies land on the tailor\'s bread and jam. Swat! Seven at one blow! He stitches it on his belt.' },
{ at: [10, 1, 14], hint: 'Find the tree where the giants sleep.', say: 'The tailor climbs the tree and drops stones on the sleeping giants, so they fight each other!' },
{ at: [3, 1, 15], hint: 'Find the tree where the unicorn got stuck.', say: 'The unicorn runs at the tailor and gets its horn stuck in a tree! The clever tailor wins the princess.' }],
win: 'Seven at one blow! You earned the Tailor\'s Belt, and a Giants\' Wood kit to build at home.' },
// template places, chunk 3 (ABC Books lessons 196-232, 2026-10-25)
{ id: 'riddle', abc: 'The Riddle', title: 'The Riddle', place: 'The Riddle Castle', keep: 'Misty Grey Cloak', color: '#8a8aa0', parts: [196, 4],
tpl: 'castle', props: [[7, 1, 14, 31], [13, 1, 14, 21]],
ach: ['Riddle Master', 'One killed none, and yet killed twelve. Can you guess it?'],
sum: 'The Riddle. A king\'s son and his servant have a strange adventure with a witch\'s poisoned drink. Then the prince comes to a princess who will marry anyone who asks her a riddle she cannot answer. She tries to cheat by listening while he sleeps, but he is only pretending, and he keeps her misty grey cloak to prove it. So he wins her!',
quest: 'Your quest: ask the princess your riddle at her throne, find the prince\'s bed, and find the misty grey cloak.',
steps: [{ at: [10, 1, 17], hint: 'Find the princess on her throne.', say: 'The prince asks his riddle: One killed none, and yet killed twelve. What is it? The princess cannot guess!' },
{ id: 31, hint: 'Find the prince\'s bed.', say: 'At night someone creeps in to hear the answer while the prince sleeps. But he is only pretending to sleep!' },
{ id: 21, hint: 'Find the chest with the misty grey cloak.', say: 'Here is the misty grey cloak the princess wore when she crept in. Now everyone knows she cheated, and the prince wins!' }],
win: 'Riddle solved! You earned the Misty Grey Cloak, and a Riddle Castle kit to build at home.' },
{ id: 'sausage', abc: 'The Mouse, the Bird, and the Sausage', title: 'The Mouse, the Bird, and the Sausage', place: 'The Little Shared House', keep: 'Little Sausage', color: '#c06040', parts: [200, 3],
tpl: 'well', roof: 33,
ach: ['Stick to Your Job', 'The bird fetched wood, the mouse fetched water, the sausage cooked. Then they swapped.'],
sum: 'The Mouse, the Bird, and the Sausage. A mouse, a bird and a sausage keep house together. The bird fetches wood, the mouse fetches water and lights the fire, and the sausage cooks. They are very happy, until the bird decides they should swap jobs. Then everything goes badly wrong, for every one of them.',
quest: 'Your quest: find the tree where the bird gets wood, find the cooking fire in the little house, and find the well.',
steps: [{ at: [4, 1, 5], hint: 'Find the tree where the bird gathers wood.', say: 'Every day the bird flies to the forest to fetch wood. The mouse carries water, and the sausage cooks.' },
{ id: 20, hint: 'Find the cooking fire in the little house.', say: 'The sausage cooks by sliding through the pot, so the food is always tasty!' },
{ at: [12, 1, 8], hint: 'Find the well.', say: 'One day they swap jobs, and everything goes wrong. Nobody does their own job any more, and the bird falls into the well!' }],
win: 'Now you know: stick to your own job! You earned the Little Sausage, and a Little Shared House kit to build at home.' },
{ id: 'ravens', abc: 'The Seven Ravens', title: 'The Seven Ravens', place: 'The Glass Mountain', keep: 'Little Ring', color: '#3a3a4a', parts: [203, 4],
tpl: 'castle', wall: 11, props: [[6, 1, 15, 49], [10, 1, 13, 19]],
ach: ['Glass Mountain Climber', 'Seven little plates, seven little cups, one brave sister.'],
sum: 'The Seven Ravens. An angry father wishes that his seven sons were ravens, and away they fly. Their little sister goes all the way to the end of the world to find them. The sun is too hot and the moon is unkind, but the morning star gives her a little chicken bone to open the glass mountain. Inside, she drops her ring into the ravens\' cup, and her brothers become boys again.',
quest: 'Your quest: find the shining morning star, find the ravens\' little table, and find the golden ring for her brothers.',
steps: [{ id: 49, hint: 'Find the shining morning star inside the glass mountain.', say: 'The kind morning star gives her a little chicken bone. It is the key to the glass mountain!' },
{ id: 19, hint: 'Find the ravens\' little table.', say: 'A dwarf sets out seven little plates and seven little cups. The girl eats a bite from each plate and drops her ring into the last cup.' },
{ at: [10, 1, 17], hint: 'Find the gold where the ravens come home.', say: 'The ravens come home and find their sister\'s ring. They turn back into her brothers, and they all go home together!' }],
win: 'The brothers are free! You earned the Little Ring, and a Glass Mountain kit to build at home.' },
{ id: 'singingbone', abc: 'The Singing Bone', title: 'The Singing Bone', place: 'The Bridge of the Singing Bone', keep: 'Little Horn', color: '#e8e0c8', parts: [207, 3],
tpl: 'mill', props: [[11, 1, 14, 57]],
ach: ['Truth Will Out', 'Even a little bone can tell the truth.'],
sum: 'The Singing Bone. A king promises his daughter to whoever kills a fierce wild boar. A little man gives the brave younger brother a spear, and he kills it. But his jealous older brother kills him, buries him under a bridge, and takes the prize. Years later a shepherd makes a horn from a little white bone, and the horn sings the whole truth.',
quest: 'Your quest: find the tree where the little man gives the spear, find the bridge over the brook, and play the horn at the king\'s gold.',
steps: [{ at: [3, 1, 4], hint: 'Find the tree where the little man gives the spear.', say: 'A little man gives the younger brother a black spear, and he bravely kills the wild boar.' },
{ at: [10, 0, 10], hint: 'Find the bridge over the brook.', say: 'Years later, a shepherd finds a little white bone under the bridge, and makes a mouthpiece for his horn.' },
{ id: 57, hint: 'Take the horn to the king\'s gold in the mill house.', say: 'The horn sings: Ah, friend, thou blowest upon my bone! It tells the whole truth, and the wicked brother is found out.' }],
win: 'The truth is out! You earned the Little Horn, and a Bridge of the Singing Bone kit to build at home.' },
{ id: 'goldenhairs', abc: 'The Devil With the Three Golden Hairs', title: 'The Devil With the Three Golden Hairs', place: "The Dry Fountain", keep: 'Golden Hair', color: '#c84020', parts: [210, 9],
tpl: 'well', wall: 33, roof: 33,
ach: ['Lucky Child', 'Born lucky. Also very good at asking questions.'],
sum: 'The Devil With the Three Golden Hairs. A boy born lucky is meant to marry the king\'s daughter, but the angry king sends him to fetch three golden hairs from the devil\'s head. On the way people ask him: why has our fountain dried up, why does our tree give no golden apples, and why must the ferryman row forever? The devil\'s kind grandmother pulls out the hairs and learns all the answers.',
quest: 'Your quest: find the fountain that dried up, find the tree that gives no golden apples, and find the devil\'s grandmother by the fire.',
steps: [{ at: [12, 1, 8], hint: 'Find the fountain that has dried up.', say: 'In one town the fountain has dried up. There is a toad under a stone, says the devil in his sleep.' },
{ at: [16, 1, 15], hint: 'Find the tree that gives no golden apples.', say: 'A mouse is gnawing at its root! Now the tree can give golden apples again.' },
{ id: 20, hint: 'Find the devil\'s grandmother by the fire.', say: 'The kind grandmother pulls three golden hairs from the sleeping devil, and gives them to the lucky boy!' }],
win: 'Three golden hairs! You earned a Golden Hair, and a Dry Fountain kit to build at home.' },
{ id: 'louseflea', abc: 'The Louse and the Flea', title: 'The Louse and the Flea', place: "The Louse and the Flea's House", keep: 'Eggshell', color: '#a08060', parts: [219, 2],
tpl: 'well', roof: 51,
ach: ['Chain Reaction', 'The door creaked, the broom swept, the cart ran... and then the spring.'],
sum: 'The Louse and the Flea. A louse and a flea keep house and brew beer in an eggshell. The little louse falls in and burns herself, and the flea weeps loudly. Then the door creaks, the broom sweeps, the little cart runs, the tree shakes off its leaves, the girl breaks her water-pitcher, and the spring flows and flows until everything is washed away.',
quest: 'Your quest: find the fire where the beer is brewed, find the little tree outside, and find the spring by the well.',
steps: [{ id: 20, hint: 'Find the fire where the beer is brewed.', say: 'A louse and a flea brew beer in an eggshell. The little louse falls in and burns herself, and the flea weeps loudly.' },
{ at: [17, 1, 4], hint: 'Find the little tree outside.', say: 'The door creaks, the broom sweeps, the little cart runs, and the little tree shakes off all its leaves.' },
{ at: [12, 1, 8], hint: 'Find the spring by the well.', say: 'The girl breaks her water-pitcher, and the little spring begins to flow and flow, until everything is washed away!' }],
win: 'What a lot of trouble! You earned the Eggshell, and a Louse and the Flea\'s House kit to build at home.' },
{ id: 'nohands', abc: 'The Girl Without Hands', title: 'The Girl Without Hands', place: "The King's Pear Garden", keep: 'Silver Hand', color: '#c0c0c8', parts: [221, 9],
tpl: 'palace', props: [[6, 4, 16, 58], [16, 1, 2, 31]],
ach: ['Pear Garden', 'Seven years in the forest, and kindness wins in the end.'],
sum: 'The Girl Without Hands. The devil tricks a poor miller, and his good daughter loses her hands. She wanders out into the world, and an angel helps her into a king\'s garden, where she eats a pear from his tree. The king loves her, gives her silver hands and marries her. The devil tricks them again, and she lives for seven years in a little forest house, where her own hands grow back. Then the king finds her.',
quest: 'Your quest: find the pear tree in the king\'s garden, find the silver hands in the palace, and find the bed in the little forest house.',
steps: [{ at: [4, 1, 5], hint: 'Find the pear tree in the king\'s garden.', say: 'An angel helps her across the water, and she eats a pear from the king\'s tree. The king sees her and loves her.' },
{ at: [6, 4, 16], hint: 'Find the silver hands in the palace.', say: 'The king has silver hands made for her, and they marry.' },
{ id: 31, hint: 'Find the bed in the little forest house.', say: 'For seven years she lives in a little house in the forest with her son, and her own hands grow back. Then the king finds them!' }],
win: 'Together again! You earned the Silver Hand, and a King\'s Pear Garden kit to build at home.' },
{ id: 'cleverhans', abc: 'Clever Hans', title: 'Clever Hans', place: "Hans's Mother's House", keep: 'Needle', color: '#c09030', parts: [230, 3],
tpl: 'cottage', props: [[3, 1, 10, 67]],
ach: ['Not So Clever', 'A needle in the hay, a knife in the sleeve, and a very cross Grethel.'],
sum: 'Clever Hans. Every day Hans visits Grethel, and every day she gives him a present. Each time he carries it home the wrong way, and his mother tells him how he should have done it. So the next time he does it her way, with the next present, and it is wrong again! In the end he gets everything so wrong that Grethel runs away.',
quest: 'Your quest: find the cart of hay, find the table in Mother\'s house, and find Hans\'s bed.',
steps: [{ id: 67, hint: 'Find the cart of hay.', say: 'Grethel gives Hans a needle. He sticks it in a cart of hay and loses it. Mother says: you should have put it in your sleeve!' },
{ id: 19, hint: 'Find the table in Mother\'s house.', say: 'Next time Grethel gives him a knife, so he sticks it in his sleeve! Each time, he does what Mother said the time before.' },
{ id: 31, hint: 'Find Hans\'s bed.', say: 'In the end, Hans gets everything so wrong that Grethel is cross and runs away. Silly Hans!' }],
win: 'Oh, Hans! You earned the Needle, and a Hans\'s Mother\'s House kit to build at home.' },
// template places, chunk 4 (ABC Books lessons 233-272, 2026-10-25)
{ id: 'threelang', abc: 'The Three Languages', title: 'The Three Languages', place: 'The Barking Tower', keep: 'White Dove Feather', color: '#7a8aa0', parts: [233, 3],
tpl: 'castle', props: [[13, 1, 14, 21], [6, 1, 12, 81]],
ach: ['Animal Languages', 'Woof, tweet and ribbit. You speak all three.'],
sum: 'The Three Languages. A count\'s son learns only what dogs, birds and frogs say, and his angry father sends him away. In a castle the barking dogs tell him about a treasure they guard, the frogs tell him what will happen to him, and on the way to Rome two white doves tell him what to say. He becomes the Pope!',
quest: 'Your quest: find the treasure the dogs guard, listen to the frog, and go to the throne.',
steps: [{ id: 21, hint: 'Find the treasure the barking dogs guard.', say: 'He understands the barking dogs: they guard a treasure under the tower! He takes it out, and the dogs are quiet at last.' },
{ at: [6, 1, 12], hint: 'Find the frog.', say: 'The frogs croak, and he understands them. They tell him what will happen to him in Rome!' },
{ at: [10, 1, 17], hint: 'Go to the throne.', say: 'Two white doves sit on his shoulders and tell him the words to say. He becomes the Pope!' }],
win: 'You speak three languages! You earned the White Dove Feather, and a Barking Tower kit to build at home.' },
{ id: 'elsie', abc: 'Clever Elsie', title: 'Clever Elsie', place: "Elsie's Cellar", keep: 'Little Bell', color: '#d0a050', parts: [236, 5],
tpl: 'cottage', props: [[3, 1, 10, 21], [4, 1, 13, 67], [3, 1, 13, 67]],
ach: ['Is It I?', 'Elsie was not sure. You are.'],
sum: 'Clever Elsie. Elsie goes down to the cellar for beer, sees a pickaxe on the wall, and cries about what might happen one day. Everyone who comes to look cries with her, and Hans marries her because she is so clever. Later she falls asleep in the field, Hans hangs little bells on her, and she wakes up wondering: is it I, or is it not I?',
quest: 'Your quest: find the beer barrel in the cellar, find the table where everyone waits, and find the field of corn.',
steps: [{ id: 21, hint: 'Find the beer barrel in the cellar.', say: 'Elsie goes to get beer, sees a pickaxe on the wall, and starts to cry about something that has not even happened!' },
{ id: 19, hint: 'Find the table where everyone waits.', say: 'Her mother, her father, the maid and the boy all go down and cry with her. Hans says: what a clever wife!' },
{ id: 67, hint: 'Find the field of corn.', say: 'Elsie falls asleep in the field. Hans hangs little bells on her, and when she wakes she asks: is it I, or is it not I?' }],
win: 'It is you! You earned the Little Bell, and an Elsie\'s Cellar kit to build at home.' },
{ id: 'tailorheaven', abc: 'The Tailor in Heaven', title: 'The Tailor in Heaven', place: "Heaven's Gate", keep: 'Golden Footstool', color: '#f0e0a0', parts: [241, 2],
tpl: 'palace', wall: 51, props: [[8, 4, 17, 57]],
ach: ['Only the Lord Judges', 'Do not throw footstools. Not even golden ones.'],
sum: 'The Tailor in Heaven. A little lame tailor asks Saint Peter to let him into heaven, and hides behind the door. While the Lord is out, he climbs onto the Lord\'s golden chair and sees everything on earth. When he sees an old woman stealing, he throws the golden footstool at her! But only the Lord may judge, so the tailor has to leave.',
quest: 'Your quest: climb the stairs to heaven\'s gate, find the golden chair, and find the golden footstool.',
steps: [{ at: [10, 3, 13], hint: 'Climb the stairs to heaven\'s gate.', say: 'A little lame tailor asks Saint Peter to let him in, and hides behind the door.' },
{ at: [10, 4, 18], hint: 'Find the golden chair.', say: 'He sits on the Lord\'s golden chair and sees everything on earth below!' },
{ at: [8, 4, 17], hint: 'Find the golden footstool.', say: 'He sees an old woman stealing, and throws the golden footstool at her! But only the Lord may judge, so the tailor has to go.' }],
win: 'You earned the Golden Footstool, and a Heaven\'s Gate kit to build at home.' },
{ id: 'wishingtable', abc: 'The Wishing-Table, the Gold-Ass, and the Cudgel in the Sack', title: 'The Wishing-Table', place: 'The Inn of the Wishing-Table', keep: 'Little Wishing-Table', color: '#a07040', parts: [243, 13],
tpl: 'cottage', props: [[3, 1, 10, 57], [4, 1, 13, 21]],
ach: ['Out of the Sack, Stick!', 'A table, a donkey and a stick. The innkeeper never stood a chance.'],
sum: 'The Wishing-Table. A tailor sends his three sons away because their goat tells lies. The first son gets a table that covers itself with food, the second a donkey that drops gold pieces, and the third a stick in a sack. A greedy innkeeper steals the table and the donkey, but the stick jumps out of the sack and beats him until he gives everything back.',
quest: 'Your quest: find the wishing table, find the gold the donkey makes, and find the sack with the stick inside.',
steps: [{ id: 19, hint: 'Find the little wishing table.', say: 'Little table, spread yourself! And it is covered with good food.' },
{ id: 57, hint: 'Find the gold the donkey makes.', say: 'Bricklebrit! says the second son, and the donkey drops gold pieces.' },
{ id: 21, hint: 'Find the sack with the stick inside.', say: 'Out of the sack, stick! The stick jumps out and beats the thief until he gives everything back.' }],
win: 'Everything is back! You earned the Little Wishing-Table, and an Inn of the Wishing-Table kit to build at home.' },
{ id: 'mrsfox', abc: 'The Wedding of Mrs. Fox', title: 'The Wedding of Mrs. Fox', place: "Mrs. Fox's House", keep: 'Fox Tail', color: '#d06a20', parts: [256, 4],
tpl: 'cottage', roof: 40,
ach: ['Just Like Mr. Fox', 'Red legs and a pointed mouth. Perfect.'],
sum: 'The Wedding of Mrs. Fox. Old Mr. Fox pretends to be dead, to see if Mrs. Fox is faithful. The cat, her maid, opens the door to every suitor: a wolf, a dog, a stag, a hare, a bear and a lion. But Mrs. Fox only wants one with red legs and a pointed mouth, just like Mr. Fox, and at last a young fox comes. What a wedding!',
quest: 'Your quest: find old Mr. Fox in his bed, find the cat by the fire, and find the wedding table.',
steps: [{ id: 31, hint: 'Find old Mr. Fox in his bed.', say: 'Old Mr. Fox pretends to be dead, to see if Mrs. Fox is faithful.' },
{ id: 20, hint: 'Find the cat by the fire.', say: 'The cat cooks by the fire and opens the door for every suitor who knocks. Not this one, says Mrs. Fox!' },
{ id: 19, hint: 'Find the wedding table.', say: 'At last a fox comes with red legs and a pointed mouth. They have a wedding, and dance and dance!' }],
win: 'What a wedding! You earned the Fox Tail, and a Mrs. Fox\'s House kit to build at home.' },
{ id: 'robbergroom', abc: 'The Robber Bridegroom', title: 'The Robber Bridegroom', place: "The Robbers' House in the Wood", keep: 'Ring', color: '#5a4a3a', parts: [260, 5],
tpl: 'cottage', wall: 6, roof: 6, leaf: 7, props: [[8, 1, 12, 21]],
ach: ['Brave Bride', 'She told it like a dream. It was not a dream.'],
sum: 'The Robber Bridegroom. A miller promises his daughter to a rich stranger, who invites her to his house deep in the wood. She drops peas to find the way. An old woman there warns her that it is a robbers\' house, and hides her behind a big barrel. At the wedding feast she tells what she saw as if it were a dream, then shows a ring she kept, and the robbers are caught.',
quest: 'Your quest: find the old woman by the fire, find the barrel to hide behind, and find the wedding table.',
steps: [{ id: 20, hint: 'Find the old woman by the fire.', say: 'An old woman by the fire whispers: you are in a robbers\' house! Quick, hide behind the big barrel.' },
{ id: 21, hint: 'Find the barrel to hide behind.', say: 'She hides very still while the robbers come home. A ring falls into her lap, and she keeps it.' },
{ id: 19, hint: 'Find the wedding table.', say: 'At the wedding she tells it all like a dream, then shows the ring. The robbers are caught!' }],
win: 'The robbers are caught! You earned the Ring, and a Robbers\' House in the Wood kit to build at home.' },
{ id: 'korbes', abc: 'Herr Korbes', title: 'Herr Korbes', place: "Herr Korbes's House", keep: 'Little Millstone', color: '#7a7a7a', parts: [265, 1],
tpl: 'cottage', props: [[3, 1, 10, 77]],
ach: ['Surprise Visit', 'A cat, a millstone, an egg, a duck, a pin and a needle.'],
sum: 'Herr Korbes. A hen and a cock set off in a little cart to visit Herr Korbes, a very bad man. A cat, a millstone, an egg, a duck, a pin and a needle all come along. Herr Korbes is not home, so they hide all over his house, and when he comes back, everything goes wrong for him at once.',
quest: 'Your quest: find the little cart, find the fire where the cat hides, and find Herr Korbes\'s bed.',
steps: [{ at: [3, 1, 10], hint: 'Find the little cart.', say: 'A hen and a cock set off in a little cart. A cat, a millstone, an egg, a duck, a pin and a needle all jump in.' },
{ id: 20, hint: 'Find the fire where the cat hides.', say: 'Herr Korbes is not home, so they all hide: the cat in the fire, the egg in the towel, the pin in the chair.' },
{ id: 31, hint: 'Find Herr Korbes\'s bed.', say: 'When Herr Korbes comes home, the cat spits ashes, the egg sticks to him, and the pin and the needle prick him. What a welcome!' }],
win: 'What a visit! You earned the Little Millstone, and a Herr Korbes\'s House kit to build at home.' },
{ id: 'godfather', abc: 'The Godfather', title: 'The Godfather', place: "The Godfather's House", keep: 'Bottle of Water', color: '#4a3a5a', parts: [266, 2],
tpl: 'cottage', wall: 4, roof: 34, props: [[3, 1, 10, 59]],
ach: ['Keyhole Peeker', 'Some godfathers have horns. Run!'],
sum: 'The Godfather. A poor man asks a stranger to be godfather to his child. The godfather gives him a bottle of water that can make sick people well. But when the man visits the godfather\'s house, strange things are happening on the stairs, and through the keyhole he sees the godfather with long horns. He runs away as fast as he can!',
quest: 'Your quest: find the bottle of healing water, find the shelf on the strange stairs, and peek at the godfather\'s bed.',
steps: [{ at: [3, 1, 10], hint: 'Find the bottle of healing water.', say: 'The strange godfather gives the poor man water that can make sick people well.' },
{ id: 35, hint: 'Find the shelf on the stairs.', say: 'On the stairs, a shovel and a broom are quarrelling, and stranger things too!' },
{ id: 31, hint: 'Peek at the godfather\'s bed.', say: 'Through the keyhole he sees the godfather with long horns! He runs away as fast as he can.' }],
win: 'You got away! You earned the Bottle of Water, and a Godfather\'s House kit to build at home.' },
{ id: 'frautrude', abc: 'Frau Trude', title: 'Frau Trude', place: "Frau Trude's House", keep: 'Little Log', color: '#8a2a2a', parts: [268, 1],
tpl: 'cottage', wall: 54, roof: 54,
ach: ['Listen to Your Parents', 'Some houses you should not visit.'],
sum: 'Frau Trude. A stubborn girl who never listens to her parents goes to the house of Frau Trude, a witch, even though they tell her not to. On the stairs she sees a green man, a red man and a black man, and Frau Trude has a head of fire. The witch turns the girl into a log and throws it on the fire. The story says: listen to your parents!',
quest: 'Your quest: find the path to Frau Trude\'s house, find the shelf on the stairs, and find the witch\'s fire.',
steps: [{ at: [10, 0, 3], hint: 'Find the path to Frau Trude\'s house.', say: 'Her parents say: do not go to Frau Trude, she is wicked! But the stubborn girl goes anyway.' },
{ id: 35, hint: 'Find the shelf on the stairs.', say: 'On the stairs she sees a green man, a red man and a black man. She is frightened!' },
{ id: 20, hint: 'Find Frau Trude\'s fire.', say: 'Frau Trude has a head of fire! She turns the girl into a log and warms herself by the fire. Always listen to your parents!' }],
win: 'You listened! You earned the Little Log, and a Frau Trude\'s House kit to build at home.' },
{ id: 'godfatherdeath', abc: 'Godfather Death', title: 'Godfather Death', place: 'The Cave of Candles', keep: 'Little Candle', color: '#2a2a2a', parts: [269, 4],
tpl: 'castle', wall: 3, props: [[6, 1, 12, 38], [13, 1, 13, 31]],
ach: ['Candle Keeper', 'Every candle is a life. Look after yours.'],
sum: 'Godfather Death. A poor man chooses Death as godfather for his son, because Death treats everyone the same. Death makes the boy a famous doctor: if Death stands at the head of the bed, the sick one will get well, if at the feet, they will not. The doctor tricks Death twice to save a king and a princess, but Death shows him the cave where every life is a candle, and his own goes out.',
quest: 'Your quest: find the healing herb, find the sick princess\'s bed, and find the light in the cave of candles.',
steps: [{ at: [6, 1, 12], hint: 'Find the healing herb.', say: 'Death gives his godson a herb that heals, and says: if I stand at the head of the bed, the sick one will get well.' },
{ id: 31, hint: 'Find the sick princess\'s bed.', say: 'Death stands at her feet, but the doctor turns the bed around to save her. Death is very angry.' },
{ at: [7, 1, 9], hint: 'Find the light in the cave of candles.', say: 'Death shows him a cave full of candles, one for every life. His own little candle is nearly burnt out, and it goes out.' }],
win: 'You earned the Little Candle, and a Cave of Candles kit to build at home.' },
// template places, chunk 5 (ABC Books lessons 273-335, 2026-10-25)
{ id: 'thumbjourney', abc: 'Thumbling as Journeyman', title: 'Thumbling as Journeyman', place: "Thumbling's Travels", keep: 'Needle Sword', color: '#90a050', parts: [273, 5],
tpl: 'cottage', props: [[8, 1, 12, 21], [3, 1, 10, 67]],
ach: ['Tiny Traveller Again', 'A needle for a sword and a thimble for a hat.'],
sum: 'Thumbling as Journeyman. A tailor\'s son no bigger than a thumb takes a needle for a sword and goes out into the world. He works for a tailor\'s wife, helps robbers into the king\'s treasure room, sleeps in the hay, and is swallowed by a cow and by a fox. Each time he talks his way out, and at last he rides home on the fox.',
quest: 'Your quest: find the table where Thumbling eats, find the king\'s treasure chest, and find the hay in the barn.',
steps: [{ id: 19, hint: 'Find the table where Thumbling eats.', say: 'Thumbling, no bigger than a thumb, takes his needle for a sword and goes out into the world.' },
{ id: 21, hint: 'Find the king\'s treasure chest.', say: 'He slips into the king\'s treasure room and throws the coins out one by one. Nobody can catch him!' },
{ id: 67, hint: 'Find the hay in the barn.', say: 'He sleeps in the hay and is swallowed by a cow, and then by a fox. But he talks his way out, and rides home on the fox!' }],
win: 'Home again! You earned the Needle Sword, and a Thumbling\'s Travels kit to build at home.' },
{ id: 'fitcher', abc: "Fitcher's Bird", title: "Fitcher's Bird", place: "The Wizard's House", keep: 'Clean Egg', color: '#6a4a8a', parts: [278, 5],
tpl: 'castle', wall: 54, props: [[13, 1, 14, 51], [10, 1, 15, 49], [6, 1, 14, 75]],
ach: ['Clever Sister', 'She kept the egg clean. The wizard never saw that coming.'],
sum: 'Fitcher\'s Bird. A wizard carries away girls to his house in the wood. He gives each one an egg and a key, and forbids one little room. The third sister is clever: she puts the egg safely away, opens the room, and saves her two sisters. Then she rolls in honey and feathers, becomes a strange bird, and gets away, and the wizard is punished.',
quest: 'Your quest: find the egg the wizard gave her, find the forbidden little room, and find the feathers.',
steps: [{ at: [13, 1, 14], hint: 'Find the egg the wizard gave her.', say: 'The wizard gives her an egg and a key and says: never open the little room! The clever girl puts the egg away safely.' },
{ at: [10, 1, 15], hint: 'Find the forbidden little room.', say: 'She opens the room and saves her sisters. The egg stays clean, so the wizard must do what she says!' },
{ id: 75, hint: 'Find the feathers.', say: 'She rolls in honey and feathers and becomes a strange bird. Fitcher\'s bird, where are you from? And she gets away!' }],
win: 'Clever girl! You earned the Clean Egg, and a Wizard\'s House kit to build at home.' },
{ id: 'juniper', abc: 'The Juniper-Tree', title: 'The Juniper-Tree', place: 'The Juniper Garden', keep: 'Red Shoes', color: '#2a6a4a', parts: [283, 10],
tpl: 'cottage', props: [[8, 1, 12, 21], [16, 1, 8, 4]],
ach: ['The Bird in the Juniper', 'A sad song, and then a happy ending.'],
sum: 'The Juniper-Tree. A wicked stepmother kills her little stepson. His sister Marlinchen buries his bones under the juniper tree, and a beautiful bird flies out of a mist and sings his sad song. It gives a gold chain to the father and red shoes to the sister, and drops a millstone on the wicked stepmother. Then the little boy is standing there, alive again.',
quest: 'Your quest: find the chest of apples, find the juniper tree, and find the millstone.',
steps: [{ id: 21, hint: 'Find the chest of apples.', say: 'The wicked stepmother does a terrible thing to the little boy at the apple chest.' },
{ at: [3, 1, 17], hint: 'Find the juniper tree.', say: 'His sister buries his bones under the juniper tree. A mist rises, and a beautiful bird flies out, singing!' },
{ at: [16, 1, 8], hint: 'Find the millstone.', say: 'The bird gives a gold chain to the father, red shoes to the sister, and drops the millstone on the wicked stepmother. The little boy is alive again!' }],
win: 'The boy is home! You earned the Red Shoes, and a Juniper Garden kit to build at home.' },
{ id: 'sultan', abc: 'Old Sultan', title: 'Old Sultan', place: "Old Sultan's Farm", keep: 'Dog Bone', color: '#8a7a5a', parts: [293, 3],
tpl: 'cottage', props: [[3, 1, 10, 77]],
ach: ['Good Old Dog', 'No teeth, still the best dog on the farm.'],
sum: 'Old Sultan. Old Sultan the dog has lost his teeth, and the farmer wants to get rid of him. His friend the wolf has a plan: the wolf grabs the farmer\'s baby, and Sultan brings it back, so the farmer loves him again. When the wolf wants a sheep in return, Sultan says no. At the duel, the cat\'s tail looks like a sword, and the wolf and the wild boar run and hide.',
quest: 'Your quest: find the farmer\'s bed, find the baby\'s cradle, and find the tree where the wolf hides.',
steps: [{ id: 31, hint: 'Find the farmer\'s bed.', say: 'Old Sultan the dog has lost his teeth, and the farmer wants to get rid of him.' },
{ at: [3, 1, 10], hint: 'Find the baby\'s cradle.', say: 'The wolf grabs the baby, and old Sultan brings it back. Now the farmer loves Sultan again!' },
{ at: [17, 1, 17], hint: 'Find the tree where the wolf hides.', say: 'At the duel, the cat\'s tail looks like a sword! The wolf climbs the tree, and the wild boar hides in the leaves.' }],
win: 'Good old Sultan! You earned the Dog Bone, and an Old Sultan\'s Farm kit to build at home.' },
{ id: 'sixswans', abc: 'The Six Swans', title: 'The Six Swans', place: 'The Swan Pond', keep: 'Starwort Shirt', color: '#e0e8f0', parts: [296, 6],
tpl: 'mill', props: [],
ach: ['Six Years of Silence', 'Six shirts, no words, one swan wing left over.'],
sum: 'The Six Swans. A wicked queen throws little white shirts over six brothers, and they turn into swans. Their sister may not speak or laugh for six years, and must sew six shirts from little star-flowers. A king marries her, and she is nearly punished for things she did not do. Just in time she throws the shirts over the swans, and they become her brothers again, all but one swan wing.',
quest: 'Your quest: find the chest of little white shirts, find the bridge over the swan pond, and find the star-flowers in the mill.',
steps: [{ id: 21, hint: 'Find the chest of little white shirts.', say: 'The wicked queen sews little white shirts, and when she throws them over the six brothers, they turn into swans!' },
{ at: [10, 0, 10], hint: 'Find the bridge over the swan pond.', say: 'Their sister must not speak or laugh for six years, and must sew six shirts from little star-flowers.' },
{ id: 67, hint: 'Find the star-flowers in the mill.', say: 'Just in time, she throws the shirts over the swans, and they become her brothers again. The youngest keeps one swan wing!' }],
win: 'The brothers are back! You earned the Starwort Shirt, and a Swan Pond kit to build at home.' },
{ id: 'fundevogel', abc: 'Fundevogel (Bird-foundling)', title: 'Fundevogel', place: "Fundevogel's Wood", keep: 'Little Rose', color: '#c05070', parts: [302, 3],
tpl: 'forest', props: [[9, 1, 16, 73]],
ach: ['Never Leave Me', 'Rose-tree and rose, pond and duck. Best friends.'],
sum: 'Fundevogel. A forester finds a little boy in a tall tree, where a bird carried him, and names him Fundevogel, bird-foundling. He grows up with the forester\'s daughter Lenchen. When the wicked old cook wants to harm him, the two children run away, and turn into a rose-tree and a rose, a church and a chandelier, and a pond and a duck, until the cook gives up.',
quest: 'Your quest: find the tall tree where the baby was found, find the rose-tree, and find the stump by the pond.',
steps: [{ at: [10, 1, 8], hint: 'Find the tall tree where the baby was found.', say: 'A forester finds a little boy in a tall tree, where a bird carried him. He calls him Fundevogel and takes him home.' },
{ at: [9, 1, 16], hint: 'Find the rose-tree.', say: 'The cook chases them! Lenchen says: turn into a rose-tree, and I will be the rose on it. Nobody finds them!' },
{ at: [12, 1, 17], hint: 'Find the stump by the pond.', say: 'They turn into a pond and a duck. The duck pulls the old cook into the water, and the children go home happy.' }],
win: 'Friends forever! You earned the Little Rose, and a Fundevogel\'s Wood kit to build at home.' },
{ id: 'thrushbeard', abc: 'King Thrushbeard', title: 'King Thrushbeard', place: "King Thrushbeard's Palace", keep: 'Clay Pot', color: '#b06a3a', parts: [305, 7],
tpl: 'palace', props: [[6, 1, 7, 33], [7, 1, 7, 33], [6, 2, 7, 33]],
ach: ['Kind at Last', 'She laughed at his chin. He taught her to be kind.'],
sum: 'King Thrushbeard. A proud princess laughs at every king who wants to marry her, and calls one King Thrushbeard because of his chin. Her angry father makes her marry a poor fiddler. She lives in a tiny house, sells pots at the market, and works in a palace kitchen. Then the fiddler tells her: I am King Thrushbeard! He did it to make her kind, and they have a real wedding.',
quest: 'Your quest: find the throne where the princess laughs, find the pots at the market, and find the lights at the palace door.',
steps: [{ at: [10, 4, 18], hint: 'Find the throne where the princess laughs.', say: 'The proud princess laughs at every king who wants to marry her. That one has a chin like a thrush\'s beak, she says!' },
{ at: [6, 1, 7], hint: 'Find the pots at the market.', say: 'Her father makes her marry a poor fiddler. She sells pots at the market, and a soldier on a horse rides over them all!' },
{ at: [8, 4, 13], hint: 'Find the lights at the palace door.', say: 'The fiddler is really King Thrushbeard! He did it to make her kind, and now they have a real wedding.' }],
win: 'A real wedding! You earned the Clay Pot, and a King Thrushbeard\'s Palace kit to build at home.' },
{ id: 'knapsack', abc: 'The Knapsack, the Hat, and the Horn', title: 'The Knapsack, the Hat, and the Horn', place: 'The Castle of the Little Horn', keep: 'Little Horn of Walls', color: '#6a5a3a', parts: [312, 8],
tpl: 'castle', props: [[7, 1, 14, 19], [13, 1, 14, 21]],
ach: ['Toot!', 'One little horn, and down come the walls.'],
sum: 'The Knapsack, the Hat, and the Horn. Three poor brothers go out to seek their fortune. The youngest finds a little cloth that spreads a feast, and trades it for a knapsack that sends out soldiers, a hat that fires cannons, and a little horn that knocks down walls and towers. With them he becomes king.',
quest: 'Your quest: find the little cloth that spreads a feast, find the magic knapsack, and go to the throne.',
steps: [{ id: 19, hint: 'Find the little cloth that spreads a feast.', say: 'Little cloth, spread yourself! And there is a feast with wine.' },
{ id: 21, hint: 'Find the magic knapsack.', say: 'Every time he taps the knapsack, soldiers march out!' },
{ at: [10, 1, 17], hint: 'Go to the throne.', say: 'He blows his little horn, and the walls and towers fall down! He becomes king.' }],
win: 'Toot! You earned the Little Horn of Walls, and a Castle of the Little Horn kit to build at home.' },
{ id: 'roland', abc: 'Sweetheart Roland', title: 'Sweetheart Roland', place: "Sweetheart Roland's Field", keep: 'Red Flower', color: '#d03050', parts: [320, 5],
tpl: 'forest',
ach: ['True Sweetheart', 'She sang, and he remembered.'],
sum: 'Sweetheart Roland. A girl and her sweetheart Roland run away from her wicked stepmother, a witch, and change into a lake and a duck, and a flower and a fiddler, to escape. Then Roland forgets her, and she waits as a red flower in a field. A shepherd picks the flower, and she keeps his house in secret. At Roland\'s wedding she sings, and he knows her voice at once.',
quest: 'Your quest: find the path where they run away, find the red flower by the path, and find the stump where she sings.',
steps: [{ at: [6, 0, 11], hint: 'Find the path where they run away.', say: 'Sweetheart Roland and the girl run away from the wicked witch. She turns Roland into a lake and herself into a duck!' },
{ at: [12, 1, 9], hint: 'Find the red flower by the path.', say: 'She turns into a red flower and waits for Roland. A shepherd picks her, and she keeps his house tidy in secret.' },
{ at: [12, 1, 17], hint: 'Find the stump where she sings.', say: 'At Roland\'s wedding she sings, and he knows her voice at once. He marries his true sweetheart!' }],
win: 'True love! You earned the Red Flower, and a Sweetheart Roland\'s Field kit to build at home.' },
{ id: 'goldenbird', abc: 'The Golden Bird', title: 'The Golden Bird', place: 'The Golden Bird Castle', keep: 'Golden Bird Feather', color: '#e0b020', parts: [325, 11],
tpl: 'castle', props: [[6, 1, 13, 57]],
ach: ['Listen to the Fox', 'Wooden cage, not golden. The fox was right.'],
sum: 'The Golden Bird. Every night a golden bird steals a golden apple from the king\'s tree. The king\'s youngest son goes after it, and a clever fox helps him, if only he will listen. With the fox\'s help he wins the golden bird, the golden horse and the beautiful princess of the golden castle, escapes his jealous brothers, and at the end the fox turns into a prince.',
quest: 'Your quest: find the apple tree, find the golden bird in its cage, and find the princess of the golden castle.',
steps: [{ at: [2, 1, 3], hint: 'Find the apple tree.', say: 'Every night a golden bird steals a golden apple from the king\'s tree.' },
{ at: [6, 1, 13], hint: 'Find the golden bird in its cage.', say: 'The clever fox says: put the golden bird in the wooden cage, not the golden one! But the prince does not listen, and he is caught.' },
{ at: [10, 1, 17], hint: 'Find the princess of the golden castle.', say: 'With the fox\'s help he wins the golden bird, the golden horse and the princess. And the fox turns into a prince!' }],
win: 'The golden bird is yours! You earned the Golden Bird Feather, and a Golden Bird Castle kit to build at home.' },
// template places, chunk 6 (ABC Books lessons 336-405, 2026-10-25)
{ id: 'dogsparrow', abc: 'The Dog and the Sparrow', title: 'The Dog and the Sparrow', place: "The Carter's Road", keep: 'Sparrow Feather', color: '#8a6a4a', parts: [336, 4],
tpl: 'cottage',
ach: ['Loyal Sparrow', 'Never run over a sparrow\'s friend.'],
sum: 'The Dog and the Sparrow. A hungry sheep-dog makes friends with a sparrow, who pecks meat and bread down for him from the butcher\'s and the baker\'s. When a cruel carter drives right over the sleeping dog, the sparrow says he will pay for it, and keeps causing trouble until the carter has lost everything.',
quest: 'Your quest: find the butcher\'s table, find the road where the dog sleeps, and find the carter\'s fire.',
steps: [{ id: 19, hint: 'Find the butcher\'s table.', say: 'A hungry sheep-dog meets a kind sparrow, who pecks meat and bread down for him from the butcher\'s and the baker\'s.' },
{ at: [10, 0, 3], hint: 'Find the road where the dog sleeps.', say: 'A cruel carter drives right over the sleeping dog. The sparrow cries: you shall pay for this!' },
{ id: 20, hint: 'Find the carter\'s fire.', say: 'The sparrow spills his wine, troubles his horses, and causes so much mischief that the carter loses everything.' }],
win: 'The sparrow kept his word! You earned the Sparrow Feather, and a Carter\'s Road kit to build at home.' },
{ id: 'frederick', abc: 'Frederick and Catherine', title: 'Frederick and Catherine', place: "Catherine's Cellar", keep: 'Little Door', color: '#c08a40', parts: [340, 8],
tpl: 'cottage', props: [[8, 1, 12, 21], [16, 1, 12, 57]],
ach: ['Oops, Catherine', 'The beer, the meal, the door... and the robbers ran away.'],
sum: 'Frederick and Catherine. Catherine means well, but everything she does goes wrong. She leaves the beer running while she chases a dog with the sausage, and sprinkles meal over the wet cellar. When they go after the thieves, she carries the house door with her. They climb a tree, robbers sit down underneath, and when she drops the door on them, they run away and leave all their gold.',
quest: 'Your quest: find the beer barrel in the cellar, find the tree in the wood, and find the robbers\' gold.',
steps: [{ id: 21, hint: 'Find the beer barrel in the cellar.', say: 'Catherine leaves the beer running while she chases the dog with the sausage. The whole cellar fills with beer!' },
{ at: [17, 1, 4], hint: 'Find the tree in the wood.', say: 'Frederick and Catherine climb a tree, and Catherine brings the house door. Robbers sit down underneath!' },
{ id: 57, hint: 'Find the robbers\' gold.', say: 'Catherine drops the door on the robbers, and they run away and leave all their gold!' }],
win: 'Lucky Catherine! You earned the Little Door, and a Catherine\'s Cellar kit to build at home.' },
{ id: 'twobrothers', abc: 'The Two Brothers', title: 'The Two Brothers', place: "The Dragon's Castle", keep: 'Hunting Knife', color: '#7a3a2a', parts: [348, 28],
tpl: 'castle', props: [[13, 1, 14, 3], [13, 2, 14, 3]],
ach: ['Dragon Slayer', 'Seven heads, five animal friends, two brave brothers.'],
sum: 'The Two Brothers. Twin brothers go out into the world, each with a hare, a fox, a wolf, a bear and a lion as friends. They part at a tree and stick a knife in it: if one blade rusts, the other is in danger. One brother kills a dragon with seven heads and saves a princess. When a witch turns him to stone, his brother sees the rusty knife, comes to find him, and sets him free.',
quest: 'Your quest: find the tree where the brothers part, go to the throne room, and find the huntsman turned to stone.',
steps: [{ at: [18, 1, 3], hint: 'Find the tree where the brothers part.', say: 'The twin brothers part at a tree and stick a knife in it. If the blade rusts, the other one is in danger.' },
{ at: [10, 1, 17], hint: 'Go to the throne room.', say: 'With his hare, fox, wolf, bear and lion, the huntsman kills a dragon with seven heads and saves the princess!' },
{ at: [13, 1, 14], hint: 'Find the huntsman turned to stone.', say: 'A witch turns him to stone, but his brother sees the rusty knife, comes, and sets him and all the others free!' }],
win: 'Brothers together! You earned the Hunting Knife, and a Dragon\'s Castle kit to build at home.' },
{ id: 'littlepeasant', abc: 'The Little Peasant', title: 'The Little Peasant', place: "The Little Peasant's Meadow", keep: 'Wooden Calf', color: '#8aa050', parts: [376, 7],
tpl: 'cottage', props: [[3, 1, 10, 5], [8, 1, 12, 21]],
ach: ['Too Clever by Half', 'A wooden calf, a parson in a chest, and sheep under the water.'],
sum: 'The Little Peasant. A poor little farmer is so clever that he tricks everyone. He leaves a wooden calf in the meadow, sells a chest with a parson hiding inside it, and tells the greedy villagers he found sheep under the water. They all jump in to get some, and the little farmer is the only rich man left.',
quest: 'Your quest: find the little wooden calf, find the chest where the parson hides, and find the road to the water.',
steps: [{ at: [3, 1, 10], hint: 'Find the little wooden calf.', say: 'The poor little farmer has a carpenter make a wooden calf, and leaves it in the meadow.' },
{ id: 21, hint: 'Find the chest where the parson hides.', say: 'He finds a parson hiding in a chest, and sells the chest for a big bag of money!' },
{ at: [10, 0, 3], hint: 'Find the road to the water.', say: 'He tells the greedy villagers he found sheep under the water. They all jump in, and the little farmer is the only rich man left.' }],
win: 'What a trickster! You earned the Wooden Calf, and a Little Peasant\'s Meadow kit to build at home.' },
{ id: 'queenbee', abc: 'The Queen Bee', title: 'The Queen Bee', place: 'The Stone Castle', keep: 'Honey', color: '#e0b030', parts: [383, 3],
tpl: 'castle', wall: 3, props: [[6, 1, 12, 56], [13, 1, 13, 59], [7, 1, 15, 31]],
ach: ['Friend of Ants, Ducks and Bees', 'Be kind to little animals. They remember.'],
sum: 'The Queen Bee. Simpleton stops his brothers from hurting an ant-hill, some ducks and a bees\' nest. They come to a castle where everything has turned to stone. To break the spell, the ants find a thousand pearls in the moss, the ducks dive for the key to the princesses\' room, and the queen bee shows which princess ate honey. Everyone wakes up, and Simpleton marries the youngest.',
quest: 'Your quest: find the pearls in the moss, find the key from the lake, and find the princess who ate honey.',
steps: [{ at: [6, 1, 12], hint: 'Find the pearls in the moss.', say: 'The ants he saved find all thousand pearls for him!' },
{ at: [13, 1, 13], hint: 'Find the key from the lake.', say: 'The ducks he saved dive down and bring up the key to the princesses\' room.' },
{ id: 31, hint: 'Find the princess who ate honey.', say: 'The queen bee lands on the lips of the princess who ate honey. Simpleton chooses right, and everyone wakes up!' }],
win: 'Everyone is awake! You earned the Honey, and a Stone Castle kit to build at home.' },
{ id: 'threefeathers', abc: 'The Three Feathers', title: 'The Three Feathers', place: "The Toad's Stairs", keep: 'Feather', color: '#8ab070', parts: [386, 4],
tpl: 'well',
ach: ['Follow the Feather', 'Down the stairs, past the toad, up to the throne.'],
sum: 'The Three Feathers. An old king blows three feathers into the air to decide which son goes where. Simpleton\'s feather falls by a stone, and under it are stairs leading down to a big fat toad. The toad gives him the most beautiful carpet, the most beautiful ring, and at last a little toad that turns into a beautiful girl. Simpleton becomes king.',
quest: 'Your quest: find where the feather fell, find the big fat toad by the fire, and find the little house.',
steps: [{ at: [12, 1, 8], hint: 'Find where Simpleton\'s feather fell.', say: 'Simpleton\'s feather falls by a stone, and under it are stairs going down!' },
{ id: 20, hint: 'Find the big fat toad by the fire.', say: 'A big fat toad gives him the most beautiful carpet, and then the most beautiful ring.' },
{ id: 31, hint: 'Find the little house.', say: 'A little toad turns into a beautiful girl, and Simpleton becomes king!' }],
win: 'King Simpleton! You earned the Feather, and a Toad\'s Stairs kit to build at home.' },
{ id: 'allerleirauh', abc: 'Allerleirauh', title: 'Allerleirauh', place: 'The Coat of a Thousand Furs', keep: 'Golden Ring', color: '#a08060', parts: [390, 7],
tpl: 'palace', props: [[6, 4, 16, 75], [14, 4, 16, 20]],
ach: ['Sun, Moon and Stars', 'Three dresses in a nutshell. Clever packing.'],
sum: 'Allerleirauh. A princess runs away from home in a coat made of a thousand kinds of fur, with three beautiful dresses folded into a nutshell. She works in a king\'s kitchen, covered in soot. At three festivals she dances with the king in dresses as golden as the sun, as silver as the moon and as bright as the stars, and drops a golden ring into his soup. The king finds out who she is, and they marry.',
quest: 'Your quest: find the coat of a thousand furs, find the kitchen fire, and find the throne at the festival.',
steps: [{ at: [6, 4, 16], hint: 'Find the coat of a thousand furs.', say: 'The princess runs away in a coat of a thousand kinds of fur, with her three dresses in a nutshell.' },
{ id: 20, hint: 'Find the kitchen fire.', say: 'She works in the king\'s kitchen and cooks his soup, and drops a golden ring into it!' },
{ at: [10, 4, 18], hint: 'Find the throne at the festival.', say: 'She dances with the king in dresses like the sun, the moon and the stars. He finds her, and they marry!' }],
win: 'Found at last! You earned the Golden Ring, and a Coat of a Thousand Furs kit to build at home.' },
{ id: 'haresbride', abc: "The Hare's Bride", title: "The Hare's Bride", place: "The Hare's Hut", keep: 'Cabbage Leaf', color: '#8ab040', parts: [397, 2],
tpl: 'cottage', roof: 40, props: [[3, 1, 10, 38], [4, 1, 13, 67]],
ach: ['Straw Doll', 'The hare married a straw doll. Oops.'],
sum: 'The Hare\'s Bride. A hare keeps eating the cabbages in a woman\'s garden. He says to her daughter: sit on my tail and come to my hut! There he wants her to cook the wedding dinner, but she makes a doll out of straw, dresses it in her own clothes, and runs home to her mother. The hare finds only straw, and goes away very sad.',
quest: 'Your quest: find the cabbages in the garden, find the fire in the hare\'s hut, and find the straw doll.',
steps: [{ at: [3, 1, 10], hint: 'Find the cabbages in the garden.', say: 'A hare keeps eating the cabbages. Sit on my tail, little girl, and come to my hut!' },
{ id: 20, hint: 'Find the fire in the hare\'s hut.', say: 'Cook the wedding dinner! But the girl makes a doll out of straw, dresses it in her clothes, and runs home.' },
{ id: 67, hint: 'Find the straw doll.', say: 'The hare knocks off the doll\'s cap. It is only straw! He goes away very sad.' }],
win: 'Home safe! You earned the Cabbage Leaf, and a Hare\'s Hut kit to build at home.' },
{ id: 'huntsmen', abc: 'The Twelve Huntsmen', title: 'The Twelve Huntsmen', place: "The Huntsmen's Hall", keep: 'Hunting Horn', color: '#4a7a3a', parts: [399, 4],
tpl: 'castle', props: [[6, 1, 12, 8], [13, 1, 12, 68]],
ach: ['Firm Steps', 'No pea rolled. The lion was fooled.'],
sum: 'The Twelve Huntsmen. A prince forgets his true bride. She and eleven girls who look just like her dress as huntsmen and work for him. His lion says they are girls and tests them with peas and spinning wheels, but they walk firmly and do not look at the wheels. When the first huntsman faints at bad news, the king sees his ring on her hand and remembers his true love.',
quest: 'Your quest: find the peas on the floor, find the spinning wheels, and go to the throne.',
steps: [{ at: [6, 1, 12], hint: 'Find the peas on the floor.', say: 'Girls trip on peas, says the lion. But the huntsmen walk so firmly that not a single pea rolls!' },
{ id: 68, hint: 'Find the spinning wheels.', say: 'Spinning wheels! The twelve huntsmen do not even look at them.' },
{ at: [10, 1, 17], hint: 'Go to the throne.', say: 'The first huntsman faints, and the king sees his own ring on her hand. He remembers his true love!' }],
win: 'True love remembered! You earned the Hunting Horn, and a Huntsmen\'s Hall kit to build at home.' },
{ id: 'thiefmaster', abc: 'The Thief and his Master', title: 'The Thief and his Master', place: "The Master's House", keep: 'Bridle', color: '#5a5a7a', parts: [403, 3],
tpl: 'cottage', props: [[3, 1, 10, 67]],
ach: ['Cleverer than the Master', 'Horse, hare, rooster and fox. Who wins?'],
sum: 'The Thief and his Master. Jan wants his son to learn a good trade, but the master teaches him to be a clever thief and a magician. The son turns himself into a horse and lets his father sell him, but warns him to keep the bridle. Then he and his master change into one animal after another, a hare and a dog, a rooster and a fox, and in the end the son is cleverer than the master.',
quest: 'Your quest: find the master\'s table, find the horse\'s hay, and find the road where they race.',
steps: [{ id: 19, hint: 'Find the master\'s table.', say: 'Jan wants his son to learn a good trade, but the master teaches him to be a clever thief and a magician.' },
{ id: 67, hint: 'Find the horse\'s hay.', say: 'The son turns himself into a horse, and his father sells him. But keep the bridle, he says!' },
{ at: [10, 0, 3], hint: 'Find the road where they race.', say: 'They change into a hare and a dog, then a rooster and a fox. In the end the son is cleverer than the master!' }],
win: 'You earned the Bridle, and a Master\'s House kit to build at home.' },
// template places, chunk 7 (ABC Books lessons 406-435, 2026-10-25)
{ id: 'jorinda', abc: 'Jorinda and Joringel', title: 'Jorinda and Joringel', place: "The Witch's Castle of Birds", keep: 'Blood-red Flower', color: '#8a2040', parts: [406, 4],
tpl: 'castle', wall: 54, props: [[13, 1, 14, 11]],
ach: ['Nightingale Freed', 'One red flower, and the spell is gone.'],
sum: 'Jorinda and Joringel. Jorinda and Joringel walk too near the castle of a witch who turns girls into birds. Jorinda becomes a nightingale in a cage, and Joringel cannot move. He dreams of a blood-red flower with a pearl in it, searches for nine days, and finds it. With the flower he breaks the spell, and Jorinda is a girl again.',
quest: 'Your quest: find the old trees by the castle, find the blood-red flower, and find the birdcages in the castle.',
steps: [{ at: [2, 1, 3], hint: 'Find the old trees by the castle.', say: 'Jorinda and Joringel walk too near the witch\'s castle. Jorinda turns into a nightingale, and Joringel cannot move!' },
{ at: [6, 1, 4], hint: 'Find the blood-red flower.', say: 'Joringel dreams of a blood-red flower with a pearl in the middle. He searches for nine days, and finds it!' },
{ at: [13, 1, 14], hint: 'Find the birdcages in the castle.', say: 'He touches the cage with the flower, and Jorinda is a girl again!' }],
win: 'Jorinda is free! You earned the Blood-red Flower, and a Witch\'s Castle of Birds kit to build at home.' },
{ id: 'threesons', abc: 'The Three Sons of Fortune', title: 'The Three Sons of Fortune', place: 'The Three Gifts Farm', keep: 'Little Scythe', color: '#a09040', parts: [410, 4],
tpl: 'cottage', props: [[3, 1, 10, 67]],
ach: ['Lucky Gifts', 'A rooster, a scythe and a cat. Worth their weight in gold.'],
sum: 'The Three Sons of Fortune. A father gives his three sons a rooster, a scythe and a cat. Each son travels to a land where nobody has ever seen such a thing: a land with no rooster to wake them, a land that cuts its corn with cannons, and a land full of mice. Each sells his gift for a donkey loaded with gold.',
quest: 'Your quest: find the father\'s table, find the field of corn, and find the shelf where the mice play.',
steps: [{ id: 19, hint: 'Find the father\'s table.', say: 'A father gives his three sons a rooster, a scythe and a cat. That is all he has.' },
{ id: 67, hint: 'Find the field of corn.', say: 'In a land where they cut corn by firing cannons, the scythe is a wonder! It sells for a donkey loaded with gold.' },
{ id: 35, hint: 'Find the shelf where the mice play.', say: 'In a land full of mice, the cat catches them all, and the king pays a donkey loaded with gold!' }],
win: 'Three lucky sons! You earned the Little Scythe, and a Three Gifts Farm kit to build at home.' },
{ id: 'sixmen', abc: 'How Six Men Got on in the World', title: 'How Six Men Got on in the World', place: "The King's Treasure House", keep: 'Magic Hat', color: '#5a6aa0', parts: [414, 7],
tpl: 'palace', props: [[6, 4, 16, 59]],
ach: ['Six Friends', 'Strong, sharp-eyed, windy, fast and frosty.'],
sum: 'How Six Men Got on in the World. A soldier sent away by the king finds five helpers: a strong man, a huntsman with sharp eyes, a man who blows like a storm, a runner faster than the wind, and a man whose hat brings frost. Together they win a race against the princess, stay cool in a room with a fire under it, and carry off all the king\'s treasure.',
quest: 'Your quest: climb to the palace, find the room that should be hot, and find the king\'s treasure.',
steps: [{ at: [10, 3, 13], hint: 'Climb the stairs to the palace.', say: 'A soldier finds five helpers: a strong man, a huntsman, a blower, a fast runner, and a man with a magic hat.' },
{ at: [6, 4, 16], hint: 'Find the room that should be hot.', say: 'The king locks them in an iron room with a fire underneath, but the man with the hat makes it so cold that ice grows on the walls!' },
{ at: [10, 4, 18], hint: 'Find the king\'s treasure.', say: 'The strong man carries off all the king\'s treasure, and the blower blows the soldiers away!' }],
win: 'Six friends, one treasure! You earned the Magic Hat, and a King\'s Treasure House kit to build at home.' },
{ id: 'wolfman', abc: 'The Wolf and the Man', title: 'The Wolf and the Man', place: 'The Huntsman\'s Path', keep: 'Wolf Tuft', color: '#6a6a6a', parts: [421, 1],
tpl: 'forest',
ach: ['Meet a Man', 'The wolf wanted to meet a man. Once was enough.'],
sum: 'The Wolf and the Man. The fox tells the wolf how strong man is, but the wolf says he is not afraid and wants to meet one. An old man walks by, then a boy, and then a huntsman with a gun and a knife. The wolf runs at him, and comes back to the fox very sorry he went.',
quest: 'Your quest: find the stump where the fox and the wolf talk, find the road where the man comes, and find the tree where the wolf runs.',
steps: [{ at: [12, 1, 17], hint: 'Find the stump where the fox and the wolf talk.', say: 'The fox tells the wolf how strong man is. The wolf says: I am not afraid!' },
{ at: [10, 0, 3], hint: 'Find the road where the man comes.', say: 'An old man comes along the road, then a boy. Then a huntsman comes. That is a man, says the fox!' },
{ at: [10, 1, 8], hint: 'Find the tree where the wolf runs.', say: 'The huntsman shoots and swings his knife, and the wolf runs back to the fox, very sorry he went.' }],
win: 'The wolf learned his lesson! You earned the Wolf Tuft, and a Huntsman\'s Path kit to build at home.' },
{ id: 'wolffox', abc: 'The Wolf and the Fox', title: 'The Wolf and the Fox', place: "The Farmer's Cellar", keep: 'Pancake', color: '#c07030', parts: [422, 2],
tpl: 'cottage', props: [[3, 1, 10, 51], [8, 1, 12, 21]],
ach: ['Too Full', 'The wolf ate so much he got stuck. The fox did not.'],
sum: 'The Wolf and the Fox. A greedy wolf makes the fox fetch food for him. The fox shows him a lamb, and pancakes cooking, and each time the wolf gets a beating. At last the fox takes him to a cellar full of meat. The wolf eats so much that he gets stuck in the hole, and the fox is free of him.',
quest: 'Your quest: find the lamb in the yard, find the pancakes by the fire, and find the meat in the cellar.',
steps: [{ at: [3, 1, 10], hint: 'Find the lamb in the yard.', say: 'The greedy wolf wants the lamb too, but the farmers chase him away!' },
{ id: 20, hint: 'Find the pancakes by the fire.', say: 'The fox takes one pancake. The wolf grabs the whole dish, and gets a beating!' },
{ id: 21, hint: 'Find the meat in the cellar.', say: 'The wolf eats so much in the cellar that he gets stuck in the hole, and the fox gets away!' }],
win: 'Clever fox! You earned the Pancake, and a Farmer\'s Cellar kit to build at home.' },
{ id: 'foxcousin', abc: 'The Fox and His Cousin', title: 'The Fox and His Cousin', place: "The Farmyard", keep: 'Fox Whisker', color: '#b06030', parts: [424, 1],
tpl: 'cottage', props: [[3, 1, 10, 51]],
ach: ['Sly Godfather', 'The fox was the godfather. The wolf got the beating.'],
sum: 'The Fox and His Cousin. Mother wolf asks the fox to be godfather to her cub. The fox promises her a good meal, and leads her to a farmyard full of sheep. Then he slips away, the farmers come running, and the wolf gets a beating while the sly fox gets away.',
quest: 'Your quest: find the christening table, find the sheep in the farmyard, and find the tree where the fox watches.',
steps: [{ id: 19, hint: 'Find the christening table.', say: 'Mother wolf asks the fox to be godfather to her little cub.' },
{ at: [3, 1, 10], hint: 'Find the sheep in the farmyard.', say: 'The fox leads the wolf to the farmer\'s sheep, then slips away. The farmers come running!' },
{ at: [3, 1, 17], hint: 'Find the tree where the fox watches.', say: 'The wolf gets a beating, and the sly fox watches from far away.' }],
win: 'Sly fox! You earned the Fox Whisker, and a Farmyard kit to build at home.' },
{ id: 'foxcat', abc: 'The Fox and the Cat', title: 'The Fox and the Cat', place: "The Cat's Tree", keep: 'Cat Whisker', color: '#7a8a5a', parts: [425, 1],
tpl: 'forest',
ach: ['One Good Trick', 'A hundred tricks, or one that works?'],
sum: 'The Fox and the Cat. A proud fox says he knows a hundred tricks and has a whole sack full of cunning. The cat knows only one trick. Then a hunter comes with four dogs. The cat springs up a tree, which is her one trick, while the fox with a hundred tricks is caught by the dogs.',
quest: 'Your quest: find where the cat meets the fox, find the path where the hunter comes, and find the tree the cat climbs.',
steps: [{ at: [12, 1, 17], hint: 'Find where the cat meets the fox.', say: 'The proud fox says: I know a hundred tricks! The cat says: I know only one.' },
{ at: [6, 0, 6], hint: 'Find the path where the hunter comes.', say: 'A hunter comes along the path with four dogs!' },
{ at: [10, 1, 14], hint: 'Find the tree the cat climbs.', say: 'The cat climbs the tree. That is her one trick! The fox with a hundred tricks is caught by the dogs.' }],
win: 'One good trick! You earned the Cat Whisker, and a Cat\'s Tree kit to build at home.' },
{ id: 'pink', abc: 'The Pink', title: 'The Pink', place: 'The Tower of the Pink', keep: 'Pink Flower', color: '#e070a0', parts: [426, 6],
tpl: 'castle', props: [[13, 1, 14, 73]],
ach: ['Wish Granted', 'Be careful what you wish. Unless you are the prince.'],
sum: 'The Pink. A wicked cook steals the queen\'s baby son, a boy who can make any wish come true, and the queen is shut in a tower for seven years, fed by angels as doves. The boy grows up, turns the cook into a black poodle, and turns the girl he loves into a pink flower to keep her safe. Then he goes home and sets his mother free.',
quest: 'Your quest: find the light by the castle door, find the pink flower, and find the queen\'s throne.',
steps: [{ at: [7, 1, 9], hint: 'Find the light by the castle door.', say: 'The wicked cook stole the baby prince. Now the boy wishes him into a black poodle!' },
{ at: [13, 1, 14], hint: 'Find the pink flower.', say: 'The prince turns the girl he loves into a pink flower, and keeps her safe with him.' },
{ at: [10, 1, 17], hint: 'Find the queen\'s throne.', say: 'His mother was shut in a tower for seven years, fed by angels as doves. The prince sets her free!' }],
win: 'The queen is free! You earned the Pink Flower, and a Tower of the Pink kit to build at home.' },
{ id: 'grethel', abc: 'Clever Grethel', title: 'Clever Grethel', place: "Grethel's Kitchen", keep: 'Chicken Wing', color: '#d08040', parts: [432, 3],
tpl: 'cottage',
ach: ['Just a Taste', 'Two chickens, one hungry cook, nobody the wiser.'],
sum: 'Clever Grethel. Clever Grethel the cook roasts two chickens for her master\'s guest. While she waits, she tastes a little bit, and a little bit more, until both chickens are gone! When the guest comes, she tells him the master wants to cut off his ears, so the guest runs away, and the master runs after him to get a chicken back.',
quest: 'Your quest: find the fire where the chickens roast, find the table where the guest will sit, and find the road where they run.',
steps: [{ id: 20, hint: 'Find the fire where the chickens roast.', say: 'Clever Grethel roasts two chickens, and tastes a little bit... and then a little bit more!' },
{ id: 19, hint: 'Find the table where the guest will sit.', say: 'She eats both chickens! When the guest comes, she tells him the master wants to cut off his ears.' },
{ at: [10, 0, 3], hint: 'Find the road where they run.', say: 'The guest runs away, and the master runs after him for a chicken. Clever Grethel is never found out!' }],
win: 'Clever Grethel! You earned the Chicken Wing, and a Grethel\'s Kitchen kit to build at home.' },
{ id: 'grandson', abc: 'The Old Man and His Grandson', title: 'The Old Man and His Grandson', place: "Grandfather's Table", keep: 'Wooden Bowl', color: '#a07a50', parts: [435, 1],
tpl: 'cottage', props: [[3, 1, 10, 5]],
ach: ['Kind Grandchild', 'Everyone gets old. Everyone gets a place at the table.'],
sum: 'The Old Man and His Grandson. A very old man\'s hands shake, and he spills his soup, so his son and daughter-in-law make him eat alone behind the stove from a wooden bowl. Then they see their little son making a little wooden trough, for them to eat from when they are old. They cry, and from then on the grandfather always eats at the table.',
quest: 'Your quest: find the warm stove in the corner, find the little bits of wood, and find the family table.',
steps: [{ id: 20, hint: 'Find the warm stove in the corner.', say: 'The old grandfather\'s hands shake, and he spills his soup. They make him eat alone behind the stove.' },
{ at: [3, 1, 10], hint: 'Find the little bits of wood.', say: 'The little grandson is making a wooden trough for his father and mother, for when they are old!' },
{ id: 19, hint: 'Find the family table.', say: 'The parents cry, and bring the grandfather back to the table. From then on he always eats with them.' }],
win: 'Everyone at the table! You earned the Wooden Bowl, and a Grandfather\'s Table kit to build at home.' },
// template places, chunk 8 (ABC Books lessons 436-484, 2026-10-25)
{ id: 'waternix', abc: 'The Water-Nix', title: 'The Water-Nix', place: "The Water-Nix's Well", keep: 'Little Comb', color: '#3a7a9a', parts: [436, 1],
tpl: 'well', roof: 54,
ach: ['Brush, Comb, Mirror', 'Three things to throw behind you. Remember them.'],
sum: 'The Water-Nix. A little brother and sister fall into a well, where a water-nix makes them work hard. One Sunday they run away. When she chases them, they throw a brush, a comb and a mirror behind them, and these turn into a hedge of bristles, a mountain of combs and a glass mountain, so the nix cannot follow.',
quest: 'Your quest: find the well, find the nix\'s fire, and find the tree where they run.',
steps: [{ at: [12, 1, 8], hint: 'Find the well.', say: 'A little brother and sister fall into a well, where a water-nix makes them work hard.' },
{ id: 20, hint: 'Find the nix\'s fire.', say: 'The girl must spin tangled flax, and the boy must chop wood with a blunt axe.' },
{ at: [16, 1, 15], hint: 'Find the tree where they run.', say: 'They throw a brush, a comb and a mirror. They become a hedge, a mountain of combs and a glass mountain, and the nix cannot follow!' }],
win: 'They got away! You earned the Little Comb, and a Water-Nix\'s Well kit to build at home.' },
{ id: 'littlehen', abc: 'The Death of the Little Hen', title: 'The Death of the Little Hen', place: 'The Nut Hill Brook', keep: 'Little Nut', color: '#a08050', parts: [437, 2],
tpl: 'mill', roof: 40,
ach: ['Sad Little Story', 'Some stories are sad. That is all right.'],
sum: 'The Death of the Little Hen. A little hen swallows a nut that is too big, and it sticks in her throat. The cock runs to the spring for water, but everyone wants something first. The little hen dies, and many animals come to pull her little cart, but at the brook everything goes wrong. In the end the cock is all alone, and very sad.',
quest: 'Your quest: find the nut tree, find the brook, and find the soft hay in the mill.',
steps: [{ at: [3, 1, 4], hint: 'Find the nut tree.', say: 'The little hen swallows a big nut, and it sticks in her throat. The cock runs to fetch water.' },
{ at: [10, 0, 10], hint: 'Find the brook.', say: 'Many animals come to help pull the little cart, but at the brook everything goes wrong.' },
{ id: 67, hint: 'Find the soft hay in the mill.', say: 'The cock is left all alone, and he is very sad for his little hen.' }],
win: 'A sad story, well listened to. You earned the Little Nut, and a Nut Hill Brook kit to build at home.' },
{ id: 'lustig', abc: 'Brother Lustig', title: 'Brother Lustig', place: "Brother Lustig's Road", keep: 'Magic Knapsack', color: '#6a8a6a', parts: [439, 13],
tpl: 'castle', props: [[13, 1, 14, 21]],
ach: ['Merry Soldier', 'Anything you wish jumps into the knapsack. Even you.'],
sum: 'Brother Lustig. Brother Lustig, a merry old soldier, shares his bread with a beggar who is really Saint Peter. They travel together, and Lustig gets into all kinds of trouble. At last Saint Peter gives him a knapsack: whatever he wishes for jumps right into it, even devils! At heaven\'s gate he throws in the knapsack and wishes himself inside it.',
quest: 'Your quest: find the road where Brother Lustig walks, find the magic knapsack, and find the gate at the end of his journey.',
steps: [{ at: [10, 0, 3], hint: 'Find the road where Brother Lustig walks.', say: 'Brother Lustig, a merry old soldier, shares his bread with a beggar, who is really Saint Peter.' },
{ id: 21, hint: 'Find the magic knapsack.', say: 'Saint Peter gives him a knapsack: whatever he wishes for jumps right into it!' },
{ at: [10, 1, 17], hint: 'Find the gate at the end of his journey.', say: 'At heaven\'s gate he throws in his knapsack and wishes himself inside. Clever Brother Lustig gets in after all!' }],
win: 'Merry to the end! You earned the Magic Knapsack, and a Brother Lustig\'s Road kit to build at home.' },
{ id: 'gamblinghansel', abc: 'Gambling Hansel', title: 'Gambling Hansel', place: "Gambling Hansel's House", keep: 'Lucky Card', color: '#7a3a5a', parts: [452, 3],
tpl: 'cottage',
ach: ['Always Wins', 'Cards, dice and a tree that holds on to Death.'],
sum: 'Gambling Hansel. Hansel gambles away everything he has. When the Lord and Saint Peter visit, he gives them his bed anyway, and gets three wishes: cards that always win, dice that always win, and a tree nobody can climb down from without his say. Even Death gets stuck in the tree, and in the end not even heaven knows what to do with him.',
quest: 'Your quest: find the card table, find the tree nobody can climb down from, and find the bed he gave away.',
steps: [{ id: 19, hint: 'Find the card table.', say: 'Gambling Hansel loses everything playing cards. When the Lord and Saint Peter visit, he gives them his bed anyway.' },
{ at: [17, 1, 4], hint: 'Find the tree nobody can climb down from.', say: 'He wishes for a tree: whoever climbs it cannot come down without his say. Even Death gets stuck!' },
{ id: 31, hint: 'Find the bed he gave away.', say: 'He wins and wins at cards, even against the devil. In the end, even heaven does not know what to do with him!' }],
win: 'You earned the Lucky Card, and a Gambling Hansel\'s House kit to build at home.' },
{ id: 'hansinluck', abc: 'Hans in Luck', title: 'Hans in Luck', place: "Hans's Lucky Road", keep: 'Lump of Gold', color: '#d0b030', parts: [455, 8],
tpl: 'well', props: [[6, 1, 4, 57], [14, 1, 6, 4]],
ach: ['Luckiest Man Alive', 'Gold, horse, cow, pig, goose, stone... and free!'],
sum: 'Hans in Luck. After seven years of work, Hans gets a lump of gold as big as his head. It is heavy, so he swaps it for a horse, the horse for a cow, the cow for a pig, the pig for a goose, and the goose for a grindstone. When the grindstone falls into a well, Hans jumps for joy: now he has nothing to carry, and he runs home happy to his mother.',
quest: 'Your quest: find the lump of gold, find the grindstone, and find the well.',
steps: [{ id: 57, hint: 'Find the lump of gold.', say: 'Hans gets a lump of gold as big as his head. It is heavy, so he swaps it for a horse!' },
{ at: [14, 1, 6], hint: 'Find the grindstone.', say: 'Horse for cow, cow for pig, pig for goose, goose for a grindstone. Hans thinks he is the luckiest man alive!' },
{ at: [12, 1, 8], hint: 'Find the well.', say: 'The grindstone falls into the well. Now I am free! cries Hans, and he runs home happy to his mother.' }],
win: 'Lucky Hans! You earned the Lump of Gold, and a Hans\'s Lucky Road kit to build at home.' },
{ id: 'hansmarried', abc: 'Hans Married', title: 'Hans Married', place: "Hans's Fields", keep: 'Wedding Bell', color: '#b0a060', parts: [463, 2],
tpl: 'cottage', props: [[3, 1, 10, 67], [8, 1, 12, 21]],
ach: ['Lucky Groom', 'His fields? Not quite. His bride? Yes!'],
sum: 'Hans Married. Hans\'s rich cousin wants to find him a wife. When the bride\'s family comes to look, the cousin points at the fields and the grain and says: all this is for Hans. The bride\'s family believes it, and Hans marries Grethel, even though the fields were never really his.',
quest: 'Your quest: find the fields of grain, find the wedding presents, and find the table.',
steps: [{ id: 67, hint: 'Find the fields of grain.', say: 'Hans\'s cousin points at the fields and says: all this is for Hans! The bride\'s family believes it.' },
{ id: 21, hint: 'Find the wedding presents.', say: 'Hans marries Grethel, and there are presents for the wedding.' },
{ id: 19, hint: 'Find the table.', say: 'Hans is happy, even though the fields were never really his!' }],
win: 'Happy wedding! You earned the Wedding Bell, and a Hans\'s Fields kit to build at home.' },
{ id: 'goldchildren', abc: 'The Gold-Children', title: 'The Gold-Children', place: 'The Golden Fish Stream', keep: 'Golden Fish', color: '#e0b830', parts: [465, 6],
tpl: 'mill', props: [[3, 1, 14, 36], [4, 1, 14, 36], [17, 1, 13, 3], [17, 2, 13, 3]],
ach: ['Golden Twins', 'Two golden lilies, two golden brothers.'],
sum: 'The Gold-Children. A poor fisherman catches a golden fish that gives him a castle, if he never tells where it came from. Later his wife has two golden children, and two golden lilies grow: if one fades, that brother is in danger. One brother rides out into the world, and a witch turns him to stone, but his lily fades, and his brother comes and sets him free.',
quest: 'Your quest: find where the fisherman casts his line, find the two golden lilies, and find the golden child turned to stone.',
steps: [{ at: [10, 0, 10], hint: 'Find where the fisherman casts his line.', say: 'A poor fisherman catches a golden fish. It gives him a castle, but he must never tell where it came from!' },
{ at: [3, 1, 14], hint: 'Find the two golden lilies.', say: 'Two golden lilies grow for the golden twins. If one fades, its brother is in danger.' },
{ at: [17, 1, 13], hint: 'Find the golden child turned to stone.', say: 'A witch turns one brother to stone, but his lily fades, and the other brother comes and sets him free!' }],
win: 'The twins are together! You earned the Golden Fish, and a Golden Fish Stream kit to build at home.' },
{ id: 'foxgeese', abc: 'The Fox and the Geese', title: 'The Fox and the Geese', place: "The Geese's Meadow", keep: 'Goose Feather', color: '#e0e0d0', parts: [471, 1],
tpl: 'cottage', props: [[3, 1, 10, 51], [4, 1, 10, 51], [3, 1, 13, 51]],
ach: ['Still Praying', 'Ga, ga, ga. The story is not over yet.'],
sum: 'The Fox and the Geese. A fox comes to a meadow full of fat geese and says he will eat them all. The geese beg him: let us say one more prayer first. The first goose begins: ga, ga, ga, and the next one joins in, and the next. They are still praying now, and when they are finished, we will tell the rest of the story.',
quest: 'Your quest: find the geese in the meadow, find the path where the fox waits, and find the table at the farm.',
steps: [{ at: [3, 1, 10], hint: 'Find the geese in the meadow.', say: 'A fox comes to a meadow full of fat geese. I will eat you all, he says!' },
{ at: [10, 0, 3], hint: 'Find the path where the fox waits.', say: 'Let us pray first, say the geese, and the first one begins: ga, ga, ga!' },
{ id: 19, hint: 'Find the table at the farm.', say: 'They are still praying now, ga, ga, ga! When they finish, we will tell you the rest of the story.' }],
win: 'Ga, ga, ga! You earned the Goose Feather, and a Geese\'s Meadow kit to build at home.' },
{ id: 'poorrich', abc: 'The Poor Man and the Rich Man', title: 'The Poor Man and the Rich Man', place: "The Poor Man's House", keep: 'Wish Coin', color: '#8a7a6a', parts: [472, 6],
tpl: 'cottage', props: [[16, 1, 12, 57]],
ach: ['Kind Host', 'Let the traveller in. You never know who he is.'],
sum: 'The Poor Man and the Rich Man. A tired traveller knocks at a rich man\'s door and is sent away, but the poor man across the road gives him his own bed. The traveller is the good Lord himself, and he gives the poor man three wishes and a new house. The greedy rich man chases after him for three wishes too, and wastes every one of them.',
quest: 'Your quest: find the rich man\'s gold, find the poor man\'s bed, and find the table.',
steps: [{ id: 57, hint: 'Find the rich man\'s gold.', say: 'The rich man will not let the tired traveller in. But the traveller is the good Lord himself!' },
{ id: 31, hint: 'Find the poor man\'s bed.', say: 'The poor man gives the traveller his own bed, and gets three wishes and a new house.' },
{ id: 19, hint: 'Find the table.', say: 'The greedy rich man wastes his three wishes. The last one only gets his wife off a saddle!' }],
win: 'Kindness wins! You earned the Wish Coin, and a Poor Man\'s House kit to build at home.' },
{ id: 'lark', abc: 'The Singing, Springing Lark', title: 'The Singing, Springing Lark', place: "The Lion's Castle", keep: 'White Feather', color: '#c0a050', parts: [478, 7],
tpl: 'castle', props: [[13, 1, 14, 51]],
ach: ['Seven Years of Feathers', 'Follow the white feathers, and do not give up.'],
sum: 'The Singing, Springing Lark. A father picks a singing, springing lark for his youngest daughter, but it belongs to a lion. The lion is an enchanted prince, and the girl marries him. When a light touches him, he must fly away as a dove for seven years. She follows his white feathers, and with help from the sun, the moon and the winds, she wins him back.',
quest: 'Your quest: find the lark\'s tree, find the lion\'s throne, and find the white feather.',
steps: [{ at: [18, 1, 3], hint: 'Find the lark\'s tree.', say: 'A father picks a singing, springing lark from a tree for his youngest daughter, but a lion owns it.' },
{ at: [10, 1, 17], hint: 'Find the lion\'s throne.', say: 'The lion is an enchanted prince. The girl marries him, until a light touches him and he flies away as a dove.' },
{ at: [13, 1, 14], hint: 'Find the white feather.', say: 'For seven years she follows the dove\'s white feathers. With help from the sun, the moon and the winds, she wins him back!' }],
win: 'Together again! You earned the White Feather, and a Lion\'s Castle kit to build at home.' },
// template places, chunk 9 (ABC Books lessons 485-549, 2026-10-25)
{ id: 'goosegirl', abc: 'The Goose-Girl', title: 'The Goose-Girl', place: "Falada's Gate", keep: 'Curdken\'s Hat', color: '#e8e0b0', parts: [485, 8],
tpl: 'castle', props: [[7, 2, 8, 51], [3, 1, 5, 51], [13, 1, 14, 20]],
ach: ['Blow, Wind, Blow', 'Curdken chased his hat. The princess kept her hair.'],
sum: 'The Goose-Girl. A princess rides to marry a prince, but her wicked maid makes her swap places. The real princess has to mind the geese with a boy named Curdken. The head of her faithful horse Falada hangs over the gate and speaks to her, and when she sings, the wind blows Curdken\'s hat away. She tells her story to an iron stove, the old king listens, and the true princess marries the prince.',
quest: 'Your quest: find Falada\'s head over the gate, find the geese in the meadow, and find the iron stove.',
steps: [{ at: [7, 2, 8], hint: 'Find Falada\'s head over the gate.', say: 'Falada, Falada, there thou hangest! The horse\'s head speaks to the real princess.' },
{ at: [3, 1, 5], hint: 'Find the geese in the meadow.', say: 'The princess minds the geese. She sings, and the wind blows Curdken\'s hat away!' },
{ id: 20, hint: 'Find the iron stove.', say: 'She tells her story to the iron stove, and the old king listens. The true princess marries the prince!' }],
win: 'The true princess! You earned Curdken\'s Hat, and a Falada\'s Gate kit to build at home.' },
{ id: 'younggiant', abc: 'The Young Giant', title: 'The Young Giant', place: "The Young Giant's Mill", keep: 'Iron Staff', color: '#7a6a5a', parts: [493, 10],
tpl: 'mill',
ach: ['Strongest Boy', 'A millstone for a collar. No problem.'],
sum: 'The Young Giant. A boy no bigger than a thumb is raised by a giant, and grows so strong that he can pull trees out of the ground. He works for a smith, a farmer and a miller, and they all try to get rid of him, but nothing can hurt him. When the miller drops a millstone on him, he wears it like a collar.',
quest: 'Your quest: find the tree he pulls up, find the millstone, and find the bridge.',
steps: [{ at: [17, 1, 4], hint: 'Find the tree he pulls up.', say: 'A tiny boy is raised by a giant, and grows so strong that he pulls a whole tree out of the ground!' },
{ at: [8, 1, 15], hint: 'Find the millstone.', say: 'The miller drops a millstone on him, but he wears it like a collar!' },
{ at: [10, 0, 10], hint: 'Find the bridge.', say: 'He works for a mean bailiff for a year, and kicks him far over the hills. The young giant always wins!' }],
win: 'So strong! You earned the Iron Staff, and a Young Giant\'s Mill kit to build at home.' },
{ id: 'gnome', abc: 'The Gnome', title: 'The Gnome', place: "The Gnome's Well", keep: 'Forbidden Apple', color: '#6a8a4a', parts: [503, 6],
tpl: 'well',
ach: ['Down the Well', 'Three princesses, three dragons, one little gnome.'],
sum: 'The Gnome. Three princesses eat apples from a forbidden tree and the ground swallows them. Three huntsmen go to look for them. The youngest is let down a deep well and saves all three from dragons, but his brothers pull up the princesses and leave him below. A little gnome helps him get out, and he marries the youngest princess.',
quest: 'Your quest: find the apple tree, find the well that goes deep underground, and find the little gnome\'s fire.',
steps: [{ at: [4, 1, 5], hint: 'Find the apple tree.', say: 'Three princesses eat apples from the forbidden tree, and the ground swallows them up!' },
{ at: [12, 1, 8], hint: 'Find the well that goes deep underground.', say: 'The youngest huntsman is let down the well, and saves all three princesses from the dragons.' },
{ id: 20, hint: 'Find the little gnome\'s fire.', say: 'His brothers leave him underground, but a little gnome helps him out, and he marries the youngest princess.' }],
win: 'Out of the well! You earned the Forbidden Apple, and a Gnome\'s Well kit to build at home.' },
{ id: 'goldenmountain', abc: 'The King of the Golden Mountain', title: 'The King of the Golden Mountain', place: 'The Golden Mountain', keep: 'Wishing Ring', color: '#e0a820', parts: [509, 8],
tpl: 'palace', wall: 57, props: [[6, 4, 16, 49]],
ach: ['Golden King', 'A cloak, a sword and boots. And a very useful ring.'],
sum: 'The King of the Golden Mountain. A merchant\'s son is sent away in a little boat and comes to an enchanted castle on a golden mountain. He breaks the spell on the princess and becomes king. She gives him a wishing ring, and when he loses her, he wins a cloak that makes him invisible, a sword and seven-league boots from three giants, and finds his way back.',
quest: 'Your quest: climb the golden mountain, find the magic ring, and find the king\'s throne.',
steps: [{ at: [10, 3, 13], hint: 'Climb the golden mountain.', say: 'A merchant\'s son floats away in a little boat and comes to an enchanted castle on a golden mountain.' },
{ at: [6, 4, 16], hint: 'Find the magic ring.', say: 'The princess gives him a ring: turn it, and you can wish yourself anywhere!' },
{ at: [10, 4, 18], hint: 'Find the king\'s throne.', say: 'With a cloak, a sword and boots from three giants, he wins his way back. He is King of the Golden Mountain!' }],
win: 'King of the Golden Mountain! You earned the Wishing Ring, and a Golden Mountain kit to build at home.' },
{ id: 'raven', abc: 'The Raven', title: 'The Raven', place: "The Raven's Castle", keep: 'Raven Ring', color: '#2a2a3a', parts: [517, 7],
tpl: 'castle', props: [[7, 1, 14, 31]],
ach: ['Stay Awake', 'Three days in a row he fell asleep. The fourth time, he made it.'],
sum: 'The Raven. A queen wishes her naughty little daughter were a raven, and she flies away. A man promises to free her, but he must not eat or drink what an old woman offers. Three times he falls asleep when the princess comes in her golden carriage. At last he climbs the glass mountain to her golden castle and drops her ring in her cup, and she is free.',
quest: 'Your quest: find the tree where the raven sits, find where the man falls asleep, and find the golden castle.',
steps: [{ at: [2, 1, 3], hint: 'Find the tree where the raven sits.', say: 'A queen wishes her naughty daughter were a raven, and she flies away! A man promises to free her.' },
{ id: 31, hint: 'Find where the man falls asleep.', say: 'Three times he falls asleep when she comes in her golden carriage. She leaves bread, wine and a golden ring.' },
{ at: [10, 1, 17], hint: 'Find the golden castle.', say: 'He climbs the glass mountain, drops the ring in her cup, and she is free!' }],
win: 'She is free! You earned the Raven Ring, and a Raven\'s Castle kit to build at home.' },
{ id: 'wisedaughter', abc: "The Peasant's Wise Daughter", title: "The Peasant's Wise Daughter", place: 'The Golden Mortar Palace', keep: 'Golden Mortar', color: '#c0a040', parts: [524, 5],
tpl: 'palace', props: [[6, 1, 4, 57], [14, 4, 16, 21]],
ach: ['Wise Answer', 'Neither dressed nor undressed, neither riding nor walking.'],
sum: 'The Peasant\'s Wise Daughter. A peasant finds a golden mortar and gives it to the king, though his clever daughter warned that the king will ask for the pestle too. The king hears how wise she is and tests her with a riddle: come neither dressed nor undressed, neither riding nor walking. She does it, and he marries her. Later he sends her away, saying she may take what she loves best, so she takes him!',
quest: 'Your quest: find the golden mortar, find the king\'s throne, and find the sack.',
steps: [{ at: [6, 1, 4], hint: 'Find the golden mortar.', say: 'A peasant finds a golden mortar. My daughter said: do not give it to the king without the pestle!' },
{ at: [10, 4, 18], hint: 'Find the king\'s throne.', say: 'The king says: come neither dressed nor undressed, neither riding nor walking. She does it, wrapped in a fishing net!' },
{ id: 21, hint: 'Find the sack.', say: 'Take what you love best, says the king. She takes the sleeping king home in a sack. He loves her again!' }],
win: 'What a wise queen! You earned the Golden Mortar, and a Golden Mortar Palace kit to build at home.' },
{ id: 'hildebrand', abc: 'Old Hildebrand', title: 'Old Hildebrand', place: "Hildebrand's House", keep: 'Basket of Eggs', color: '#b09060', parts: [529, 5],
tpl: 'cottage', props: [[3, 1, 10, 77]],
ach: ['Basket Ride', 'Carried home in a basket of eggs. Do not break any!'],
sum: 'Old Hildebrand. Old Hildebrand\'s wife and the parson want to have a feast while he is away. A friend carries Hildebrand home hidden in a basket of eggs. Inside, the wife and the parson are feasting and singing songs. Hildebrand sings from his basket, jumps out, and chases the parson away.',
quest: 'Your quest: find the basket of eggs, find the feast table, and find the fire.',
steps: [{ at: [3, 1, 10], hint: 'Find the basket of eggs.', say: 'Old Hildebrand climbs into a basket of eggs, and a friend carries him home.' },
{ id: 19, hint: 'Find the feast table.', say: 'His wife and the parson are having a feast, and they sing songs about it.' },
{ id: 20, hint: 'Find the fire.', say: 'Hildebrand sings from his basket by the fire, jumps out, and chases the parson away!' }],
win: 'Surprise! You earned the Basket of Eggs, and a Hildebrand\'s House kit to build at home.' },
{ id: 'threebirds', abc: 'The Three Little Birds', title: 'The Three Little Birds', place: 'The Singing River', keep: 'Little Bird', color: '#6aa0c0', parts: [534, 6],
tpl: 'mill', props: [[10, 1, 14, 59]],
ach: ['Away to the Water', 'Till I see you again.'],
sum: 'The Three Little Birds. A king marries the youngest of three sisters. Each time she has a baby, her jealous sisters throw it into the river and say something terrible, and a little bird sings: away to the water. A kind fisherman saves all three children. When they grow up, they find the singing tree, the water of life and the bird, and the truth comes out.',
quest: 'Your quest: find the river, find the tree where the little bird sings, and find the water of life.',
steps: [{ at: [10, 0, 10], hint: 'Find the river.', say: 'Jealous sisters throw the queen\'s babies into the river, but a kind fisherman saves them.' },
{ at: [17, 1, 17], hint: 'Find the tree where the little bird sings.', say: 'Each time, a little bird sings: away to the water, till I see you again!' },
{ at: [10, 1, 14], hint: 'Find the water of life.', say: 'With the singing tree, the water of life and the bird, the children go to the king, and the truth comes out!' }],
win: 'The truth is out! You earned the Little Bird, and a Singing River kit to build at home.' },
{ id: 'wateroflife', abc: 'The Water of Life', title: 'The Water of Life', place: 'The Enchanted Castle', keep: 'Water of Life', color: '#40a0d0', parts: [540, 7],
tpl: 'palace', props: [[14, 4, 16, 59], [6, 4, 16, 57]],
ach: ['Kind Prince', 'He was polite to the dwarf. It paid off.'],
sum: 'The Water of Life. A king is very ill, and only the water of life can save him. His two proud sons are rude to a dwarf and get stuck. The youngest is kind, so the dwarf tells him where to find the water in an enchanted castle, along with a sword that beats armies and bread that never runs out. His brothers trick him, but the truth comes out, and the princess of the castle marries him.',
quest: 'Your quest: find the water of life, find the sword and the bread, and find the golden road.',
steps: [{ at: [14, 4, 16], hint: 'Find the water of life.', say: 'The kind prince is helpful to a dwarf, who tells him where the water of life is, in an enchanted castle.' },
{ at: [6, 4, 16], hint: 'Find the sword and the bread.', say: 'He takes a sword that beats whole armies and a loaf of bread that never runs out, and helps three kingdoms.' },
{ at: [10, 0, 3], hint: 'Find the golden road.', say: 'The princess has a golden road built. Only the one who rides straight up the middle is her true prince!' }],
win: 'The king is well again! You earned the Water of Life, and an Enchanted Castle kit to build at home.' },
{ id: 'knowall', abc: 'Doctor Knowall', title: 'Doctor Knowall', place: "Doctor Knowall's House", keep: 'Doctor\'s Book', color: '#5a6a8a', parts: [547, 3],
tpl: 'cottage', props: [[8, 1, 12, 21]],
ach: ['Lucky Guess', 'Crabb guessed the crab. What luck!'],
sum: 'Doctor Knowall. A poor peasant named Crabb buys a doctor\'s book and a sign that says Doctor Knowall. A rich lord asks him to find stolen money. At dinner, Crabb says: that was the first, meaning the first dish, but the servant who stole the money thinks he knows everything. He even guesses the crab under the cover, and finds where the money is hidden.',
quest: 'Your quest: find the doctor\'s books, find the dinner table, and find the hidden money.',
steps: [{ id: 35, hint: 'Find the doctor\'s books.', say: 'Crabb the peasant buys a doctor\'s book and a sign: Doctor Knowall!' },
{ id: 19, hint: 'Find the dinner table.', say: 'At dinner he says: that was the first! He means the dish, but the servant thinks he means the first thief!' },
{ id: 21, hint: 'Find the hidden money.', say: 'He guesses the crab under the dish, and finds where the stolen money is hidden. Everyone thinks he knows everything!' }],
win: 'Doctor Knowall knows all! You earned the Doctor\'s Book, and a Doctor Knowall\'s House kit to build at home.' },
// template places, chunk 10 (ABC Books lessons 550-602, 2026-10-25); from place 100 on the item ids are 1000 + i and 2000 + i
{ id: 'spiritbottle', abc: 'The Spirit in the Bottle', title: 'The Spirit in the Bottle', place: 'The Old Oak', keep: 'Healing Rag', color: '#5a7a4a', parts: [550, 6],
tpl: 'forest', props: [[15, 1, 17, 58]],
ach: ['Back in the Bottle', 'Can you really fit in there? Oops, yes.'],
sum: 'The Spirit in the Bottle. A poor student hears a voice under an old oak and finds a little bottle in its roots. A huge spirit jumps out and wants to break his neck! The clever student says he cannot believe something so big fits in such a small bottle, so the spirit shows him, and in he goes. To get out again, the spirit gives him a rag that heals wounds and turns iron into silver.',
quest: 'Your quest: find the old oak tree, find where the spirit grows huge, and find the silver axe.',
steps: [{ at: [10, 1, 14], hint: 'Find the old oak tree.', say: 'A poor student hears a voice under an old oak: let me out! He finds a little bottle in the roots.' },
{ at: [12, 1, 17], hint: 'Find where the spirit grows huge.', say: 'A huge spirit jumps out! Can you really fit in that little bottle? asks the student. The spirit shows him, and in he goes!' },
{ at: [15, 1, 17], hint: 'Find the silver axe.', say: 'The spirit gives him a rag: rub it on a wound and it heals, rub it on iron and it turns to silver!' }],
win: 'Clever student! You earned the Healing Rag, and an Old Oak kit to build at home.' },
{ id: 'sootybrother', abc: "The Devil's Sooty Brother", title: "The Devil's Sooty Brother", place: "The Devil's Kettles", keep: 'Bag of Sweepings', color: '#3a2a2a', parts: [556, 4],
tpl: 'castle', wall: 33, props: [[6, 1, 15, 20], [13, 1, 14, 12]],
ach: ['Sooty Soldier', 'Seven years without washing, and a bag of gold.'],
sum: 'The Devil\'s Sooty Brother. A poor soldier works for the devil for seven years. He keeps the fires going under the kettles, sweeps up, and never once looks into the kettles. He may not wash or cut his hair. His pay is a knapsack full of sweepings, and at home they turn into gold. He plays music for a king and marries the youngest princess.',
quest: 'Your quest: find the fires under the kettles, find the sweepings, and find the throne.',
steps: [{ id: 20, hint: 'Find the fires under the kettles.', say: 'A soldier works for the devil for seven years, keeping the fires going. He must never look into the kettles!' },
{ at: [13, 1, 14], hint: 'Find the sweepings.', say: 'His pay is a knapsack full of sweepings, and at home they turn into gold!' },
{ at: [10, 1, 17], hint: 'Find the throne.', say: 'He plays music for the king, and marries the youngest princess.' }],
win: 'Gold from soot! You earned the Bag of Sweepings, and a Devil\'s Kettles kit to build at home.' },
{ id: 'bearskin', abc: 'Bearskin', title: 'Bearskin', place: "Bearskin's Cottage", keep: 'Half a Ring', color: '#5a3a2a', parts: [560, 6],
tpl: 'cottage', props: [[8, 1, 12, 21]],
ach: ['Seven Years in a Bearskin', 'No washing, no combing, and a true bride at the end.'],
sum: 'Bearskin. A poor soldier makes a deal with the devil: for seven years he must wear a bearskin and never wash or comb his hair, but his pockets will always be full of gold. He helps a poor old man, whose youngest daughter promises to marry him even though he looks so wild. After seven years he comes back clean and handsome, drops half a ring in her cup, and she knows him.',
quest: 'Your quest: find the tree where he meets the devil, find his pocket full of gold, and find the wedding table.',
steps: [{ at: [3, 1, 17], hint: 'Find the tree where he meets the devil.', say: 'A poor soldier makes a deal: for seven years he must wear a bearskin and never wash or comb his hair.' },
{ id: 21, hint: 'Find his pocket full of gold.', say: 'His pockets are always full of gold, and he helps a poor old man. The youngest daughter promises to marry him.' },
{ id: 19, hint: 'Find the wedding table.', say: 'After seven years he is clean and handsome. He drops half a ring in her cup, and she knows him!' }],
win: 'A true bride! You earned the Half a Ring, and a Bearskin\'s Cottage kit to build at home.' },
{ id: 'willowwrenbear', abc: 'The Willow-Wren and the Bear', title: 'The Willow-Wren and the Bear', place: 'The Battlefield of the Animals', keep: 'Wren Feather', color: '#8a7a3a', parts: [566, 3],
tpl: 'forest',
ach: ['Little Wren, Big Win', 'Never call a wren\'s children rude names.'],
sum: 'The Willow-Wren and the Bear. The bear calls the little wren\'s children rude names, and the wren declares war. The bear brings all the four-footed animals, and the wren brings all the birds, bees and wasps. The fox will lift his tail as the signal to attack, but a wasp stings him, his tail drops, and all the four-footed animals run away. The bear has to say sorry.',
quest: 'Your quest: find the wren\'s nest, find where the animals gather, and find where the fox stands.',
steps: [{ at: [3, 1, 15], hint: 'Find the wren\'s nest.', say: 'The bear calls the little wren\'s children rude names. The wren says: this means war!' },
{ at: [14, 0, 11], hint: 'Find where the animals gather.', say: 'Bears, oxen and donkeys on one side, birds, bees and wasps on the other. The fox will lift his tail as a signal.' },
{ at: [12, 1, 17], hint: 'Find where the fox stands.', say: 'A wasp stings the fox, his tail drops, and all the four-footed animals run away. The bear says sorry!' }],
win: 'The wren wins! You earned the Wren Feather, and a Battlefield of the Animals kit to build at home.' },
{ id: 'porridge', abc: 'Sweet Porridge', title: 'Sweet Porridge', place: 'The Porridge Street', keep: 'Little Pot', color: '#e0c890', parts: [569, 1],
tpl: 'cottage',
ach: ['Stop, Little Pot!', 'Always remember the magic word to stop.'],
sum: 'Sweet Porridge. A poor girl meets an old woman in the wood who gives her a little pot. When she says cook, little pot, cook, it cooks good sweet porridge, and when she says stop, little pot, it stops. One day her mother says cook, but forgets the word to stop it, and the porridge fills the house, the street and the whole town!',
quest: 'Your quest: find the old woman in the wood, find the little pot on the fire, and find the street full of porridge.',
steps: [{ at: [3, 1, 4], hint: 'Find the old woman in the wood.', say: 'A poor girl meets an old woman in the wood, who gives her a little pot.' },
{ id: 20, hint: 'Find the little pot on the fire.', say: 'Cook, little pot, cook! And it cooks good sweet porridge.' },
{ at: [10, 0, 3], hint: 'Find the street full of porridge.', say: 'Mother forgets the word to stop it, and the porridge fills the house and the whole street! Stop, little pot!' }],
win: 'Stop, little pot! You earned the Little Pot, and a Porridge Street kit to build at home.' },
{ id: 'wisefolks', abc: 'Wise Folks', title: 'Wise Folks', place: "The Farmer's Road", keep: 'Purse of Money', color: '#9a8a5a', parts: [570, 6],
tpl: 'cottage', props: [[8, 1, 12, 21]],
ach: ['Even Sillier', 'He went looking for sillier people. He found them.'],
sum: 'Wise Folks. A farmer\'s wife sells their cows for only a promise of money, and he says he will leave unless he finds three people sillier than she is. On the road he finds a woman who gives him all her money to take to her dead husband in heaven, and her son chases after him and gives him his horse too. The farmer goes home happy: there are sillier people in the world.',
quest: 'Your quest: find the farmer\'s table, find the road, and find the bag of money.',
steps: [{ id: 19, hint: 'Find the farmer\'s table.', say: 'His wife sells the cows for only a promise of money. Find me three people sillier than you, says the farmer!' },
{ at: [10, 0, 3], hint: 'Find the road.', say: 'On the road he meets a woman who gives him all her money to take to her husband in heaven!' },
{ id: 21, hint: 'Find the bag of money.', say: 'There are sillier people in the world, says the farmer, and he goes home happy with the money.' }],
win: 'Wise folks indeed! You earned the Purse of Money, and a Farmer\'s Road kit to build at home.' },
{ id: 'snakestories', abc: 'Stories about Snakes', title: 'Stories about Snakes', place: 'The Little Snake\'s Yard', keep: 'Snake Crown', color: '#5a8a5a', parts: [576, 2],
tpl: 'cottage', props: [[3, 1, 10, 57]],
ach: ['Milk Sharer', 'Eat your bread too, little thing.'],
sum: 'Stories about Snakes. A little child shares her bowl of milk and bread with a little snake every day, and tells it: eat your bread too, little thing, not only the milk! The snake brings her a tiny golden crown. These are short old stories about snakes, and some of them are sad.',
quest: 'Your quest: find the child\'s bowl of milk, find the snake\'s golden crown, and find the child\'s bed.',
steps: [{ id: 19, hint: 'Find the child\'s bowl of milk.', say: 'A little child shares her bowl of milk and bread with a little snake every day.' },
{ at: [3, 1, 10], hint: 'Find the snake\'s golden crown.', say: 'The little snake brings its tiny golden crown as a present.' },
{ id: 31, hint: 'Find the child\'s bed.', say: 'Eat your bread too, little thing, says the child, not only the milk!' }],
win: 'You earned the Snake Crown, and a Little Snake\'s Yard kit to build at home.' },
{ id: 'millerboy', abc: "The Poor Miller's Boy and the Cat", title: "The Poor Miller's Boy and the Cat", place: "The Tabby Cat's Mill", keep: 'Silver Axe', color: '#9a8aa0', parts: [578, 4],
tpl: 'mill', props: [[11, 1, 14, 57]],
ach: ['Seven Years for a Cat', 'Best boss ever. Turned out to be a princess.'],
sum: 'The Poor Miller\'s Boy and the Cat. An old miller says the apprentice who brings him the best horse will get the mill. Hans, the youngest, follows a little tabby cat, and works for her for seven years, cutting wood with a silver axe and building a little silver house. She gives him a wonderful horse, and then comes in a golden carriage: she is really a king\'s daughter, and she marries Hans.',
quest: 'Your quest: find the cave in the forest, find the cat\'s silver tools, and find the cat\'s golden carriage.',
steps: [{ at: [3, 1, 4], hint: 'Find the tree by the cave in the forest.', say: 'Hans, the miller\'s youngest boy, lies down by a cave, and a little tabby cat says: come with me.' },
{ id: 21, hint: 'Find the cat\'s silver tools.', say: 'For seven years Hans works for the cat, cutting wood with a silver axe and building a little house.' },
{ id: 57, hint: 'Find the cat\'s golden carriage.', say: 'The little cat is really a king\'s daughter! She comes in a golden carriage and takes Hans away to be her husband.' }],
win: 'A princess cat! You earned the Silver Axe, and a Tabby Cat\'s Mill kit to build at home.' },
{ id: 'twotravellers', abc: 'The Two Travellers', title: 'The Two Travellers', place: "The Travellers' Road", keep: 'Tailor\'s Thimble', color: '#7a9a6a', parts: [582, 14],
tpl: 'forest',
ach: ['Merry Tailor', 'Kind to a foal, a stork, ducks and bees. They remembered.'],
sum: 'The Two Travellers. A merry little tailor and a grumpy shoemaker travel together. When they run out of food, the shoemaker is terribly cruel and takes the tailor\'s eyes. The tailor washes his eyes in the morning dew and can see again. He is kind to a foal, a stork, some ducks and a swarm of bees, and when the king gives him impossible tasks, the animals help him, and he marries the princess.',
quest: 'Your quest: find the long road, find the tree where he washes his eyes, and find where the animals thank him.',
steps: [{ at: [6, 0, 6], hint: 'Find the long road.', say: 'A merry tailor and a grumpy shoemaker travel together. The shoemaker is very unkind to him.' },
{ at: [10, 1, 8], hint: 'Find the tree where he washes his eyes.', say: 'The tailor washes his eyes with the morning dew, and he can see again!' },
{ at: [12, 1, 17], hint: 'Find where the animals thank him.', say: 'He spares a foal, a stork, ducks and bees, and they all help him later. The tailor marries the princess!' }],
win: 'Kindness wins! You earned the Tailor\'s Thimble, and a Travellers\' Road kit to build at home.' },
{ id: 'hedgehog', abc: 'Hans the Hedgehog', title: 'Hans the Hedgehog', place: "Hans the Hedgehog's Wood", keep: 'Bagpipe', color: '#8a6a4a', parts: [596, 7],
tpl: 'cottage', roof: 40,
ach: ['Prickly Prince', 'Half hedgehog, all heart.'],
sum: 'Hans the Hedgehog. A farmer wishes so hard for a child that he gets a boy who is half hedgehog. Hans the Hedgehog rides into the forest on a rooster, keeps pigs, and plays the bagpipes in a tree. He shows two lost kings the way home, if they promise him their daughters. His second bride is kind to him, his hedgehog skin is burned, and he is a handsome young man.',
quest: 'Your quest: find the hedgehog boy\'s tree, find the lost king\'s road, and find the wedding bed.',
steps: [{ at: [17, 1, 17], hint: 'Find the hedgehog boy\'s tree.', say: 'Hans the Hedgehog rides his rooster into the forest, keeps pigs, and plays his bagpipes in a tree.' },
{ at: [10, 0, 3], hint: 'Find the lost king\'s road.', say: 'He shows two lost kings the way home, if they promise him the first thing they see.' },
{ id: 31, hint: 'Find the wedding bed.', say: 'His bride is kind to him. His hedgehog skin is burned, and he is a handsome young man!' }],
win: 'A handsome prince! You earned the Bagpipe, and a Hans the Hedgehog\'s Wood kit to build at home.' },
// template places, chunk 11 (ABC Books lessons 603-640, 2026-10-25). Tale 110 is flagged in ABC Books and has no place.
{ id: 'shroud', abc: 'The Shroud', title: 'The Shroud', place: 'The Quiet House', keep: 'White Candle', color: '#d0d0e0', parts: [603, 1],
tpl: 'cottage', props: [[3, 1, 10, 49]],
ach: ['Gentle Heart', 'A sad little story about letting go.'],
sum: 'The Shroud. A mother cries day and night for her little child who has died. At night the child comes back in its little white shroud and says: my shroud will not dry, because of your tears. So the mother stops crying, and the child can rest peacefully.',
quest: 'Your quest: find the little bed, find the little light, and find the table where the mother sits.',
steps: [{ id: 31, hint: 'Find the little bed.', say: 'A mother cries day and night for her little child who has died.' },
{ at: [3, 1, 10], hint: 'Find the little light.', say: 'The child comes back at night in its little white shroud, and says: my shroud will not dry, because of your tears.' },
{ id: 19, hint: 'Find the table where the mother sits.', say: 'The mother stops crying, and the child can rest peacefully.' }],
win: 'You earned the White Candle, and a Quiet House kit to build at home.' },
{ id: 'skilfulhuntsman', abc: 'The Skilful Huntsman', title: 'The Skilful Huntsman', place: "The Giants' Castle", keep: 'Air-Gun', color: '#4a6a3a', parts: [604, 7],
tpl: 'castle', props: [[6, 1, 15, 20]],
ach: ['Never Misses', 'Three giants, one sleeping princess, one very good shot.'],
sum: 'The Skilful Huntsman. A young man learns to be a huntsman and gets an air-gun that never misses. He meets three giants by a fire and shoots the meat right out of their hands, so they want him to help them steal a princess. Instead he saves her from the giants, and after a lot of trouble he marries her.',
quest: 'Your quest: find the tree where he learns to hunt, find the giants\' fire, and find the princess\'s throne.',
steps: [{ at: [2, 1, 3], hint: 'Find the tree where he learns to hunt.', say: 'A young man learns to be a huntsman, and gets an air-gun that never misses.' },
{ id: 20, hint: 'Find the giants\' fire.', say: 'Three giants sit by a fire. He shoots the meat right out of their hands!' },
{ at: [10, 1, 17], hint: 'Find the princess\'s throne.', say: 'He saves the princess from the giants, and in the end he marries her.' }],
win: 'What a shot! You earned the Air-Gun, and a Giants\' Castle kit to build at home.' },
{ id: 'flail', abc: 'The Flail From Heaven', title: 'The Flail From Heaven', place: 'The Tree to Heaven', keep: 'Flail', color: '#a0b060', parts: [611, 1],
tpl: 'forest', props: [[15, 1, 17, 67]],
ach: ['Down on a Rope of Chaff', 'Up a tree to heaven, and back again.'],
sum: 'The Flail From Heaven. A farmer plants a seed, and it grows into a tree that reaches all the way up to heaven. He climbs up and sees the angels threshing oats. When the tree is cut down, he makes a rope out of chaff and climbs down, but lands in a deep hole. Luckily he still has a flail, so he can dig his way out.',
quest: 'Your quest: find the tree that grows up to heaven, find the chaff, and find where he lands.',
steps: [{ at: [10, 1, 8], hint: 'Find the tree that grows up to heaven.', say: 'A farmer plants a seed, and a tree grows all the way up to heaven! He climbs up.' },
{ id: 67, hint: 'Find the chaff.', say: 'In heaven the angels are threshing oats. He makes a rope out of chaff, and climbs down on it.' },
{ at: [12, 1, 17], hint: 'Find where he lands.', say: 'He lands in a deep hole, but he has the flail, so he can dig his way out!' }],
win: 'Back on the ground! You earned the Flail, and a Tree to Heaven kit to build at home.' },
{ id: 'twokings', abc: "The Two Kings' Children", title: "The Two Kings' Children", place: 'The Forest Palace', keep: 'Wooden Bead', color: '#6a8aa0', parts: [612, 12],
tpl: 'palace', props: [[6, 4, 16, 59]],
ach: ['Never Forget', 'She helped with every task. He forgot. She won him back.'],
sum: 'The Two Kings\' Children. A prince must work for a strange king, who gives him three impossible tasks. The youngest princess helps him: a whole forest cut down in a day, a great pond cleaned, a castle built overnight. They run away together, changing shape to escape. Then the prince forgets her, but she wins him back with three beautiful dresses, and they marry.',
quest: 'Your quest: find the forest he must cut down, find the clean pond, and find the wedding throne.',
steps: [{ at: [4, 1, 5], hint: 'Find the forest he must cut down.', say: 'The king gives the prince three hard tasks. The youngest princess helps him, and the whole forest is cut down in a day!' },
{ at: [6, 4, 16], hint: 'Find the clean pond.', say: 'She cleans the great pond and builds a castle overnight. Then they run away together!' },
{ at: [10, 4, 18], hint: 'Find the wedding throne.', say: 'The prince forgets her, but she wins him back with three beautiful dresses, and they marry.' }],
win: 'Remembered! You earned the Wooden Bead, and a Forest Palace kit to build at home.' },
{ id: 'cunningtailor', abc: 'The Cunning Little Tailor', title: 'The Cunning Little Tailor', place: "The Bear's Stable", keep: 'Fiddle Bow', color: '#8a6a7a', parts: [624, 4],
tpl: 'castle', props: [[6, 1, 12, 56], [7, 1, 14, 19]],
ach: ['Nuts, Not Pebbles', 'He cracked nuts. The bear cracked his teeth.'],
sum: 'The Cunning Little Tailor. A proud princess will marry whoever guesses her riddle, and a little tailor guesses that her hair is gold and silver. Then he must spend the night in a stable with a bear. He cracks nuts while the bear tries to crack pebbles, plays the fiddle until the bear dances, and tricks it into a vice. In the morning he marries the princess.',
quest: 'Your quest: find the princess\'s throne, find the bag of nuts, and find the workbench.',
steps: [{ at: [10, 1, 17], hint: 'Find the princess\'s throne.', say: 'The proud princess asks: what colours is my hair? Gold and silver! says the little tailor.' },
{ at: [6, 1, 12], hint: 'Find the bag of nuts.', say: 'He must spend the night with a bear. He cracks nuts, while the bear chews on pebbles!' },
{ id: 19, hint: 'Find the workbench.', say: 'He tricks the bear into a vice and plays his fiddle. In the morning he marries the princess!' }],
win: 'Cunning tailor! You earned the Fiddle Bow, and a Bear\'s Stable kit to build at home.' },
{ id: 'brightsun', abc: 'The Bright Sun Brings It to Light', title: 'The Bright Sun Brings It to Light', place: "The Tailor's House", keep: 'Sunbeam', color: '#e8c040', parts: [628, 2],
tpl: 'cottage',
ach: ['The Truth Comes Out', 'Nothing stays hidden from the bright sun.'],
sum: 'The Bright Sun Brings It to Light. A tailor does a terrible thing on a lonely road to take a poor man\'s money, and the man says: the bright sun will bring it to light. Years later the tailor sees the sun shining on his coffee and laughs about it. His wife makes him tell her why, she tells others, and the truth comes out.',
quest: 'Your quest: find the lonely road, find the breakfast table, and find the tailor\'s bed.',
steps: [{ at: [10, 0, 3], hint: 'Find the lonely road.', say: 'A tailor does a terrible thing on a lonely road, to take a poor man\'s money.' },
{ id: 19, hint: 'Find the breakfast table.', say: 'Years later the sun shines on his coffee, and he laughs: the bright sun wants to bring it to light!' },
{ id: 31, hint: 'Find the tailor\'s bed.', say: 'His wife tells, the truth comes out, and he is punished. The bright sun brings everything to light.' }],
win: 'The truth is out! You earned the Sunbeam, and a Tailor\'s House kit to build at home.' },
{ id: 'bluelight', abc: 'The Blue Light', title: 'The Blue Light', place: 'The Witch\'s Dry Well', keep: 'Blue Light', color: '#3a5ac0', parts: [630, 6],
tpl: 'well', roof: 34,
ach: ['What Do You Want, Master?', 'A blue light, a pipe, and a very helpful little man.'],
sum: 'The Blue Light. A soldier sent away by the king works for a witch, who lets him down a dry well to fetch a blue light. He keeps the light, and when he lights his pipe with it, a little black man appears who must do whatever he says. The little man helps him every time, and in the end the soldier marries the king\'s daughter.',
quest: 'Your quest: find the dry well, find the soldier\'s fire, and find the tree by the castle.',
steps: [{ at: [12, 1, 8], hint: 'Find the dry well.', say: 'A witch lets a soldier down a dry well to fetch a blue light. He keeps it.' },
{ id: 20, hint: 'Find the soldier\'s fire.', say: 'He lights his pipe with the blue light, and a little black man appears: what do you want, master?' },
{ at: [16, 1, 15], hint: 'Find the tree by the castle.', say: 'The little man helps him every time, and in the end the soldier marries the king\'s daughter.' }],
win: 'You earned the Blue Light, and a Witch\'s Dry Well kit to build at home.' },
{ id: 'wilfulchild', abc: 'The Wilful Child', title: 'The Wilful Child', place: 'The Quiet Clearing', keep: 'Little Rose', color: '#7a6a8a', parts: [636, 1],
tpl: 'forest', props: [[9, 1, 16, 73]],
ach: ['Kind Listener', 'A very short, very old story.'],
sum: 'The Wilful Child. A child is wilful and never does what its mother wants. When the child dies, even then its little arm keeps coming up out of the ground, until its mother taps it with a rod. Then at last the child rests. It is a very short and very old story.',
quest: 'Your quest: find the quiet clearing, find the little rose, and find the tree with the rod.',
steps: [{ at: [12, 1, 17], hint: 'Find the quiet clearing.', say: 'A child is wilful and never does what its mother wants.' },
{ at: [9, 1, 16], hint: 'Find the little rose.', say: 'Even under the ground, its little arm keeps coming up.' },
{ at: [10, 1, 14], hint: 'Find the tree with the rod.', say: 'Its mother taps the little arm with a rod, and then the child is at rest.' }],
win: 'You earned the Little Rose, and a Quiet Clearing kit to build at home.' },
{ id: 'surgeons', abc: 'The Three Army-Surgeons', title: 'The Three Army-Surgeons', place: 'The Surgeons\' Inn', keep: 'Magic Ointment', color: '#a05a5a', parts: [637, 4],
tpl: 'cottage', props: [[8, 1, 12, 21]],
ach: ['Cat\'s Eyes', 'He could see mice in the dark. Handy, sort of.'],
sum: 'The Three Army-Surgeons. Three army-surgeons stay at an inn and show off their magic ointment: each takes out his own hand, heart or eyes, to put back the next morning. But the maid\'s cat eats them in the night! She puts in a thief\'s hand, a pig\'s heart and a cat\'s eyes instead, and the surgeons start acting very strangely.',
quest: 'Your quest: find the inn table, find the cupboard, and find the surgeons\' beds.',
steps: [{ id: 19, hint: 'Find the inn table.', say: 'Three army-surgeons show off: each takes out his own hand, heart or eyes, to put back the next day with a magic ointment!' },
{ id: 21, hint: 'Find the cupboard.', say: 'The maid keeps them in the cupboard, but a cat eats them! She puts in a thief\'s hand, a pig\'s heart and a cat\'s eyes instead.' },
{ id: 31, hint: 'Find the surgeons\' beds.', say: 'The one with the cat\'s eyes sees mice in the dark, and the one with the pig\'s heart wants to roll in the mud!' }],
win: 'What a mix-up! You earned the Magic Ointment, and a Surgeons\' Inn kit to build at home.' },
// template places, chunk 12 (ABC Books lessons 641-691, 2026-10-25)
{ id: 'swabians', abc: 'The Seven Swabians', title: 'The Seven Swabians', place: 'The Swabians\' Meadow', keep: 'Long Spear', color: '#8a9a5a', parts: [641, 4],
tpl: 'forest',
ach: ['Brave Seven', 'Seven heroes, one spear, one terrible... hare.'],
sum: 'The Seven Swabians. Seven Swabians march out to see the world, all holding on to one long spear. A buzzing hornet makes them think an enemy drum is coming. Then they bravely charge at a terrible monster in the grass, and it turns out to be a hare!',
quest: 'Your quest: find the road where they march, find where the hornet buzzes, and find the monster in the grass.',
steps: [{ at: [10, 0, 3], hint: 'Find the road where they march.', say: 'Seven Swabians march out to see the world, all holding on to one long spear!' },
{ at: [10, 1, 8], hint: 'Find where the hornet buzzes.', say: 'A hornet buzzes past, and they think it is an enemy drum!' },
{ at: [12, 1, 17], hint: 'Find the monster in the grass.', say: 'They all charge at a terrible monster... and it is only a hare!' }],
win: 'Brave Swabians! You earned the Long Spear, and a Swabians\' Meadow kit to build at home.' },
{ id: 'apprentices', abc: 'The Three Apprentices', title: 'The Three Apprentices', place: 'The Apprentices\' Inn', keep: 'Money Purse', color: '#6a5a4a', parts: [645, 4],
tpl: 'cottage', props: [[8, 1, 12, 21]],
ach: ['All Three of Us', 'For money. And quite right too.'],
sum: 'The Three Apprentices. Three poor apprentices promise the devil that they will only ever say three things: all three of us, for money, and quite right too. When a wicked innkeeper robs a rich man, those words make them look guilty, and they are nearly punished. At the last moment the devil comes and shows that the innkeeper is the real thief.',
quest: 'Your quest: find the road where they meet the devil, find the inn table, and find the money chest.',
steps: [{ at: [10, 0, 3], hint: 'Find the road where they meet the devil.', say: 'Three poor apprentices promise the devil to say only: all three of us, for money, and quite right too!' },
{ id: 19, hint: 'Find the inn table.', say: 'An innkeeper robs a rich man, and the apprentices can only say their three sayings. They are nearly punished!' },
{ id: 21, hint: 'Find the money chest.', say: 'The devil comes to save them, and shows that the innkeeper is the real thief!' }],
win: 'Quite right too! You earned the Money Purse, and an Apprentices\' Inn kit to build at home.' },
{ id: 'fearednothing', abc: "The King's Son Who Feared Nothing", title: "The King's Son Who Feared Nothing", place: 'The Enchanted Castle of the Lion', keep: 'Apple of Life', color: '#a07030', parts: [649, 7],
tpl: 'castle', props: [[6, 1, 12, 6]],
ach: ['Fears Nothing', 'Giant ninepins, a lion friend, three long nights.'],
sum: 'The King\'s Son Who Feared Nothing. A prince who is afraid of nothing plays ninepins with a giant, and fetches an apple from the Tree of Life at the end of the world. A lion follows him like a friend. In an enchanted castle he lets the spirits trouble him for three nights without a word, and the princess is set free.',
quest: 'Your quest: find the giant\'s ninepins, find the tree of life, and find the enchanted princess.',
steps: [{ at: [6, 1, 12], hint: 'Find the giant\'s ninepins.', say: 'A prince who fears nothing plays ninepins with a giant\'s huge balls.' },
{ at: [18, 1, 3], hint: 'Find the tree of life.', say: 'He picks an apple from the Tree of Life, and a lion follows him like a friend.' },
{ at: [10, 1, 17], hint: 'Find the enchanted princess.', say: 'For three nights he lets the spirits trouble him without a word, and the princess is free!' }],
win: 'Fearless! You earned the Apple of Life, and an Enchanted Castle of the Lion kit to build at home.' },
{ id: 'donkeycabbages', abc: 'Donkey Cabbages', title: 'Donkey Cabbages', place: 'The Cabbage Garden', keep: 'Wishing Cloak', color: '#7ab050', parts: [656, 9],
tpl: 'cottage', props: [[3, 1, 10, 38]],
ach: ['Hee-Haw!', 'Never trust a witch\'s salad.'],
sum: 'Donkey Cabbages. A kind huntsman helps an old woman and gets a bird\'s heart that puts a gold piece under his pillow every morning, and a cloak that can wish him anywhere. A witch and her daughter trick him out of both. Lost and hungry, he eats a cabbage and turns into a donkey, and another kind of cabbage turns him back. So he feeds the donkey cabbages to the witches!',
quest: 'Your quest: find the huntsman\'s pillow, find the cabbages in the garden, and find the road to the mill.',
steps: [{ id: 31, hint: 'Find the huntsman\'s pillow.', say: 'He eats a bird\'s heart, and every morning there is a gold piece under his pillow!' },
{ at: [3, 1, 10], hint: 'Find the cabbages in the garden.', say: 'He eats a cabbage, and turns into a donkey! Another cabbage turns him back.' },
{ at: [10, 0, 3], hint: 'Find the road to the mill.', say: 'He feeds the cabbages to the wicked witch and her daughter. Hee-haw! Now they are donkeys!' }],
win: 'Hee-haw! You earned the Wishing Cloak, and a Cabbage Garden kit to build at home.' },
{ id: 'oldwomanwood', abc: 'The Old Woman in the Wood', title: 'The Old Woman in the Wood', place: 'The Dove\'s Tree', keep: 'Plain Ring', color: '#6a9a6a', parts: [665, 3],
tpl: 'forest', props: [[15, 1, 17, 21]],
ach: ['The Plain Ring', 'Many rings, but only one was right.'],
sum: 'The Old Woman in the Wood. A servant girl is lost in the forest. A white dove brings her a little key: open the tree, and there is food, a bed and beautiful clothes. The dove asks her to go to the old woman\'s house and take a plain ring from all the rings there. She does, and the tree turns into a prince, set free from the old witch\'s spell.',
quest: 'Your quest: find the tree where the dove lives, find the little house in the wood, and find the tree that turns into a prince.',
steps: [{ at: [10, 1, 14], hint: 'Find the tree where the dove lives.', say: 'A white dove brings her a little key: open the tree, and you will find food.' },
{ id: 21, hint: 'Find the old woman\'s house in the wood.', say: 'In the old woman\'s house there are many rings. She takes the plain one.' },
{ at: [12, 1, 17], hint: 'Find the tree that turns into a prince.', say: 'The tree turns into a prince! The witch turned him into a tree, and the ring set him free.' }],
win: 'The prince is free! You earned the Plain Ring, and a Dove\'s Tree kit to build at home.' },
{ id: 'threebrothers', abc: 'The Three Brothers', title: 'The Three Brothers', place: "The Father's House", keep: 'Horseshoe', color: '#7a6a5a', parts: [668, 3],
tpl: 'cottage', props: [[3, 1, 10, 4]],
ach: ['Best Trade', 'Barber, smith or fencer? All three!'],
sum: 'The Three Brothers. A father has only one house, so he says it will go to the son who learns his trade best. The barber shaves a running hare without a nick, the smith puts new shoes on a galloping horse, and the fencer swings his sword so fast in the rain that not a drop touches him. The fencer wins, but they all live in the house together.',
quest: 'Your quest: find where the hare runs by, find the smith\'s anvil, and find the father\'s table.',
steps: [{ at: [10, 0, 3], hint: 'Find where the hare runs by.', say: 'The barber shaves a running hare, without even a nick!' },
{ at: [3, 1, 10], hint: 'Find the smith\'s anvil.', say: 'The smith puts new shoes on a galloping horse!' },
{ id: 19, hint: 'Find the father\'s table.', say: 'The fencer swings his sword so fast that not one raindrop touches him. He wins the house, and they all live there together.' }],
win: 'All three are winners! You earned the Horseshoe, and a Father\'s House kit to build at home.' },
{ id: 'devilgrandmother', abc: 'The Devil and his Grandmother', title: 'The Devil and his Grandmother', place: 'The Dragon\'s Riddle House', keep: 'Magic Whip', color: '#8a3a3a', parts: [671, 4],
tpl: 'castle', wall: 33, props: [[6, 1, 12, 67], [13, 1, 14, 20]],
ach: ['Riddle Guessed', 'Grandmother always knows.'],
sum: 'The Devil and his Grandmother. Three poor soldiers hide in a cornfield, and a dragon, who is really the devil, carries them away. He gives them a whip that makes gold, but in seven years they must guess his riddle or belong to him. One soldier finds the devil\'s grandmother, who hides him and gets the devil to tell the answers. The soldiers guess right and keep the whip.',
quest: 'Your quest: find the cornfield where they hide, find the grandmother by the fire, and find the dragon\'s seat.',
steps: [{ id: 67, hint: 'Find the cornfield where they hide.', say: 'Three soldiers hide in a cornfield. A dragon carries them away and gives them a magic whip, if they can guess his riddle in seven years.' },
{ id: 20, hint: 'Find the grandmother by the fire.', say: 'The devil\'s grandmother hides one soldier and listens as the devil tells the answers!' },
{ at: [10, 1, 17], hint: 'Find the dragon\'s seat.', say: 'The soldiers know the answers, so the devil has no power over them, and they keep the magic whip!' }],
win: 'Riddle solved! You earned the Magic Whip, and a Dragon\'s Riddle House kit to build at home.' },
{ id: 'ferdinand', abc: 'Ferdinand the Faithful', title: 'Ferdinand the Faithful', place: "Ferdinand's Palace", keep: 'Golden Pen', color: '#c0b060', parts: [675, 6],
tpl: 'palace', props: [[6, 4, 16, 57]],
ach: ['Faithful Rider', 'A white horse that talks, and a golden pen.'],
sum: 'Ferdinand the Faithful. Ferdinand the Faithful has a clever white horse that can talk. On the road he finds a golden pen, and is kind to a fish and some birds. His jealous companion, Ferdinand the Unfaithful, keeps getting the king to send him on dangerous tasks, but the animals help him every time. He brings back the princess, and in the end she marries Ferdinand the Faithful.',
quest: 'Your quest: climb to the king\'s palace, find the golden pen, and go to the throne.',
steps: [{ at: [10, 3, 13], hint: 'Climb to the king\'s palace.', say: 'Ferdinand the Faithful rides his clever white horse, which can talk.' },
{ at: [6, 4, 16], hint: 'Find the golden pen.', say: 'He finds a golden pen on the road, and feeds a fish and some birds, so they help him later.' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'He brings back the princess, and in the end she marries Ferdinand the Faithful.' }],
win: 'Faithful wins! You earned the Golden Pen, and a Ferdinand\'s Palace kit to build at home.' },
{ id: 'ironstove', abc: 'The Iron Stove', title: 'The Iron Stove', place: 'The Iron Stove in the Forest', keep: 'Magic Nut', color: '#5a5a6a', parts: [681, 8],
tpl: 'forest', props: [[15, 1, 17, 20]],
ach: ['Scrape, Scrape', 'An iron stove, a prince inside, three magic nuts.'],
sum: 'The Iron Stove. A princess lost in the forest finds an iron stove with a prince shut inside by a witch. She scrapes a hole and sets him free, but she breaks her promise and he disappears. She walks over glass mountains and through the world, and with three magic nuts that hold beautiful dresses, she finds him again and they marry.',
quest: 'Your quest: find the iron stove in the forest, find where she scrapes a hole, and find where she finds him again.',
steps: [{ id: 20, hint: 'Find the iron stove in the forest.', say: 'A princess finds an iron stove in the forest. A prince is shut inside it by a witch!' },
{ at: [10, 1, 14], hint: 'Find where she scrapes a hole.', say: 'She scrapes a hole, and the prince is free. But she breaks her promise, and he is gone!' },
{ at: [12, 1, 17], hint: 'Find where she finds him again.', say: 'With three magic nuts, she finds him again, and they marry.' }],
win: 'Found him! You earned the Magic Nut, and an Iron Stove in the Forest kit to build at home.' },
{ id: 'lazyspinner', abc: 'The Lazy Spinner', title: 'The Lazy Spinner', place: "The Lazy Spinner's House", keep: 'Reel', color: '#b0a080', parts: [689, 3],
tpl: 'cottage', props: [[8, 1, 12, 68]],
ach: ['Whoever Reels', 'Shall die! Or so the tree said.'],
sum: 'The Lazy Spinner. A lazy wife does not want to spin or reel her yarn. When her husband goes to cut wood for a reel, she hides behind a tree and calls: whoever reels shall die! The frightened husband believes it, and the lazy wife never has to work.',
quest: 'Your quest: find the spinning wheel, find the tree where she hides, and find the table.',
steps: [{ id: 68, hint: 'Find the spinning wheel.', say: 'A lazy wife does not want to spin, so she tells her husband she has no reel.' },
{ at: [17, 1, 4], hint: 'Find the tree where she hides.', say: 'She hides behind a tree and calls: whoever reels shall die! The husband drops the wood.' },
{ id: 19, hint: 'Find the table.', say: 'So the yarn is never reeled, and the lazy wife never has to work.' }],
win: 'Lazy, but clever! You earned the Reel, and a Lazy Spinner\'s House kit to build at home.' },
// template places, chunk 13 (ABC Books lessons 692-740, 2026-10-25)
{ id: 'fourbrothers', abc: 'The Four Skilful Brothers', title: 'The Four Skilful Brothers', place: 'The Four Brothers\' Castle', keep: 'Finch Egg', color: '#6a7aa0', parts: [692, 6],
tpl: 'castle', props: [[6, 1, 12, 3]],
ach: ['Teamwork', 'See it, take it, shoot it, sew it back together.'],
sum: 'The Four Skilful Brothers. Four brothers learn four trades: one is a thief, one an astronomer, one a huntsman and one a tailor. To show their skill, the astronomer spots five eggs in a nest, the thief takes them without the bird noticing, the huntsman shoots them, and the tailor sews them back together. Then they work together to rescue a princess from a dragon.',
quest: 'Your quest: find the tree with the bird\'s nest, find the dragon\'s rock, and go to the throne.',
steps: [{ at: [2, 1, 3], hint: 'Find the tree with the bird\'s nest.', say: 'The astronomer sees five eggs, the thief takes them, the huntsman shoots them, and the tailor sews them back together!' },
{ at: [6, 1, 12], hint: 'Find the dragon\'s rock.', say: 'A dragon has carried away the princess. The four brothers sail out and find her on a rock in the sea.' },
{ at: [10, 1, 17], hint: 'Go to the throne.', say: 'The king gives each brother half a kingdom, and they all live happily.' }],
win: 'Four skilful brothers! You earned the Finch Egg, and a Four Brothers\' Castle kit to build at home.' },
{ id: 'oneeye', abc: 'One-eye, Two-eyes, and Three-eyes', title: 'One-eye, Two-eyes, and Three-eyes', place: "Two-eyes's Garden", keep: 'Golden Apple', color: '#c0a0c0', parts: [698, 10],
tpl: 'cottage', props: [[3, 1, 10, 84], [16, 1, 8, 89]],
ach: ['Little Goat, Bleat', 'Little table, appear!'],
sum: 'One-eye, Two-eyes, and Three-eyes. Two-eyes looks just like everyone else, so her sisters with one eye and three eyes are unkind to her and give her hardly any food. A wise woman tells her: say little goat, bleat, little table, appear, and a table full of food will come. Later a tree with silver leaves and golden apples grows, and only Two-eyes can pick them, so a knight takes her away to his castle.',
quest: 'Your quest: find Two-eyes\'s little goat, find the tree with silver leaves, and find the table.',
steps: [{ at: [3, 1, 10], hint: 'Find Two-eyes\'s little goat.', say: 'Little goat, bleat, little table, appear! And a table full of food appears for hungry Two-eyes.' },
{ at: [16, 1, 8], hint: 'Find the tree with silver leaves.', say: 'A tree with silver leaves and golden apples grows. Only Two-eyes can pick its apples!' },
{ id: 19, hint: 'Find the table.', say: 'A knight asks for a branch of the tree, and Two-eyes gives it. He takes her away to his castle.' }],
win: 'Two-eyes is happy! You earned the Golden Apple, and a Two-eyes\'s Garden kit to build at home.' },
{ id: 'katrinelje', abc: 'Fair Katrinelje and Pif-Paf-Poltrie', title: 'Fair Katrinelje and Pif-Paf-Poltrie', place: "Katrinelje's House", keep: 'Little Bit of Everything', color: '#d08aa0', parts: [708, 1],
tpl: 'cottage', roof: 40,
ach: ['Good Day, Father Hollenthe', 'Ask everyone in the house!'],
sum: 'Fair Katrinelje and Pif-Paf-Poltrie. Pif-Paf-Poltrie comes to ask for Fair Katrinelje. Good day, Father Hollenthe! He must ask the father, the mother, the brother, the sister and even the cow. Katrinelje has a little bit of everything, and so does he, so they marry. It is a funny little story that sounds like a song.',
quest: 'Your quest: find the road where Pif-Paf-Poltrie comes, find the warm fire, and find the table.',
steps: [{ at: [10, 0, 3], hint: 'Find the road where Pif-Paf-Poltrie comes.', say: 'Good day, Father Hollenthe! Pif-Paf-Poltrie comes to ask for Fair Katrinelje.' },
{ id: 20, hint: 'Find the warm fire.', say: 'Ask the mother, the brother, the sister, and even the cow!' },
{ id: 19, hint: 'Find the table.', say: 'Katrinelje has a little bit of everything, and so has he. So they marry!' }],
win: 'Pif-paf! You earned the Little Bit of Everything, and a Katrinelje\'s House kit to build at home.' },
{ id: 'foxhorse', abc: 'The Fox and the Horse', title: 'The Fox and the Horse', place: "The Fox's Wood", keep: 'Horse Tail', color: '#a07050', parts: [709, 2],
tpl: 'forest',
ach: ['Stronger than a Lion', 'With a little help from a fox.'],
sum: 'The Fox and the Horse. A farmer sends his old horse away: come back when you are stronger than a lion. In the wood a fox tells the horse to lie down and pretend to be dead. Then the fox tells a lion there is a dead horse to eat, ties the lion\'s legs to the horse\'s tail, and the horse jumps up and drags the lion all the way home.',
quest: 'Your quest: find the farmer\'s gate, find the fox in the wood, and find where the lion sleeps.',
steps: [{ at: [10, 0, 3], hint: 'Find the farmer\'s gate.', say: 'The farmer sends his old horse away: come back when you are stronger than a lion!' },
{ at: [10, 1, 8], hint: 'Find the fox in the wood.', say: 'The fox has a plan: lie down and pretend to be dead!' },
{ at: [12, 1, 17], hint: 'Find where the lion sleeps.', say: 'The fox ties the lion to the horse\'s tail, and the horse drags him all the way home!' }],
win: 'Stronger than a lion! You earned the Horse Tail, and a Fox\'s Wood kit to build at home.' },
{ id: 'sixservants', abc: 'The Six Servants', title: 'The Six Servants', place: "The Witch-Queen's Palace", keep: 'Magic Ring', color: '#6a4a8a', parts: [711, 9],
tpl: 'palace', props: [[6, 4, 16, 59]],
ach: ['Six Helpers', 'Big, small, cold, far-seeing. All useful.'],
sum: 'The Six Servants. A prince wants to marry the daughter of a wicked old queen who gives impossible tasks. He has six wonderful servants: one can grow huge, one hears everything, one sees everything, one eats a mountain, and one makes everything ice cold. They find a ring at the bottom of the sea, eat three hundred oxen, and freeze a fiery room, and the prince wins the princess.',
quest: 'Your quest: climb to the witch-queen\'s palace, find the icy room, and go to the throne.',
steps: [{ at: [10, 3, 13], hint: 'Climb to the witch-queen\'s palace.', say: 'A prince wants to marry the daughter of a wicked old queen. Six wonderful servants come with him.' },
{ at: [6, 4, 16], hint: 'Find the icy room.', say: 'They are shut in a room with a fire underneath, but one servant makes it so cold that everyone shivers!' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'The servants help with every task, and the prince wins the princess!' }],
win: 'Six servants, one princess! You earned the Magic Ring, and a Witch-Queen\'s Palace kit to build at home.' },
{ id: 'whitebride', abc: 'The White Bride and the Black One', title: 'The White Bride and the Black One', place: 'The White Duck\'s River', keep: 'White Duck Feather', color: '#e0e0e8', parts: [720, 5],
tpl: 'mill', props: [[10, 1, 14, 49]],
ach: ['Kind to Strangers', 'One kind answer, one beautiful blessing.'],
sum: 'The White Bride and the Black One. A poor girl is kind to the good Lord dressed as a beggar, and he makes her beautiful, while her rude stepsister and stepmother are not. Her brother paints her picture, and the king falls in love with it. On the way to the wedding the wicked stepmother pushes her into the river, and she becomes a white duck, until the king breaks the spell.',
quest: 'Your quest: find the painting, find the river, and find the kitchen where the duck swims up.',
steps: [{ at: [10, 1, 14], hint: 'Find the painting.', say: 'Her brother paints her picture, and the king falls in love with it.' },
{ at: [10, 0, 10], hint: 'Find the river.', say: 'The wicked stepmother pushes the bride into the river, and she becomes a snow-white duck.' },
{ id: 21, hint: 'Find the kitchen where the duck swims up.', say: 'The white duck swims up to the kitchen every night. The king sets her free, and she is a beautiful bride again!' }],
win: 'The true bride! You earned the White Duck Feather, and a White Duck\'s River kit to build at home.' },
{ id: 'ironjohn', abc: 'Iron John', title: 'Iron John', place: "Iron John's Golden Well", keep: 'Golden Hair', color: '#8a6a2a', parts: [725, 11],
tpl: 'well', props: [[16, 1, 11, 57]],
ach: ['Golden Knight', 'Red, white, black, and golden hair underneath.'],
sum: 'Iron John. A wild man covered in rusty hair lives at the bottom of a pool. A little prince sets him free, and Iron John takes him to guard a golden well. The boy\'s finger and hair turn to gold, so he hides it under a cap and works as a gardener boy. At a festival a knight in red, then white, then black armour catches the princess\'s golden apples. It is the gardener boy, and Iron John becomes a king again.',
quest: 'Your quest: find the golden well, find the golden apple, and find the gardener boy\'s bed.',
steps: [{ at: [12, 1, 8], hint: 'Find the golden well.', say: 'Iron John lets the boy guard his golden well. The boy dips his finger, and it turns to gold!' },
{ id: 57, hint: 'Find the golden apple.', say: 'A knight in red, then white, then black armour catches the golden apples. Who is he?' },
{ id: 31, hint: 'Find the gardener boy\'s bed.', say: 'The gardener boy with golden hair is the knight! He marries the princess, and Iron John is a king again.' }],
win: 'The golden knight! You earned the Golden Hair, and an Iron John\'s Golden Well kit to build at home.' },
{ id: 'blackprincesses', abc: 'The Three Black Princesses', title: 'The Three Black Princesses', place: 'The Black Princesses\' Castle', keep: 'Candle', color: '#3a3a3a', parts: [736, 3],
tpl: 'castle', wall: 54, props: [[10, 1, 15, 49]],
ach: ['Half Free', 'A very strange old story.'],
sum: 'The Three Black Princesses. Three princesses are under a spell, and a young fisherman is asked to set them free by staying silent for a year. When he goes home to visit, his mother tells him to look at them by the light of a candle. Hot wax drips, the princesses are only half free, and the young man has to run away. It is a very strange old story.',
quest: 'Your quest: find the three black princesses, find the candle light, and find the road home.',
steps: [{ at: [10, 1, 17], hint: 'Find the three black princesses.', say: 'Three princesses are under a spell. A young fisherman tries to set them free.' },
{ at: [10, 1, 15], hint: 'Find the candle light.', say: 'His mother tells him to light a candle and look. Hot wax drips, and the princesses are only half free.' },
{ at: [10, 0, 3], hint: 'Find the road home.', say: 'The young man has to run away, and the spell stays. A very strange old story!' }],
win: 'You earned the Candle, and a Black Princesses\' Castle kit to build at home.' },
{ id: 'knoist', abc: 'Knoist and his Three Sons', title: 'Knoist and his Three Sons', place: 'The Road to Soest', keep: 'Little Hare', color: '#9a8a6a', parts: [739, 1],
tpl: 'forest',
ach: ['Impossible Story', 'Blind, lame and naked. Nonsense!'],
sum: 'Knoist and his Three Sons. Knoist has three sons: one is blind, one is lame, and one has no clothes on. They go out into the field, the blind one shoots a hare, the lame one catches it, and the naked one puts it in his pocket. It is a funny, impossible nonsense story.',
quest: 'Your quest: find the road to Soest, find the field, and find where they catch the hare.',
steps: [{ at: [10, 0, 3], hint: 'Find the road to Soest.', say: 'Knoist has three sons: one is blind, one is lame, and one has no clothes on.' },
{ at: [10, 1, 8], hint: 'Find the field.', say: 'The blind one shoots a hare, the lame one catches it...' },
{ at: [12, 1, 17], hint: 'Find where they catch the hare.', say: '...and the naked one puts it in his pocket! What a funny, impossible story!' }],
win: 'Nonsense! You earned the Little Hare, and a Road to Soest kit to build at home.' },
{ id: 'brakel', abc: 'The Maid of Brakel', title: 'The Maid of Brakel', place: "Saint Anne's Chapel", keep: 'Little Prayer Book', color: '#8aa0c0', parts: [740, 1],
tpl: 'castle', wall: 50, props: [[10, 1, 13, 49]],
ach: ['Hold Your Tongue', 'The answer came from behind the altar.'],
sum: 'The Maid of Brakel. A girl from Brakel goes to Saint Anne\'s little chapel to pray for a husband. The sacristan hides behind the altar and calls out: you shall not have him! The girl thinks it is the little child Jesus speaking, and says: hold your tongue, child, and let your mother speak!',
quest: 'Your quest: find the chapel light, find where the sacristan hides, and find the altar.',
steps: [{ at: [10, 1, 13], hint: 'Find the chapel light.', say: 'A girl from Brakel goes to Saint Anne\'s chapel to pray for a husband.' },
{ at: [7, 1, 9], hint: 'Find where the sacristan hides.', say: 'The sacristan hides behind the altar and calls out: you shall not have him!' },
{ at: [10, 1, 17], hint: 'Find the altar.', say: 'Hold your tongue, child! says the girl. Let your mother speak!' }],
win: 'You earned the Little Prayer Book, and a Saint Anne\'s Chapel kit to build at home.' },
// template places, chunk 14 (ABC Books lessons 741-761, 2026-10-25)
{ id: 'domestic', abc: 'Domestic Servants', title: 'Domestic Servants', place: 'The Road to Walpe', keep: 'Little Rhyme', color: '#a0a080', parts: [741, 1],
tpl: 'cottage',
ach: ['To Walpe!', 'A silly rhyme from long ago.'],
sum: 'Domestic Servants. Where are you going? To Walpe! Two people meet on the road, find they are going the same way, and tell each other the funny names of their husband, child, cradle, servant, kitchen and cow. It is a silly little rhyme from long ago.',
quest: 'Your quest: find the road to Walpe, find the table, and find the bed.',
steps: [{ at: [10, 0, 3], hint: 'Find the road to Walpe.', say: 'Where are you going? To Walpe! Two people meet and go along together.' },
{ id: 19, hint: 'Find the table.', say: 'They tell each other the funny names of their husband, child, cow and house!' },
{ id: 31, hint: 'Find the bed.', say: 'A silly little rhyme from long ago.' }],
win: 'To Walpe! You earned the Little Rhyme, and a Road to Walpe kit to build at home.' },
{ id: 'lambkin', abc: 'The Lambkin and the Little Fish', title: 'The Lambkin and the Little Fish', place: 'The Lambkin\'s Pond', keep: 'Little Fish Scale', color: '#a0c0d0', parts: [742, 2],
tpl: 'mill',
ach: ['Brother and Sister Again', 'A lamb and a fish who talk.'],
sum: 'The Lambkin and the Little Fish. A wicked stepmother turns a little brother into a fish and his sister into a lamb. When the cook is told to cook the lamb, the lamb and the little fish speak to each other so sadly that the cook cannot do it. She takes the lamb to a wise woman, who breaks the spell, and they are brother and sister again.',
quest: 'Your quest: find the pond, find the kitchen, and find the wise woman\'s tree.',
steps: [{ at: [10, 0, 10], hint: 'Find the pond.', say: 'A wicked stepmother turns the brother into a little fish and the sister into a little lamb.' },
{ id: 21, hint: 'Find the kitchen.', say: 'The cook should cook the lamb, but the lamb and the fish talk so sadly that she cannot do it.' },
{ at: [17, 1, 17], hint: 'Find the wise woman\'s tree.', say: 'A wise woman breaks the spell, and they become brother and sister again!' }],
win: 'Together again! You earned the Little Fish Scale, and a Lambkin\'s Pond kit to build at home.' },
{ id: 'simeli', abc: 'Simeli Mountain', title: 'Simeli Mountain', place: 'Simeli Mountain', keep: 'Mountain Gold', color: '#7a7a6a', parts: [744, 3],
tpl: 'castle', wall: 3, props: [[6, 1, 12, 57]],
ach: ['Remember the Word', 'Semsi mountain, open! Do not forget.'],
sum: 'Simeli Mountain. A poor brother sees robbers say: Semsi mountain, Semsi mountain, open! and the bare mountain opens. Inside is treasure, and he takes only a little. His greedy rich brother goes in too and fills his sacks, but forgets the magic word to get out. The robbers find him there.',
quest: 'Your quest: find the road to the mountain, find the treasure inside, and find the door of the mountain.',
steps: [{ at: [10, 0, 3], hint: 'Find the road to the mountain.', say: 'A poor brother sees robbers say: Semsi mountain, Semsi mountain, open! And the mountain opens.' },
{ id: 57, hint: 'Find the treasure inside.', say: 'He takes only a little gold. Later his greedy rich brother goes in and fills his sacks.' },
{ at: [7, 1, 9], hint: 'Find the door of the mountain.', say: 'The greedy brother forgets the word: Simeli mountain, open! But it will not open, and the robbers find him.' }],
win: 'Semsi mountain, open! You earned the Mountain Gold, and a Simeli Mountain kit to build at home.' },
{ id: 'travelling', abc: 'Going A-Travelling', title: 'Going A-Travelling', place: 'The Travelling Road', keep: 'Walking Stick', color: '#8a9a7a', parts: [747, 2],
tpl: 'forest',
ach: ['Wrong Words, Wrong Time', 'He always said the right thing at the wrong moment.'],
sum: 'Going A-Travelling. A poor woman\'s son wants to go travelling. His mother tells him what to say, but every time he says it to the wrong people at the wrong moment, and gets into trouble. Each time he learns a new thing to say, and uses it wrongly again!',
quest: 'Your quest: find the road where he sets off, find the tree by the field, and find where he rests.',
steps: [{ at: [10, 0, 3], hint: 'Find the road where he sets off.', say: 'A poor woman\'s son wants to go travelling. His mother tells him what to say.' },
{ at: [10, 1, 8], hint: 'Find the tree by the field.', say: 'Every time he says the right words to the wrong people, and gets into trouble!' },
{ at: [12, 1, 17], hint: 'Find where he rests.', say: 'Each time he learns something new to say, and uses it at the wrong moment again!' }],
win: 'What a trip! You earned the Walking Stick, and a Travelling Road kit to build at home.' },
{ id: 'donkey', abc: 'The Donkey', title: 'The Donkey', place: 'The Donkey Prince\'s Palace', keep: 'Little Lute', color: '#8a8070', parts: [749, 4],
tpl: 'palace', props: [[6, 4, 16, 5], [14, 4, 16, 75]],
ach: ['Donkey Lute Player', 'A donkey who plays the lute. Why not?'],
sum: 'The Donkey. A king and queen at last have a son, but he is born a little donkey. He learns to play the lute beautifully, travels to another king\'s court, and marries the princess. At night he takes off his donkey skin and is a handsome young man. The old king burns the skin, so he stays a prince for good.',
quest: 'Your quest: find the little donkey\'s lute, go to the throne, and find the donkey skin.',
steps: [{ at: [6, 4, 16], hint: 'Find the little donkey\'s lute.', say: 'A king\'s son is born as a little donkey. He learns to play the lute beautifully!' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'He plays for another king, and marries the princess.' },
{ at: [14, 4, 16], hint: 'Find the donkey skin.', say: 'At night he takes off his donkey skin and is a handsome young man. The old king burns the skin, and he stays a prince!' }],
win: 'A prince for good! You earned the Little Lute, and a Donkey Prince\'s Palace kit to build at home.' },
{ id: 'ungrateful', abc: 'The Ungrateful Son', title: 'The Ungrateful Son', place: 'The Ungrateful Son\'s House', keep: 'Little Toad', color: '#6a7a4a', parts: [753, 1],
tpl: 'cottage', props: [[8, 1, 12, 21]],
ach: ['Always Share', 'Hide the chicken from your father, and look what happens.'],
sum: 'The Ungrateful Son. A man and his wife are about to eat a roast chicken when his old father comes to the door, so the man hides the chicken. When the father has gone, he takes it out again, but it has turned into a big toad, which jumps onto his face and stays there.',
quest: 'Your quest: find the dinner table, find the door where the father comes, and find where the chicken is hidden.',
steps: [{ id: 19, hint: 'Find the dinner table.', say: 'A man and his wife are about to eat a roast chicken.' },
{ at: [10, 0, 3], hint: 'Find the path where the father comes.', say: 'His old father comes to visit, so he hides the chicken.' },
{ id: 21, hint: 'Find where the chicken is hidden.', say: 'When he takes it out, it has turned into a big toad that jumps onto his face and stays there!' }],
win: 'Always share! You earned the Little Toad, and an Ungrateful Son\'s House kit to build at home.' },
{ id: 'turnip', abc: 'The Turnip', title: 'The Turnip', place: 'The Giant Turnip Field', keep: 'Turnip Seed', color: '#c0a0c0', parts: [754, 4],
tpl: 'cottage', props: [[3, 1, 10, 50], [4, 1, 10, 50], [3, 2, 10, 50], [4, 2, 10, 50]],
ach: ['Biggest Turnip', 'It filled a whole cart.'],
sum: 'The Turnip. A poor brother grows a turnip so big that it fills a whole cart, and he gives it to the king, who makes him rich. His jealous rich brother gives the king a fine present too, hoping for more, but gets only the turnip! Angry, he has his brother tied in a sack on a tree, but the poor brother tricks a passing student into taking his place.',
quest: 'Your quest: find the giant turnip, find the road to the king, and find the tree with the sack.',
steps: [{ at: [3, 1, 10], hint: 'Find the giant turnip.', say: 'A poor man grows a turnip so big that it fills a whole cart!' },
{ at: [10, 0, 3], hint: 'Find the road to the king.', say: 'He gives it to the king, who makes him rich. His jealous rich brother wants a reward too.' },
{ at: [17, 1, 17], hint: 'Find the tree with the sack.', say: 'The poor brother is tied in a sack on a tree, but he tricks a student into taking his place!' }],
win: 'What a turnip! You earned the Turnip Seed, and a Giant Turnip Field kit to build at home.' },
{ id: 'oldmanyoung', abc: 'The Old Man Made Young Again', title: 'The Old Man Made Young Again', place: "The Smith's Forge", keep: 'Little Hammer', color: '#8a5a3a', parts: [758, 2],
tpl: 'cottage', wall: 4, props: [[3, 1, 10, 4]],
ach: ['Do Not Try This', 'Only the Lord can do it, not the smith.'],
sum: 'The Old Man Made Young Again. The Lord comes to a smith\'s house and puts a poor old beggar in the forge fire, and he comes out young and healthy. The smith thinks he can do it too, and tries it on his old mother-in-law, but it goes terribly wrong. Only the Lord can do such a thing.',
quest: 'Your quest: find the smith\'s forge, find the anvil, and find the table.',
steps: [{ id: 20, hint: 'Find the smith\'s forge.', say: 'The Lord puts an old beggar in the smith\'s fire, and he comes out young again!' },
{ at: [3, 1, 10], hint: 'Find the anvil.', say: 'The smith tries it on his old mother-in-law, but it goes terribly wrong.' },
{ id: 19, hint: 'Find the table.', say: 'Only the Lord can do such a thing, not the smith!' }],
win: 'You earned the Little Hammer, and a Smith\'s Forge kit to build at home.' },
{ id: 'lordsanimals', abc: "The Lord's Animals and the Devil's", title: "The Lord's Animals and the Devil's", place: 'The Goat Meadow', keep: 'Goat Horn', color: '#7a6a4a', parts: [760, 1],
tpl: 'forest', props: [[15, 1, 17, 84]],
ach: ['Short Tails', 'Now you know why goats have short tails.'],
sum: 'The Lord\'s Animals and the Devil\'s. The Lord makes all the animals, and the wolves to be his dogs. The devil makes goats with long tails, but their tails keep getting caught in the hedges, so he bites them off. And that, says this old story, is why goats have short tails.',
quest: 'Your quest: find the tree in the wood, find the goat, and find the clearing.',
steps: [{ at: [10, 1, 8], hint: 'Find the tree in the wood.', say: 'The Lord makes all the animals, and the wolves to be his dogs.' },
{ at: [15, 1, 17], hint: 'Find the goat.', say: 'The devil makes goats with long tails, but their tails get stuck in the hedges!' },
{ at: [12, 1, 17], hint: 'Find the clearing.', say: 'He bites the tails off, and that is why goats have short tails, says the old story.' }],
win: 'You earned the Goat Horn, and a Goat Meadow kit to build at home.' },
{ id: 'beam', abc: 'The Beam', title: 'The Beam', place: "The Magician's Square", keep: 'Four-leaf Clover', color: '#5a9a5a', parts: [761, 1],
tpl: 'forest', props: [[15, 1, 17, 67]],
ach: ['Clover Eyes', 'With a four-leaf clover, you see the truth.'],
sum: 'The Beam. A magician makes a crowd believe a rooster is carrying a heavy beam. A girl with a four-leaf clover sees it is only a straw, and laughs at them all. Later, when she has lost her clover, the magician makes her think she is walking through a stream, and now everyone laughs at her!',
quest: 'Your quest: find the square where the crowd watches, find the straw, and find the stream.',
steps: [{ at: [10, 0, 3], hint: 'Find the square where the crowd watches.', say: 'A magician makes everyone think a rooster is carrying a heavy beam!' },
{ at: [15, 1, 17], hint: 'Find the straw.', say: 'A girl with a four-leaf clover sees it is only a straw, and laughs.' },
{ at: [12, 1, 17], hint: 'Find the stream.', say: 'Later he makes her think she is in a stream, and she lifts her dress. Now everyone laughs at her!' }],
win: 'You earned the Four-leaf Clover, and a Magician\'s Square kit to build at home.' },
// template places, chunk 15 (ABC Books lessons 762-776, 2026-10-25)
{ id: 'beggarwoman', abc: 'The Old Beggar-Woman', title: 'The Old Beggar-Woman', place: 'The Warm Hearth', keep: 'Bucket of Water', color: '#9a7a6a', parts: [762, 1],
tpl: 'cottage',
ach: ['Always Help', 'Should he not have fetched the water?'],
sum: 'The Old Beggar-Woman. An old beggar woman comes to a house, and a young man lets her warm herself by the fire. Her old rags catch fire, and the young man just stands there and watches. The story asks: should he not have run to fetch water?',
quest: 'Your quest: find the path where she comes, find the fire, and find the table.',
steps: [{ at: [10, 0, 3], hint: 'Find the path where she comes.', say: 'An old beggar woman comes to a house, and a young man lets her warm herself by the fire.' },
{ id: 20, hint: 'Find the fire.', say: 'Her old rags catch fire, and the young man just stands there.' },
{ id: 19, hint: 'Find the table.', say: 'Should he not have run to fetch water? asks the story. Always help!' }],
win: 'You would help! You earned the Bucket of Water, and a Warm Hearth kit to build at home.' },
{ id: 'sluggards', abc: 'The Three Sluggards', title: 'The Three Sluggards', place: 'The Laziest Kingdom', keep: 'Lazy Pillow', color: '#b0a0c0', parts: [763, 1],
tpl: 'cottage',
ach: ['Laziest of All', 'Too lazy to turn his head. King!'],
sum: 'The Three Sluggards. A king says his laziest son shall be king after him. The first is too lazy to close his eyes when he wants to sleep. The second is too lazy to pull his foot out of the fire. The third is too lazy to turn his head even with a rope around his neck. So the third is the laziest, and he becomes king.',
quest: 'Your quest: find the bed, find the fire, and find the table.',
steps: [{ id: 31, hint: 'Find the bed.', say: 'A king says the laziest of his three sons shall be king.' },
{ id: 20, hint: 'Find the fire.', say: 'The first is too lazy to close his eyes, the second too lazy to pull his foot out of the fire.' },
{ id: 19, hint: 'Find the table.', say: 'The third is too lazy to turn his head even with a rope around his neck. He is the laziest, so he is king!' }],
win: 'So lazy! You earned the Lazy Pillow, and a Laziest Kingdom kit to build at home.' },
{ id: 'idleservants', abc: 'The Twelve Idle Servants', title: 'The Twelve Idle Servants', place: 'The Idle Hall', keep: 'Lazy Hat', color: '#a0a0b0', parts: [764, 4],
tpl: 'castle', props: [[6, 1, 12, 67], [13, 1, 13, 31]],
ach: ['Twelve Lazybones', 'Each one lazier than the last.'],
sum: 'The Twelve Idle Servants. Twelve servants who do nothing all day lie in the grass and tell each other how lazy they are. One lets the sun burn him because walking to the shade is too much work, one will not lift a feather, and one will not even open his mouth to eat. Each one is lazier than the last.',
quest: 'Your quest: go to the master\'s throne, find the hay, and find the servants\' bed.',
steps: [{ at: [10, 1, 17], hint: 'Go to the master\'s throne.', say: 'Twelve servants who do nothing all day tell how lazy they are.' },
{ id: 67, hint: 'Find the hay.', say: 'One lies in the hay all day. Another lets the sun burn him, because walking to the shade is too much work!' },
{ id: 31, hint: 'Find the servants\' bed.', say: 'Each one is lazier than the last. A very funny list of lazy servants!' }],
win: 'So idle! You earned the Lazy Hat, and an Idle Hall kit to build at home.' },
{ id: 'shepherdboy', abc: 'The Shepherd Boy', title: 'The Shepherd Boy', place: 'The Diamond Mountain', keep: 'Diamond', color: '#80d0e0', parts: [768, 1],
tpl: 'palace', props: [[6, 4, 16, 53]],
ach: ['Wise Answers', 'How long is eternity? Ask the shepherd boy.'],
sum: 'The Shepherd Boy. A shepherd boy is famous for his wise answers, so the king asks him three questions. How many drops are in the sea? How many stars are in the sky? How many seconds are in eternity? For the last, he says: there is a diamond mountain, and every hundred years a little bird sharpens its beak on it. When the whole mountain is worn away, the first second of eternity is over.',
quest: 'Your quest: climb to the king\'s palace, find the diamond mountain, and go to the throne.',
steps: [{ at: [10, 3, 13], hint: 'Climb to the king\'s palace.', say: 'A shepherd boy is famous for his wise answers, and the king sends for him.' },
{ at: [6, 4, 16], hint: 'Find the diamond mountain.', say: 'How many seconds are in eternity? There is a diamond mountain, and every hundred years a little bird sharpens its beak on it...' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'When the whole mountain is worn away, the first second of eternity is over! The king makes him his own son.' }],
win: 'So wise! You earned the Diamond, and a Diamond Mountain kit to build at home.' },
{ id: 'starmoney', abc: 'The Star-Money', title: 'The Star-Money', place: 'The Star-Money Wood', keep: 'Star Coin', color: '#e0e0a0', parts: [769, 1],
tpl: 'forest', props: [[15, 1, 17, 58]],
ach: ['Giving Heart', 'She gave everything away. The stars gave it back.'],
sum: 'The Star-Money. A poor little orphan girl has nothing but the clothes she wears and a piece of bread. She gives the bread to a hungry man, and her cap, her jacket and her frock to cold children. Alone in the dark wood, she gives away her last little shirt. Then the stars fall from the sky as shining silver coins, and she has a new shirt of the finest linen.',
quest: 'Your quest: find the path where she meets the hungry man, find the tree in the wood, and find the fallen stars.',
steps: [{ at: [10, 0, 3], hint: 'Find the path where she meets the hungry man.', say: 'A poor little orphan girl has only her clothes and a piece of bread. She gives the bread to a hungry man.' },
{ at: [10, 1, 8], hint: 'Find the tree in the wood.', say: 'She gives away her cap, her jacket and her frock to cold children.' },
{ at: [15, 1, 17], hint: 'Find the fallen stars.', say: 'The stars fall from the sky as shining silver coins, and she has a new shirt of the finest linen!' }],
win: 'Stars from the sky! You earned the Star Coin, and a Star-Money Wood kit to build at home.' },
{ id: 'farthings', abc: 'The Stolen Farthings', title: 'The Stolen Farthings', place: 'The Quiet Dining Room', keep: 'Two Farthings', color: '#b0a090', parts: [770, 1],
tpl: 'cottage', props: [[8, 1, 12, 57]],
ach: ['Give It Back', 'Two little farthings, and peace at last.'],
sum: 'The Stolen Farthings. Every day at dinner, a little child in white comes in quietly, walks into the next room and goes again. It is a child of the family who has died. The child had kept back two farthings meant for a poor man, and hid them under a floorboard, so it cannot rest. When the parents give the farthings to a poor man, the child is seen no more.',
quest: 'Your quest: find the dinner table, find the hidden farthings, and find the little bed.',
steps: [{ id: 19, hint: 'Find the dinner table.', say: 'A family sits at dinner, and a little child in white comes in quietly.' },
{ at: [8, 1, 12], hint: 'Find the hidden farthings.', say: 'The child hid two farthings meant for a poor man, and cannot rest.' },
{ id: 31, hint: 'Find the little bed.', say: 'The parents give the farthings to a poor man, and the child can rest in peace.' }],
win: 'You earned the Two Farthings, and a Quiet Dining Room kit to build at home.' },
{ id: 'bridestrial', abc: 'Brides On Their Trial', title: 'Brides On Their Trial', place: 'The Cheese Table', keep: 'Cheese', color: '#e0c060', parts: [771, 1],
tpl: 'cottage', props: [[3, 1, 10, 50]],
ach: ['Just Right', 'Not too much rind, not too little.'],
sum: 'Brides On Their Trial. A young shepherd cannot choose between three pretty sisters, so his mother says: give them cheese, and watch how they cut it. The first eats it rind and all, the second cuts off too much good cheese with the rind, and the third cuts the rind off just right. He marries the third.',
quest: 'Your quest: find the table, find the cheese, and find the bed.',
steps: [{ id: 19, hint: 'Find the table.', say: 'A young shepherd cannot choose, so his mother says: give them cheese, and watch how they cut it.' },
{ at: [3, 1, 10], hint: 'Find the cheese.', say: 'The first eats it rind and all. The second cuts off too much good cheese with the rind.' },
{ id: 31, hint: 'Find the bed.', say: 'The third cuts the rind just right, and he marries her!' }],
win: 'Just right! You earned the Cheese, and a Cheese Table kit to build at home.' },
{ id: 'oddsends', abc: 'Odds And Ends', title: 'Odds And Ends', place: 'The Spinning Room', keep: 'Little Dress', color: '#c0a0b0', parts: [772, 1],
tpl: 'cottage', props: [[8, 1, 12, 68], [4, 1, 13, 21]],
ach: ['Waste Not', 'Odds and ends make a pretty dress.'],
sum: 'Odds And Ends. A lazy girl throws away all the knotty bits of flax when she spins. Her hard-working maid saves the odds and ends, spins them, and makes herself a pretty dress. At the wedding, the bridegroom hears the bride laughing that the maid dances in her leftovers, so he marries the hard-working maid instead.',
quest: 'Your quest: find the spinning wheel, find the clothes chest, and find the table.',
steps: [{ id: 68, hint: 'Find the spinning wheel.', say: 'A lazy girl throws away all the knotty bits of flax when she spins.' },
{ id: 21, hint: 'Find the clothes chest.', say: 'Her maid saves the bits and spins them into a pretty dress.' },
{ id: 19, hint: 'Find the table.', say: 'At the wedding, the bridegroom hears the truth, and marries the hard-working maid instead!' }],
win: 'Waste not! You earned the Little Dress, and a Spinning Room kit to build at home.' },
{ id: 'sparrowfour', abc: 'The Sparrow And His Four Children', title: 'The Sparrow And His Four Children', place: 'The Swallow\'s Nest', keep: 'Little Feather', color: '#9a8060', parts: [773, 3],
tpl: 'forest',
ach: ['Learned a Lot', 'Watch out for cats, hawks and boys with slings.'],
sum: 'The Sparrow And His Four Children. A sparrow has four children in a swallow\'s nest, and a storm scatters them before they can fly well. When they come home, Father Sparrow asks each one what he has learned out in the world. They have learned to watch out for cats, hawks and boys with slings, and to trust in the good Lord.',
quest: 'Your quest: find the nest, find the path home, and find the clearing.',
steps: [{ at: [3, 1, 15], hint: 'Find the nest.', say: 'A sparrow has four children in a swallow\'s nest. A storm scatters them.' },
{ at: [10, 0, 3], hint: 'Find the path home.', say: 'They come back home, and Father Sparrow asks each one what he has learned.' },
{ at: [12, 1, 17], hint: 'Find the clearing.', say: 'They learned to watch out for cats, hawks and boys with slings, and to trust in the good Lord.' }],
win: 'Well learned! You earned the Little Feather, and a Swallow\'s Nest kit to build at home.' },
{ id: 'schlauraffen', abc: 'The Story of Schlauraffen Land', title: 'The Story of Schlauraffen Land', place: 'Schlauraffen Land', keep: 'Pancake Stone', color: '#e0a060', parts: [776, 1],
tpl: 'palace', props: [[6, 4, 16, 69]],
ach: ['Nonsense Land', 'A millstone floating over the Rhine. Of course.'],
sum: 'The Story of Schlauraffen Land. In the land of Schlauraffen I saw the strangest things: a millstone floating over the river, roasted birds flying, and a pancake mountain. It is all nonsense from beginning to end, and the story laughs at itself.',
quest: 'Your quest: find the road into the land, find the pancake mountain, and go to the throne.',
steps: [{ at: [10, 0, 3], hint: 'Find the road into the land.', say: 'In Schlauraffen land, I saw a millstone floating over the river!' },
{ at: [6, 4, 16], hint: 'Find the pancake mountain.', say: 'I saw roasted birds flying, and a mountain made of pancakes!' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'It is all nonsense, and the story laughs at itself!' }],
win: 'Nonsense! You earned the Pancake Stone, and a Schlauraffen Land kit to build at home.' },
// template places, chunk 16 (ABC Books lessons 777-820, 2026-10-25)
{ id: 'ditmarsch', abc: 'The Ditmarsch Tale of Wonders', title: 'The Ditmarsch Tale of Wonders', place: 'The Wonder Road', keep: 'Little Anvil', color: '#a0b0c0', parts: [777, 1],
tpl: 'forest',
ach: ['Tall Tale', 'An anvil swimming across the river? Sure.'],
sum: 'The Ditmarsch Tale of Wonders. I saw two roasted fowls flying, an anvil and a millstone swimming across the Rhine, and a frog sitting on the ice eating a ploughshare. The whole story is made of impossible things, and at the end it says: open the window, so the lies can fly out!',
quest: 'Your quest: find the road of wonders, find the old tree, and find the clearing.',
steps: [{ at: [10, 0, 3], hint: 'Find the road of wonders.', say: 'I saw two roasted fowls flying, fast and straight!' },
{ at: [10, 1, 8], hint: 'Find the old tree.', say: 'An anvil and a millstone swam across the Rhine, and a frog sat on the ice eating a ploughshare.' },
{ at: [12, 1, 17], hint: 'Find the clearing.', say: 'Open the window, so the lies can fly out!' }],
win: 'What wonders! You earned the Little Anvil, and a Wonder Road kit to build at home.' },
{ id: 'riddlingtale', abc: 'A Riddling Tale', title: 'A Riddling Tale', place: 'The Flower Field', keep: 'Dewless Flower', color: '#d070a0', parts: [778, 1],
tpl: 'cottage', props: [[3, 1, 9, 36], [4, 1, 9, 36], [2, 1, 9, 36]],
ach: ['No Dew', 'He picked the right flower.'],
sum: 'A Riddling Tale. Three women are turned into flowers in a field, but one of them may go home to her own house at night. She tells her husband: come and pick me in the morning, and I will be free. In the morning he picks the one flower with no dew on it, because she was at home all night, and she is free.',
quest: 'Your quest: find the bed where she sleeps at night, find the path to the field, and find the flower without dew.',
steps: [{ id: 31, hint: 'Find the bed where she sleeps at night.', say: 'Three women are turned into flowers, but one may go home at night.' },
{ at: [10, 0, 3], hint: 'Find the path to the field.', say: 'She tells her husband: come and pick me in the morning, and I will be free.' },
{ at: [4, 1, 9], hint: 'Find the flower without dew.', say: 'He picks the flower with no dew on it, because she was at home all night. Clever husband!' }],
win: 'Riddle solved! You earned the Dewless Flower, and a Flower Field kit to build at home.' },
{ id: 'snowrose', abc: 'Snow-White and Rose-Red', title: 'Snow-White and Rose-Red', place: "Snow-White and Rose-Red's Cottage", keep: 'Rose', color: '#e04060', parts: [779, 9],
tpl: 'cottage', props: [[3, 1, 9, 73], [4, 1, 9, 73]],
ach: ['Friend of Bears', 'A bear by the fire, a grumpy dwarf, two kind sisters.'],
sum: 'Snow-White and Rose-Red. Two kind sisters are named after the white and red rose-trees in front of their mother\'s cottage. All winter a friendly bear warms himself by their fire. In summer they help a grumpy dwarf three times, even though he is rude to them. The bear defeats the wicked dwarf, turns into a king\'s son, and the sisters marry him and his brother.',
quest: 'Your quest: find the two rose-trees, find the fire where the bear sleeps, and find the tree where the dwarf\'s beard is stuck.',
steps: [{ at: [3, 1, 9], hint: 'Find the two rose-trees.', say: 'Snow-White and Rose-Red are named after the two rose-trees in front of their cottage.' },
{ id: 20, hint: 'Find the fire where the bear sleeps.', say: 'All winter a friendly bear warms himself by their fire, and they play with him.' },
{ at: [17, 1, 17], hint: 'Find the tree where the dwarf\'s beard is stuck.', say: 'They help a grumpy dwarf three times. The bear is really a prince, and the sisters marry him and his brother!' }],
win: 'Happy sisters! You earned the Rose, and a Snow-White and Rose-Red\'s Cottage kit to build at home.' },
{ id: 'wiseservant', abc: 'The Wise Servant', title: 'The Wise Servant', place: 'The Blackbird Field', keep: 'Blackbird Feather', color: '#3a3a3a', parts: [788, 1],
tpl: 'cottage',
ach: ['Not So Wise', 'He went for a cow and came back with a story.'],
sum: 'The Wise Servant. A master sends his servant to look for a lost cow. The servant sees three blackbirds instead, chases them all day, and comes home happily with nothing. How lucky is the master, says the story, to have such a wise servant!',
quest: 'Your quest: find the master\'s table, find the field, and find the tree with the blackbirds.',
steps: [{ id: 19, hint: 'Find the master\'s table.', say: 'A master sends his servant out to find a lost cow.' },
{ at: [10, 0, 3], hint: 'Find the field.', say: 'The servant sees three blackbirds and chases them instead!' },
{ at: [17, 1, 4], hint: 'Find the tree with the blackbirds.', say: 'He comes home with nothing, very pleased with himself. What a wise servant!' }],
win: 'You earned the Blackbird Feather, and a Blackbird Field kit to build at home.' },
{ id: 'glasscoffin', abc: 'The Glass Coffin', title: 'The Glass Coffin', place: 'The Glass Coffin Castle', keep: 'Glass Key', color: '#90c0e0', parts: [789, 8],
tpl: 'castle', wall: 11, props: [[6, 1, 12, 11], [6, 2, 12, 11]],
ach: ['Brave Little Tailor', 'He opened the glass coffin.'],
sum: 'The Glass Coffin. A little tailor lost in the forest watches a fight between a stag and a wild bull. The stag carries him to a rock that opens, and deep underground he finds a glass coffin with a beautiful girl asleep inside, and a whole castle shrunk inside a glass box. He opens the coffin, the girl wakes, the spell on her brother and castle is broken, and she marries the tailor.',
quest: 'Your quest: find the tree in the forest, find the glass coffin, and go to the throne.',
steps: [{ at: [2, 1, 3], hint: 'Find the tree in the forest.', say: 'A little tailor lost in the forest watches a fight between a stag and a wild bull.' },
{ at: [6, 1, 12], hint: 'Find the glass coffin.', say: 'Deep under the ground he finds a glass coffin, with a beautiful sleeping girl inside.' },
{ at: [10, 1, 17], hint: 'Go to the throne.', say: 'He opens the coffin, she wakes, her brother and castle come back, and she marries the tailor!' }],
win: 'Spell broken! You earned the Glass Key, and a Glass Coffin Castle kit to build at home.' },
{ id: 'lazyharry', abc: 'Lazy Harry', title: 'Lazy Harry', place: "Lazy Harry's Meadow", keep: 'Goat Bell', color: '#b0b070', parts: [797, 4],
tpl: 'cottage', props: [[3, 1, 10, 84]],
ach: ['Too Much Work', 'Even a goat is too much work for Harry.'],
sum: 'Lazy Harry. Lazy Harry has to take his goat to the meadow every day, and he thinks it is far too much work. So he marries fat Trina, who also has a goat, and they swap both goats for a beehive, which needs no looking after. Then they lie in bed dreaming of how to be even lazier.',
quest: 'Your quest: find Harry\'s goat, find the table, and find the bed.',
steps: [{ at: [3, 1, 10], hint: 'Find Harry\'s goat.', say: 'Lazy Harry has to take his goat to the meadow every day. Too much work!' },
{ id: 19, hint: 'Find the table.', say: 'He marries fat Trina, who has a goat too. They swap the goats for a beehive!' },
{ id: 31, hint: 'Find the bed.', say: 'Then they lie in bed and dream of even easier things.' }],
win: 'So lazy! You earned the Goat Bell, and a Lazy Harry\'s Meadow kit to build at home.' },
{ id: 'griffin', abc: 'The Griffin', title: 'The Griffin', place: "The Griffin's Nest", keep: 'Griffin Feather', color: '#a08030', parts: [801, 9],
tpl: 'well', props: [[14, 1, 6, 5]],
ach: ['Griffin Feather', 'A boat on dry land, a hundred hares, and a griffin\'s feather.'],
sum: 'The Griffin. A king\'s daughter is ill, and only apples can cure her. Kind Hans brings the best apples, but the king gives him more tasks: a boat that sails on land and water, a hundred hares to keep together, and a feather from the griffin\'s tail. A little grey man helps him, and the griffin\'s kind wife hides him and gets the answers he needs.',
quest: 'Your quest: find the apple tree, find the boat that sails on land, and find the griffin\'s fire.',
steps: [{ at: [4, 1, 5], hint: 'Find the apple tree.', say: 'Hans brings the sick princess the best apples, and she gets well.' },
{ at: [14, 1, 6], hint: 'Find the boat that sails on land.', say: 'With help from a little grey man, he makes a boat that sails on land and on water.' },
{ id: 20, hint: 'Find the griffin\'s fire.', say: 'The griffin\'s wife hides him and gets the answers. He brings back a griffin feather and marries the princess!' }],
win: 'A griffin feather! You earned the Griffin Feather, and a Griffin\'s Nest kit to build at home.' },
{ id: 'stronghans', abc: 'Strong Hans', title: 'Strong Hans', place: "Strong Hans's Well", keep: 'Iron Staff', color: '#6a5a4a', parts: [810, 8],
tpl: 'well', props: [[14, 1, 6, 13]],
ach: ['Strong as Hans', 'Robbers, a dwarf and a deep well. No problem.'],
sum: 'Strong Hans. Little Hans and his mother are prisoners in a robbers\' cave. Hans grows so strong that he beats the robbers and takes his mother home. Then he sets out with a huge iron staff, makes two strong friends, and climbs down a deep well, where he beats a wicked dwarf and saves a princess, and in the end he marries her.',
quest: 'Your quest: find the robbers\' fire, find the iron staff, and find the deep well.',
steps: [{ id: 20, hint: 'Find the robbers\' fire.', say: 'Hans and his mother are prisoners in a robbers\' cave. Hans grows so strong that he beats them all!' },
{ at: [14, 1, 6], hint: 'Find the iron staff.', say: 'He gets a huge iron staff and sets out into the world.' },
{ at: [12, 1, 8], hint: 'Find the deep well.', say: 'He climbs down a well, saves a princess from a wicked dwarf, and marries her!' }],
win: 'So strong! You earned the Iron Staff, and a Strong Hans\'s Well kit to build at home.' },
{ id: 'peasantheaven', abc: 'The Peasant in Heaven', title: 'The Peasant in Heaven', place: 'The Heavenly Gate', keep: 'Little Halo', color: '#f0e0c0', parts: [818, 1],
tpl: 'palace', wall: 51, props: [[6, 4, 16, 49]],
ach: ['Everyone Is Welcome', 'Rich men come so rarely.'],
sum: 'The Peasant in Heaven. A poor peasant and a rich man arrive at heaven\'s gate together. The rich man is welcomed with music and singing, while the peasant is let in quietly. The peasant wonders why, and Saint Peter explains: poor peasants come every day, but a rich man comes only once in a hundred years!',
quest: 'Your quest: climb to heaven\'s gate, find the music, and go to the throne.',
steps: [{ at: [10, 3, 13], hint: 'Climb to heaven\'s gate.', say: 'A poor peasant and a rich man arrive at heaven\'s gate together.' },
{ at: [6, 4, 16], hint: 'Find the music.', say: 'The rich man is welcomed with music and singing!' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'Poor peasants come every day, says Saint Peter, but a rich man only once in a hundred years!' }],
win: 'You earned the Little Halo, and a Heavenly Gate kit to build at home.' },
{ id: 'leanlisa', abc: 'Lean Lisa', title: 'Lean Lisa', place: "Lean Lisa's House", keep: 'Dream Cow', color: '#a09080', parts: [819, 2],
tpl: 'cottage',
ach: ['Dream Big', 'A cow, a calf, a farm... and a pinch.'],
sum: 'Lean Lisa. Lean Lisa works hard all day, while her husband, Tall Lenz, does very little. One day she dreams out loud of all they could have: if they found a coin they could buy a cow, and then a calf. She gets so carried away that she gives her husband a slap for what he might do with the calf! But it is all only a dream.',
quest: 'Your quest: find Lisa\'s bed, find the table, and find the path to the market.',
steps: [{ id: 31, hint: 'Find Lisa\'s bed.', say: 'Lean Lisa works hard all day, and her husband Tall Lenz does very little.' },
{ id: 19, hint: 'Find the table.', say: 'If only we had a coin! Then we could buy a cow, and then a calf!' },
{ at: [10, 0, 3], hint: 'Find the path to the market.', say: 'She gets so carried away that she slaps her husband. But the cow is only a dream!' }],
win: 'What a dream! You earned the Dream Cow, and a Lean Lisa\'s House kit to build at home.' },
// template places, chunk 17 (ABC Books lessons 821-849, 2026-10-25)
{ id: 'hutforest', abc: 'The Hut in the Forest', title: 'The Hut in the Forest', place: 'The Hut in the Forest', keep: 'Brindled Cow Bell', color: '#7a6a3a', parts: [821, 7],
tpl: 'cottage', wall: 6, props: [[3, 1, 10, 67]],
ach: ['Animals First', 'Feed the hen, the cock and the cow before yourself.'],
sum: 'The Hut in the Forest. A woodcutter\'s three daughters each get lost bringing his dinner, and come to a hut where an old man lives with a hen, a cock and a brindled cow. The two eldest eat without a thought for the animals. The youngest feeds them first. In the night the hut turns into a palace, and the old man and the animals turn into a king\'s son and his servants.',
quest: 'Your quest: find the path into the forest, find the animals\' straw, and find the bed.',
steps: [{ at: [10, 0, 3], hint: 'Find the path into the forest.', say: 'Three sisters take their father\'s dinner into the forest, but each one loses her way.' },
{ id: 67, hint: 'Find the animals\' straw.', say: 'The youngest sister feeds the hen, the cock and the brindled cow before she eats.' },
{ id: 31, hint: 'Find the bed.', say: 'In the night the hut becomes a palace, and the old man and the animals become a king\'s son and his servants!' }],
win: 'Kindness wins! You earned the Brindled Cow Bell, and a Hut in the Forest kit to build at home.' },
{ id: 'sharingjoy', abc: 'Sharing Joy and Sorrow', title: 'Sharing Joy and Sorrow', place: "The Quarrelsome Tailor's House", keep: 'Judge\'s Note', color: '#8a7a8a', parts: [828, 1],
tpl: 'cottage',
ach: ['Share the Good Things', 'Joy and sorrow, not blows.'],
sum: 'Sharing Joy and Sorrow. A quarrelsome tailor is always unkind to his good wife. The judge orders him to live in peace and share joy and sorrow with her. So the tailor says he will share the blows with her too! The judge sends him to prison for it.',
quest: 'Your quest: find the tailor\'s table, find the road to the judge, and find the bed.',
steps: [{ id: 19, hint: 'Find the tailor\'s table.', say: 'A quarrelsome tailor is always unkind to his good wife.' },
{ at: [10, 0, 3], hint: 'Find the road to the judge.', say: 'The judge tells him to share joy and sorrow with her.' },
{ id: 31, hint: 'Find the bed.', say: 'He says he will share the blows too! So the judge sends him to prison.' }],
win: 'Share the good things! You earned the Judge\'s Note, and a Quarrelsome Tailor\'s House kit to build at home.' },
{ id: 'willowwren', abc: 'The Willow-Wren', title: 'The Willow-Wren', place: 'The Birds\' Meadow', keep: 'Tiny Crown', color: '#8aa060', parts: [829, 5],
tpl: 'forest',
ach: ['King of the Birds', 'Hide in the eagle\'s feathers. Clever!'],
sum: 'The Willow-Wren. The birds decide that whoever flies highest shall be their king. The eagle flies higher than anyone, but the little wren has hidden in his feathers, and flies out on top: I am king! The birds say it was a trick, and the wren hides in a mouse-hole while the owl keeps watch.',
quest: 'Your quest: find the tree where the birds meet, find where the wren flies out, and find the mouse-hole path.',
steps: [{ at: [10, 1, 14], hint: 'Find the tree where the birds meet.', say: 'The birds decide: whoever flies highest shall be king.' },
{ at: [12, 1, 17], hint: 'Find where the wren flies out.', say: 'The little wren hides in the eagle\'s feathers, and flies out on top. I am king!' },
{ at: [6, 0, 6], hint: 'Find the mouse-hole path.', say: 'The birds say it was a trick, and the owl must watch the mouse-hole where the wren hides.' }],
win: 'Little king! You earned the Tiny Crown, and a Birds\' Meadow kit to build at home.' },
{ id: 'sole', abc: 'The Sole', title: 'The Sole', place: 'The Fishes\' Race', keep: 'Fish Scale', color: '#7a90a0', parts: [834, 1],
tpl: 'mill', props: [[10, 1, 14, 8]],
ach: ['Crooked Mouth', 'Never be jealous of the herring.'],
sum: 'The Sole. The fish want a king, so they decide whoever swims fastest shall be king. The herring wins the race. The herring? cries the sole crossly, and its mouth twists to one side, and it has stayed that way ever since.',
quest: 'Your quest: find the water, find the finish of the race, and find the sandy bottom.',
steps: [{ at: [10, 0, 10], hint: 'Find the water.', say: 'The fish want a king, so they decide on a swimming race.' },
{ at: [17, 1, 17], hint: 'Find the finish of the race.', say: 'The herring wins the race!' },
{ at: [10, 1, 14], hint: 'Find the sandy bottom.', say: 'The herring? cries the sole crossly, and its mouth twists to one side. It is still twisted today.' }],
win: 'You earned the Fish Scale, and a Fishes\' Race kit to build at home.' },
{ id: 'bittern', abc: 'The Bittern and the Hoopoe', title: 'The Bittern and the Hoopoe', place: 'The Cowherd\'s Meadow', keep: 'Hoopoe Feather', color: '#9a7a5a', parts: [835, 1],
tpl: 'forest',
ach: ['Up, Up, Up', 'Bunt, bunt! say the birds.'],
sum: 'The Bittern and the Hoopoe. Two cowherds look after cows in very different ways: one lets them eat in the rich meadow, the other drives them up the bare hill. When they die, they turn into birds. One cries bunt, bunt, still calling his cows, and the other calls up, up, up!',
quest: 'Your quest: find the rich meadow, find the bare hill, and find the clearing.',
steps: [{ at: [10, 0, 3], hint: 'Find the rich meadow.', say: 'One cowherd lets his cows eat in the rich meadow.' },
{ at: [10, 1, 8], hint: 'Find the bare hill.', say: 'The other drives his cows up the bare hill.' },
{ at: [12, 1, 17], hint: 'Find the clearing.', say: 'They turn into birds. One calls bunt, bunt, and the other calls up, up, up!' }],
win: 'Bunt! You earned the Hoopoe Feather, and a Cowherd\'s Meadow kit to build at home.' },
{ id: 'owl', abc: 'The Owl', title: 'The Owl', place: 'The Owl\'s Barn', keep: 'Owl Feather', color: '#8a7a6a', parts: [836, 3],
tpl: 'cottage', props: [[3, 1, 10, 67]],
ach: ['Only an Owl', 'A whole town, scared of one owl.'],
sum: 'The Owl. A big owl hides in a barn in a little town, and nobody there has ever seen an owl before. They think it is a terrible monster! The bravest man tries to catch it and runs away scared, and in the end they burn down the whole barn just to get rid of one owl.',
quest: 'Your quest: find the hay in the barn, find the street where the people gather, and find the fire.',
steps: [{ id: 67, hint: 'Find the hay in the barn.', say: 'A big owl hides in a barn, and the townspeople have never seen one before!' },
{ at: [10, 0, 3], hint: 'Find the street where the people gather.', say: 'They are so scared that they bring out spears and ladders!' },
{ id: 20, hint: 'Find the fire.', say: 'In the end they burn down the whole barn, just to get rid of one owl.' }],
win: 'Only an owl! You earned the Owl Feather, and an Owl\'s Barn kit to build at home.' },
{ id: 'moon', abc: 'The Moon', title: 'The Moon', place: 'The Moon Oak', keep: 'Moon Piece', color: '#d0d0e0', parts: [839, 3],
tpl: 'forest', props: [[15, 1, 17, 49]],
ach: ['Moon Catcher', 'Hang the moon on an oak tree.'],
sum: 'The Moon. Long ago there was a land with no moon at night. Four young men travelling see a shining ball hanging in an oak tree in another land, buy it, and take it home. When they die, each takes a piece of it into the grave, and it wakes up the dead! Saint Peter comes and takes the moon away and hangs it up in the sky.',
quest: 'Your quest: find the oak tree, find the shining moon, and find the clearing.',
steps: [{ at: [10, 1, 14], hint: 'Find the oak tree.', say: 'In a land with no moon, four young men see a shining ball in an oak tree.' },
{ at: [15, 1, 17], hint: 'Find the shining moon.', say: 'They take it home and hang it up. Now their land has a moon!' },
{ at: [12, 1, 17], hint: 'Find the clearing.', say: 'Saint Peter takes the moon away and hangs it up in the sky, where it shines for everyone.' }],
win: 'You earned the Moon Piece, and a Moon Oak kit to build at home.' },
{ id: 'duration', abc: 'The Duration of Life', title: 'The Duration of Life', place: 'The Thirty Years Meadow', keep: 'Hourglass', color: '#a0907a', parts: [842, 2],
tpl: 'cottage', props: [[3, 1, 10, 67]],
ach: ['Seventy Years', 'Thirty for man, the rest from the donkey, dog and monkey.'],
sum: 'The Duration of Life. When God makes the world, he gives every creature thirty years. The donkey, the dog and the monkey say thirty years is too long, but man says it is too short, so man gets some of their years too. That, says the story, is why man has seventy years.',
quest: 'Your quest: find the path, find the donkey\'s hay, and find the bed.',
steps: [{ at: [10, 0, 3], hint: 'Find the path.', say: 'God gives every creature thirty years.' },
{ id: 67, hint: 'Find the donkey\'s hay.', say: 'The donkey, the dog and the monkey say thirty years is too long.' },
{ id: 31, hint: 'Find the bed.', say: 'Man says thirty is too short, so he gets some of their years too, and lives to seventy.' }],
win: 'You earned the Hourglass, and a Thirty Years Meadow kit to build at home.' },
{ id: 'deathmessengers', abc: "Death's Messengers", title: "Death's Messengers", place: "The Giant's Road", keep: 'Messenger\'s Bell', color: '#5a5a5a', parts: [844, 2],
tpl: 'forest',
ach: ['Kind Helper', 'He helped even Death up from the road.'],
sum: 'Death\'s Messengers. A giant knocks Death down on the road, and a kind young man helps him up. To thank him, Death promises not to come for him without sending messengers first. Years later Death comes, and the man says he never got a message. Death says: I sent illness, dizziness, toothache and every night, sleep, my brother.',
quest: 'Your quest: find the road, find the tree where the young man rests, and find the clearing.',
steps: [{ at: [10, 0, 3], hint: 'Find the road.', say: 'A giant knocks Death down on the road, and a kind young man helps him up.' },
{ at: [10, 1, 8], hint: 'Find the tree where the young man rests.', say: 'Death promises: I will send messengers before I come for you.' },
{ at: [12, 1, 17], hint: 'Find the clearing.', say: 'Years later, Death says: I sent illness, dizziness, toothache, and every night, sleep, my brother.' }],
win: 'You earned the Messenger\'s Bell, and a Giant\'s Road kit to build at home.' },
{ id: 'pfriem', abc: 'Master Pfriem (Master Cobbler\'s Awl)', title: 'Master Pfriem', place: 'The Grumbling Gate', keep: 'Cobbler\'s Awl', color: '#9a8070', parts: [846, 4],
tpl: 'palace', wall: 51, props: [[6, 4, 16, 5]],
ach: ['Stop Grumbling', 'Even in heaven, he found something to complain about.'],
sum: 'Master Pfriem. Master Pfriem the cobbler finds fault with everything and everyone. He dreams that he goes to heaven, and even there he grumbles: the angels carry a beam the wrong way, and people fill a leaky barrel with water. When he grumbles one time too many, he is sent out, and wakes up at home.',
quest: 'Your quest: climb to heaven\'s gate, find the wooden beam, and go to the throne.',
steps: [{ at: [10, 3, 13], hint: 'Climb to heaven\'s gate.', say: 'Master Pfriem the cobbler finds fault with everything and everyone.' },
{ at: [6, 4, 16], hint: 'Find the wooden beam.', say: 'Even in heaven he grumbles: they are carrying that beam the wrong way!' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'He grumbles one time too many, is sent away, and wakes up at home. It was a dream!' }],
win: 'No more grumbling! You earned the Cobbler\'s Awl, and a Grumbling Gate kit to build at home.' },
// template places, chunk 18 (ABC Books lessons 850-902, 2026-10-25)
{ id: 'goosegirlwell', abc: 'The Goose-Girl at the Well', title: 'The Goose-Girl at the Well', place: 'The Moonlit Well', keep: 'Tear Pearl', color: '#c0c0e0', parts: [850, 12],
tpl: 'well', props: [[14, 1, 6, 56]],
ach: ['Pearls of Tears', 'Some tears turn into pearls.'],
sum: 'The Goose-Girl at the Well. A wise old woman lives in the wild with her geese and an ugly goose-girl. A young count helps the old woman and gets a little box with an emerald pearl. At night by the well, the goose-girl takes off her ugly skin, and she is a beautiful princess whose tears turn into pearls. Her father the king sent her away long ago, and now she comes home and marries the count.',
quest: 'Your quest: find the well in the moonlight, find the pearls, and find the wise old woman\'s fire.',
steps: [{ at: [12, 1, 8], hint: 'Find the well in the moonlight.', say: 'At night by the well, the ugly goose-girl takes off her skin, and she is a beautiful princess!' },
{ at: [14, 1, 6], hint: 'Find the pearls.', say: 'Her tears turn into pearls. Her father the king sent her away long ago.' },
{ id: 20, hint: 'Find the wise old woman\'s fire.', say: 'The wise old woman helps her go home, and she marries the young count.' }],
win: 'A princess again! You earned the Tear Pearl, and a Moonlit Well kit to build at home.' },
{ id: 'evechildren', abc: "Eve's Various Children", title: "Eve's Various Children", place: "Adam and Eve's House", keep: 'Blessing', color: '#b0a080', parts: [862, 3],
tpl: 'cottage', props: [[8, 1, 12, 21]],
ach: ['Everyone Is Needed', 'Kings and farmers, tailors and shoemakers.'],
sum: 'Eve\'s Various Children. When God comes to visit Adam and Eve, Eve shows him her handsome, clean children and hides the others in the hay and under the stove. God blesses the handsome ones to be kings and lords. Then the others come out, and he blesses them to be farmers, tailors and shoemakers, because those are needed too.',
quest: 'Your quest: find the table, find where the other children hide, and find the warm stove.',
steps: [{ id: 19, hint: 'Find the table.', say: 'God comes to visit, and Eve shows him her handsome, clean children.' },
{ id: 21, hint: 'Find where the other children hide.', say: 'She hides the others in the hay and under the stove.' },
{ id: 20, hint: 'Find the warm stove.', say: 'God blesses them all: some to be kings and lords, and the others to be farmers, tailors and shoemakers, who are needed too.' }],
win: 'Everyone is needed! You earned the Blessing, and an Adam and Eve\'s House kit to build at home.' },
{ id: 'nixpond', abc: 'The Nix of the Mill-Pond', title: 'The Nix of the Mill-Pond', place: 'The Mill-Pond', keep: 'Golden Comb', color: '#4a8a9a', parts: [865, 7],
tpl: 'mill', props: [[11, 1, 14, 57], [7, 1, 14, 68]],
ach: ['Golden Comb, Flute and Wheel', 'Three golden things bring him back.'],
sum: 'The Nix of the Mill-Pond. A poor miller meets a water-nix in his mill-pond, who makes him rich, if he gives her what has just been born in his house: his own little son. Years later the nix pulls the son into the pond. His wife combs her hair with a golden comb, plays a golden flute and spins with a golden wheel by the pond, and gets him back. They are parted again, and at last find each other as shepherds.',
quest: 'Your quest: find the bridge over the mill-pond, find the golden comb, and find the golden spinning wheel.',
steps: [{ at: [10, 0, 10], hint: 'Find the bridge over the mill-pond.', say: 'A poor miller meets a water-nix, who makes him rich, if he gives her what was just born in his house.' },
{ id: 57, hint: 'Find the golden comb.', say: 'When the nix takes his son, his wife combs her hair with a golden comb by the pond, and plays a golden flute.' },
{ id: 68, hint: 'Find the golden spinning wheel.', say: 'With a golden spinning wheel she gets him back. Years later they find each other again as shepherds.' }],
win: 'Together again! You earned the Golden Comb, and a Mill-Pond kit to build at home.' },
{ id: 'littlefolks', abc: "The Little Folks' Presents", title: "The Little Folks' Presents", place: 'The Moonlight Dance', keep: 'Lump of Coal', color: '#7a7a9a', parts: [872, 3],
tpl: 'forest', props: [[15, 1, 17, 12]],
ach: ['Not Greedy', 'Coal turns to gold, unless you want too much.'],
sum: 'The Little Folks\' Presents. A tailor and a goldsmith see little folk dancing in the moonlight. The little old man shaves their hair and beards, and gives them coal. In the morning the coal has turned to gold! The greedy goldsmith goes back for more, but this time the coal stays coal, his gold from before turns back to coal too, and he gets a second hump.',
quest: 'Your quest: find the path in the moonlight, find where the little folk dance, and find the coal.',
steps: [{ at: [10, 0, 3], hint: 'Find the path in the moonlight.', say: 'A tailor and a goldsmith see little folk dancing in the moonlight.' },
{ at: [12, 1, 17], hint: 'Find where the little folk dance.', say: 'The little old man shaves their hair, and gives them coal. In the morning, it is gold!' },
{ at: [15, 1, 17], hint: 'Find the coal.', say: 'The greedy goldsmith goes back for more, but it stays coal, and he gets a second hump!' }],
win: 'Do not be greedy! You earned the Lump of Coal, and a Moonlight Dance kit to build at home.' },
{ id: 'gianttailor', abc: 'The Giant and the Tailor', title: 'The Giant and the Tailor', place: "The Giant's Willow", keep: 'Willow Twig', color: '#7a8a5a', parts: [875, 3],
tpl: 'forest',
ach: ['Flung Away', 'Hold on to a willow tree. Then let go.'],
sum: 'The Giant and the Tailor. A boastful little tailor goes to work for a giant. He tries to trick the giant again and again. At last the giant bends a willow tree down and asks the tailor to hold it. The tailor holds on, the tree springs back up, and he is flung far away, so that is the end of the boastful tailor\'s working days.',
quest: 'Your quest: find the road to the giant\'s house, find the willow tree, and find where the tailor lands.',
steps: [{ at: [10, 0, 3], hint: 'Find the road to the giant\'s house.', say: 'A boastful little tailor goes to work for a giant.' },
{ at: [10, 1, 14], hint: 'Find the willow tree.', say: 'The giant bends a willow tree down. Hold it! he says.' },
{ at: [12, 1, 17], hint: 'Find where the tailor lands.', say: 'The tree springs back up, and the tailor is flung far, far away!' }],
win: 'Whoosh! You earned the Willow Twig, and a Giant\'s Willow kit to build at home.' },
{ id: 'nail', abc: 'The Nail', title: 'The Nail', place: 'The Merchant\'s Road', keep: 'Horseshoe Nail', color: '#7a7a7a', parts: [878, 1],
tpl: 'forest', props: [[15, 1, 17, 4]],
ach: ['Fix It Now', 'For want of a nail...'],
sum: 'The Nail. A merchant hurries home from the fair. A nail is missing from his horse\'s shoe, but he does not want to stop for it. Then the shoe falls off, the horse goes lame, and at last the horse falls, and the merchant has to walk home carrying his bags. All for want of a nail.',
quest: 'Your quest: find the road home from the fair, find the tree where he does not stop, and find the horseshoe.',
steps: [{ at: [10, 0, 3], hint: 'Find the road home from the fair.', say: 'A merchant hurries home from the fair. A nail is missing from his horse\'s shoe.' },
{ at: [10, 1, 8], hint: 'Find the tree where he does not stop.', say: 'He does not want to stop and fix it. Then the shoe falls off!' },
{ at: [15, 1, 17], hint: 'Find the horseshoe.', say: 'The horse goes lame and falls, and he must walk home. All for want of a nail!' }],
win: 'Fix it now! You earned the Horseshoe Nail, and a Merchant\'s Road kit to build at home.' },
{ id: 'poorboy', abc: 'The Poor Boy in the Grave', title: 'The Poor Boy in the Grave', place: "The Farmer's Yard", keep: 'Honey Pot', color: '#8a7a6a', parts: [879, 5],
tpl: 'cottage', props: [[8, 1, 12, 21]],
ach: ['Be Kind', 'A sad story about a poor shepherd boy.'],
sum: 'The Poor Boy in the Grave. A poor orphan shepherd boy lives with a rich farmer and his wife, who are cruel to him. When he loses a chick, he is so afraid of being beaten that he eats a pot the farmer said held poison, but it was honey. The poor boy dies. The cruel farmer\'s house burns down, and he loses everything. It is a very sad story.',
quest: 'Your quest: find the farmer\'s table, find the pot, and find the bed.',
steps: [{ id: 19, hint: 'Find the farmer\'s table.', say: 'A poor shepherd boy lives with a rich, cruel farmer and his wife.' },
{ id: 21, hint: 'Find the pot.', say: 'The farmer said the pot held poison, but it is only honey!' },
{ id: 31, hint: 'Find the bed.', say: 'The poor boy dies, and the cruel farmer loses everything in the end. Always be kind.' }],
win: 'You earned the Honey Pot, and a Farmer\'s Yard kit to build at home.' },
{ id: 'truesweethearts', abc: 'The True Sweethearts', title: 'The True Sweethearts', place: "The True Sweethearts' Palace", keep: 'Little Spoon', color: '#d06080', parts: [884, 10],
tpl: 'palace', props: [[6, 4, 16, 59]],
ach: ['True Love', 'She sang, and he remembered.'],
sum: 'The True Sweethearts. A wicked stepmother gives a girl impossible tasks: empty a pond with a spoon, build a castle. A kind old woman does them for her while she sleeps. A prince loves her, but when he goes home he forgets her. She waits patiently, and at his wedding feast she sings, and he remembers his true sweetheart.',
quest: 'Your quest: find the pond she must empty, find the tree where she waits, and go to the throne.',
steps: [{ at: [6, 4, 16], hint: 'Find the pond she must empty.', say: 'A wicked stepmother says: empty the pond with a spoon! A kind old woman helps.' },
{ at: [16, 1, 5], hint: 'Find the tree where she waits.', say: 'The prince goes home and forgets her, but she waits patiently.' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'At the wedding feast she sings, and he remembers. He marries his true sweetheart!' }],
win: 'True love! You earned the Little Spoon, and a True Sweethearts\' Palace kit to build at home.' },
{ id: 'harehedgehog', abc: 'The Hare and the Hedgehog', title: 'The Hare and the Hedgehog', place: 'The Turnip Field Race', keep: 'Little Turnip', color: '#8a9a5a', parts: [894, 5],
tpl: 'forest',
ach: ['I Am Here Already', 'Short legs, clever wife.'],
sum: 'The Hare and the Hedgehog. The proud hare laughs at the hedgehog\'s short crooked legs, so the hedgehog challenges him to a race across the field. The hedgehog\'s wife waits at the other end, and she looks just like him. Every time the hare gets there, a hedgehog says: I am here already! The hare runs back and forth until he can run no more.',
quest: 'Your quest: find the start of the race, find the furrow in the field, and find the end of the race.',
steps: [{ at: [6, 0, 6], hint: 'Find the start of the race.', say: 'The proud hare laughs at the hedgehog\'s short legs. Let us race! says the hedgehog.' },
{ at: [10, 1, 8], hint: 'Find the furrow in the field.', say: 'The hedgehog\'s wife waits at the other end of the field, and she looks just like him!' },
{ at: [12, 1, 17], hint: 'Find the end of the race.', say: 'I am here already! says a hedgehog, every time. The hare runs until he can run no more!' }],
win: 'The hedgehog wins! You earned the Little Turnip, and a Turnip Field Race kit to build at home.' },
{ id: 'spindle', abc: 'The Spindle, The Shuttle, and the Needle', title: 'The Spindle, The Shuttle, and the Needle', place: 'The Orphan\'s Cottage', keep: 'Golden Thread', color: '#d0b060', parts: [899, 4],
tpl: 'cottage', props: [[8, 1, 12, 68]],
ach: ['Poorest and Richest', 'A spindle, a shuttle and a needle make a home beautiful.'],
sum: 'The Spindle, The Shuttle, and the Needle. A poor orphan girl spins, weaves and sews in her little house. A prince is looking for a bride who is the poorest and the richest. When he rides by, she sings: spindle, spindle, go away, and bring my lover home! The spindle runs after him with a golden thread, the shuttle weaves a carpet, and the needle decorates her house, and the prince marries her.',
quest: 'Your quest: find the spinning wheel, find the road the spindle runs along, and find the table.',
steps: [{ id: 68, hint: 'Find the spinning wheel.', say: 'A poor orphan girl spins and weaves in her little house.' },
{ at: [10, 0, 3], hint: 'Find the road the spindle runs along.', say: 'Spindle, spindle, go away, and bring my lover home! The spindle runs after the prince with a golden thread.' },
{ id: 19, hint: 'Find the table.', say: 'The shuttle weaves a carpet and the needle decorates the room. The prince marries the poorest and richest girl!' }],
win: 'Poorest and richest! You earned the Golden Thread, and an Orphan\'s Cottage kit to build at home.' },
// template places, chunk 19 (ABC Books lessons 903-959, 2026-10-25)
{ id: 'peasantdevil', abc: 'The Peasant and the Devil', title: 'The Peasant and the Devil', place: "The Clever Peasant's Field", keep: 'Turnip', color: '#8a6a3a', parts: [903, 2],
tpl: 'cottage', props: [[3, 1, 10, 12], [4, 1, 13, 67]],
ach: ['Above or Below?', 'Turnips one year, wheat the next.'],
sum: 'The Peasant and the Devil. A clever peasant finds the devil sitting on a pile of treasure. They agree to share the crops for two years. The first year the devil wants what grows above the ground, so the peasant plants turnips. The next year the devil wants what grows below, so the peasant plants wheat! The devil gets nothing, and the peasant keeps the treasure.',
quest: 'Your quest: find the burning treasure, find the field of crops, and find the table.',
steps: [{ at: [3, 1, 10], hint: 'Find the burning treasure.', say: 'A clever peasant finds the devil sitting on a pile of treasure.' },
{ id: 67, hint: 'Find the field of crops.', say: 'The devil wants what grows above the ground, so the peasant plants turnips!' },
{ id: 19, hint: 'Find the table.', say: 'Next year the devil wants what grows below, so the peasant plants wheat! The clever peasant keeps the treasure.' }],
win: 'Clever peasant! You earned the Turnip, and a Clever Peasant\'s Field kit to build at home.' },
{ id: 'crumbs', abc: 'The Crumbs on the Table', title: 'The Crumbs on the Table', place: 'The Crumb Kitchen', keep: 'Bread Crumb', color: '#c0a070', parts: [905, 1],
tpl: 'cottage',
ach: ['Not Allowed', 'The cock said no. The chicks said yes.'],
sum: 'The Crumbs on the Table. A rooster tells the hen and the chicks: come quickly and eat the crumbs on the table, the mistress has gone out! The hen says they are not allowed. They eat them anyway, and when the mistress comes home, there is trouble for everyone.',
quest: 'Your quest: find the table with the crumbs, find the path where the mistress goes, and find the bed.',
steps: [{ id: 19, hint: 'Find the table with the crumbs.', say: 'Quick, eat the crumbs on the table! says the rooster.' },
{ at: [10, 0, 3], hint: 'Find the path where the mistress goes.', say: 'The mistress has gone out. But we are not allowed! says the hen.' },
{ id: 31, hint: 'Find the bed.', say: 'They eat them anyway, and when the mistress comes home, there is trouble!' }],
win: 'You earned the Bread Crumb, and a Crumb Kitchen kit to build at home.' },
{ id: 'seahare', abc: 'The Sea-Hare', title: 'The Sea-Hare', place: 'The Tower of Twelve Windows', keep: 'Sea-Hare', color: '#4a8ab0', parts: [906, 5],
tpl: 'castle', props: [[10, 1, 15, 49]],
ach: ['Hide and Seek', 'Hide where she cannot look: in her own hair!'],
sum: 'The Sea-Hare. A princess has a tower with twelve windows, and from the top she can see everything in her kingdom. She will only marry a man who can hide from her. The youngest of three brothers is kind to a raven, a fish and a fox. The fox turns him into a tiny sea-hare, and he hides in the princess\'s own hair, where she cannot see him. So she marries him.',
quest: 'Your quest: find the twelve windows, find the tree where the fox helps him, and go to the throne.',
steps: [{ at: [10, 1, 15], hint: 'Find the twelve windows.', say: 'A princess has a tower with twelve windows, and from the top she can see everything!' },
{ at: [2, 1, 3], hint: 'Find the tree where the fox helps him.', say: 'The youngest brother is kind to a raven, a fish and a fox. The fox turns him into a tiny sea-hare.' },
{ at: [10, 1, 17], hint: 'Go to the throne.', say: 'He hides in her long hair, and she cannot find him! So she marries him.' }],
win: 'Best hiding place ever! You earned the Sea-Hare, and a Tower of Twelve Windows kit to build at home.' },
{ id: 'masterthief', abc: 'The Master-Thief', title: 'The Master-Thief', place: "The Count's Castle", keep: 'Ring', color: '#4a4a6a', parts: [911, 10],
tpl: 'castle', props: [[6, 1, 12, 67], [13, 1, 13, 31], [7, 1, 14, 21]],
ach: ['Master-Thief', 'A horse, a sheet, a ring and a parson in a sack.'],
sum: 'The Master-Thief. A poor farmer\'s son comes home years later as a master-thief. The count, his godfather, sets him three tests: steal his horse, take the sheet and ring from the countess\'s bed, and carry off the parson. He does all three with clever tricks. The count lets him go, but he must leave the country.',
quest: 'Your quest: find the stable, find the countess\'s bed, and find the sack.',
steps: [{ id: 67, hint: 'Find the stable.', say: 'The master-thief steals the count\'s horse right from under the sleeping grooms!' },
{ id: 31, hint: 'Find the countess\'s bed.', say: 'He takes the sheet and the ring right from the countess\'s bed!' },
{ id: 21, hint: 'Find the sack.', say: 'He even carries off the parson in a sack! The count lets him go, but he must leave the country.' }],
win: 'What a thief! You earned the Ring, and a Count\'s Castle kit to build at home.' },
{ id: 'drummer', abc: 'The Drummer', title: 'The Drummer', place: 'The Glass Mountain Palace', keep: 'Little Drum', color: '#a04040', parts: [921, 13],
tpl: 'palace', wall: 11, props: [[6, 1, 4, 51]],
ach: ['Drum Roll', 'A drummer, a glass mountain and a princess.'],
sum: 'The Drummer. A drummer finds a little piece of white linen by a lake. It belongs to a princess under a spell, who lives on top of a glass mountain. He climbs the glass mountain and works for a wicked witch, and the princess helps him with every impossible task. He forgets her for a while, but she wins him back, and they marry.',
quest: 'Your quest: find the white linen by the lake, climb the glass mountain, and go to the throne.',
steps: [{ at: [6, 1, 4], hint: 'Find the white linen by the lake.', say: 'A drummer finds a little piece of white linen by a lake. It belongs to a princess under a spell!' },
{ at: [10, 3, 13], hint: 'Climb the glass mountain.', say: 'He climbs the glass mountain and works for a wicked witch, and the princess helps him with every task.' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'He forgets her for a while, but at last they marry.' }],
win: 'Drum roll! You earned the Little Drum, and a Glass Mountain Palace kit to build at home.' },
{ id: 'earofcorn', abc: 'The Ear of Corn', title: 'The Ear of Corn', place: 'The Corn Field', keep: 'Ear of Corn', color: '#d0b050', parts: [934, 1],
tpl: 'forest', props: [[15, 1, 17, 67]],
ach: ['Do Not Waste', 'Once, corn grew all the way up the stalk.'],
sum: 'The Ear of Corn. Long ago, corn grew all the way up its stalk, and people had so much that they wasted it. When a woman uses some to wipe her child, God says the corn shall grow no more. The animals beg for their share, so God leaves a little at the top of the stalk, the way it grows now.',
quest: 'Your quest: find the path to the field, find the old tree, and find the ear of corn.',
steps: [{ at: [10, 0, 3], hint: 'Find the path to the field.', say: 'Long ago, corn grew all the way up the stalk!' },
{ at: [10, 1, 8], hint: 'Find the old tree.', say: 'People had so much that they wasted it.' },
{ at: [15, 1, 17], hint: 'Find the ear of corn.', say: 'The animals beg for their share, so God leaves a little at the top of the stalk, the way it grows now.' }],
win: 'Do not waste! You earned the Ear of Corn, and a Corn Field kit to build at home.' },
{ id: 'gravemound', abc: 'The Grave-Mound', title: 'The Grave-Mound', place: 'The Watch by the Grave', keep: 'Boot of Gold', color: '#6a6a5a', parts: [935, 6],
tpl: 'forest', props: [[15, 1, 17, 57]],
ach: ['Bottomless Boot', 'Cut a hole in the boot, and it never fills up.'],
sum: 'The Grave-Mound. A rich farmer asks a poor man to watch over his grave for three nights, and an old soldier keeps watch with him. The devil comes and offers gold to go away. The soldier holds out his boot to be filled, but he has cut a hole in it and placed it over a pit, so it never fills up! In the end they win all the devil\'s gold.',
quest: 'Your quest: find the grave-mound, find the path where the devil comes, and find the gold.',
steps: [{ at: [12, 1, 17], hint: 'Find the grave-mound.', say: 'A rich farmer asks a poor man to watch over his grave for three nights.' },
{ at: [10, 0, 3], hint: 'Find the path where the devil comes.', say: 'An old soldier keeps watch with him. The devil comes and offers gold!' },
{ at: [15, 1, 17], hint: 'Find the gold.', say: 'The soldier holds out his boot with a hole cut in it, so it never fills up. They win all the devil\'s gold!' }],
win: 'A bottomless boot! You earned the Boot of Gold, and a Watch by the Grave kit to build at home.' },
{ id: 'rinkrank', abc: 'Old Rinkrank', title: 'Old Rinkrank', place: 'The Glass Mountain Window', keep: 'Grey Beard Hair', color: '#9a9aaa', parts: [941, 3],
tpl: 'castle', wall: 11, props: [[6, 1, 12, 11], [13, 1, 14, 52]],
ach: ['Caught by the Beard', 'Old Rinkrank never saw it coming.'],
sum: 'Old Rinkrank. A princess falls into a glass mountain, where old Rinkrank with his long grey beard makes her work hard for him. One day, while he is out, she pulls up his ladder, and when he comes back she catches his long beard in the window. He has to give her the ladder, and she climbs out and goes home to her father.',
quest: 'Your quest: find the glass mountain, find the ladder, and go to the throne.',
steps: [{ at: [6, 1, 12], hint: 'Find the glass mountain.', say: 'A princess falls into a glass mountain, where old Rinkrank makes her work.' },
{ at: [13, 1, 14], hint: 'Find the ladder.', say: 'She pulls up his ladder, and catches his long grey beard in the window!' },
{ at: [10, 1, 17], hint: 'Go to the throne.', say: 'Old Rinkrank must give her the ladder, and she climbs out and goes home to her father.' }],
win: 'Free! You earned the Grey Beard Hair, and a Glass Mountain Window kit to build at home.' },
{ id: 'crystalball', abc: 'The Crystal Ball', title: 'The Crystal Ball', place: 'The Castle of the Golden Sun', keep: 'Crystal Ball', color: '#a0d0f0', parts: [944, 4],
tpl: 'castle', wall: 57, props: [[13, 1, 14, 51]],
ach: ['Spell Breaker', 'A bull, a firebird, an egg, a crystal ball.'],
sum: 'The Crystal Ball. A sorceress turns two brothers into an eagle and a whale. The youngest goes to the Castle of the Golden Sun, where a princess is under a spell. He fights a wild bull, a firebird flies out of it with an egg, and inside the egg is a crystal ball. When he holds it up, the spell is broken, and his brothers are free too.',
quest: 'Your quest: find the tree where the eagle sits, find the firebird\'s egg, and go to the throne.',
steps: [{ at: [18, 1, 3], hint: 'Find the tree where the eagle sits.', say: 'A sorceress turns two brothers into an eagle and a whale. The youngest goes to the Castle of the Golden Sun.' },
{ at: [13, 1, 14], hint: 'Find the firebird\'s egg.', say: 'He beats a wild bull, and a firebird flies out with an egg. Inside the egg is a crystal ball!' },
{ at: [10, 1, 17], hint: 'Go to the throne.', say: 'He holds up the crystal ball, and the spell is broken!' }],
win: 'Spell broken! You earned the Crystal Ball, and a Castle of the Golden Sun kit to build at home.' },
{ id: 'maleen', abc: 'Maid Maleen', title: 'Maid Maleen', place: "Maid Maleen's Tower", keep: 'Necklace', color: '#7a5a8a', parts: [948, 7],
tpl: 'castle', props: [[6, 1, 12, 3], [13, 1, 14, 20]],
ach: ['True Bride', 'Seven years in a tower, and she still won.'],
sum: 'Maid Maleen. A princess called Maid Maleen will not give up the prince she loves, so her father shuts her in a dark tower for seven years. When she digs her way out, the land is ruined, and she works as a kitchen maid in her sweetheart\'s castle. He is about to marry an ugly bride, but the bride cannot answer his questions, and Maid Maleen can. She is his true bride.',
quest: 'Your quest: find the dark tower, find the kitchen fire, and go to the throne.',
steps: [{ at: [6, 1, 12], hint: 'Find the dark tower.', say: 'Maid Maleen is shut in a dark tower for seven years, because she would not give up her true love.' },
{ id: 20, hint: 'Find the kitchen fire.', say: 'She digs her way out and works as a kitchen maid in her sweetheart\'s castle.' },
{ at: [10, 1, 17], hint: 'Go to the throne.', say: 'The ugly bride cannot answer his questions, but Maid Maleen can. She is his true bride!' }],
win: 'The true bride! You earned the Necklace, and a Maid Maleen\'s Tower kit to build at home.' },
{ id: 'buffaloboots', abc: 'The Boots of Buffalo-Leather', title: 'The Boots of Buffalo-Leather', place: "The Robbers' Wood", keep: 'Buffalo Boot', color: '#7a5a3a', parts: [955, 5],
tpl: 'forest',
ach: ['Fearless Soldier', 'He tricked the robbers. The huntsman was the king.'],
sum: 'The Boots of Buffalo-Leather. A soldier who is afraid of nothing, wearing boots of buffalo leather, meets a huntsman lost in the forest. They come to a robbers\' house, and the brave soldier tricks the robbers and keeps them both safe. The huntsman is really the king, and he rewards the soldier.',
quest: 'Your quest: find the forest path, find the robbers\' tree, and find the clearing.',
steps: [{ at: [10, 0, 3], hint: 'Find the forest path.', say: 'A soldier with boots of buffalo leather meets a huntsman lost in the forest.' },
{ at: [10, 1, 14], hint: 'Find the robbers\' tree.', say: 'They come to a robbers\' house, and the brave soldier tricks the robbers.' },
{ at: [12, 1, 17], hint: 'Find the clearing.', say: 'The huntsman is really the king! He rewards the brave soldier.' }],
win: 'Brave soldier! You earned the Buffalo Boot, and a Robbers\' Wood kit to build at home.' },
// template places, chunk 20: the Golden Key and the ten Children's Legends (ABC Books lessons 960-978, 2026-10-25)
{ id: 'goldenkey', abc: 'The Golden Key', title: 'The Golden Key', place: 'The Snowy Wood', keep: 'Golden Key', color: '#d0b040', parts: [960, 1],
tpl: 'forest', leaf: 51, props: [[15, 1, 17, 21]],
ach: ['What Is Inside?', 'We must wait until he opens the lid.'],
sum: 'The Golden Key. On a snowy winter day, a poor boy goes out to fetch wood on a sledge. He scrapes away the snow to make a fire, and finds a tiny golden key, and then a little iron chest. He finds the keyhole and turns the key once round. Now we must wait until he opens the lid, and then we shall know what wonderful things are inside.',
quest: 'Your quest: find the snowy path, find the golden key under the snow, and find the little iron chest.',
steps: [{ at: [10, 0, 3], hint: 'Find the snowy path.', say: 'On a snowy winter day, a poor boy goes out to fetch wood on a sledge.' },
{ at: [12, 1, 17], hint: 'Find the golden key under the snow.', say: 'He scrapes away the snow to make a fire, and finds a tiny golden key!' },
{ id: 21, hint: 'Find the little iron chest.', say: 'He finds an iron chest and turns the key once round. Now we must wait until he opens the lid!' }],
win: 'What could be inside? You earned the Golden Key, and a Snowy Wood kit to build at home.' },
{ id: 'stjoseph', abc: 'St. Joseph in the Forest', title: 'St. Joseph in the Forest', place: "St. Joseph's Hut", keep: 'Little Pancake', color: '#8a7a5a', parts: [961, 5],
tpl: 'cottage', wall: 6, props: [[8, 1, 12, 21]],
ach: ['Kind Sharer', 'Share your pancakes with an old man in the forest.'],
sum: 'St. Joseph in the Forest. Three sisters each get lost in the forest and come to the little hut of an old man, who is Saint Joseph. The youngest shares her food with him, and in the morning she finds a bag of gold. The second is also kind and is rewarded. The eldest is greedy and selfish, and gets nothing good at all.',
quest: 'Your quest: find the path into the forest, find the fire in the little hut, and find the bag of gold.',
steps: [{ at: [10, 0, 3], hint: 'Find the path into the forest.', say: 'The youngest sister gets lost in the forest and comes to a little hut.' },
{ id: 20, hint: 'Find the fire in the little hut.', say: 'An old man, Saint Joseph, lives here. She shares her food with him.' },
{ id: 21, hint: 'Find the bag of gold.', say: 'In the morning she finds a bag of gold! Her greedy eldest sister gets nothing good at all.' }],
win: 'Kindness wins! You earned the Little Pancake, and a St. Joseph\'s Hut kit to build at home.' },
{ id: 'apostles', abc: 'The Twelve Apostles', title: 'The Twelve Apostles', place: 'The Sleeping Cave', keep: 'Little Lamp', color: '#a0a0c0', parts: [966, 1],
tpl: 'forest',
ach: ['Long Sleep', 'Three hundred years asleep in a cave.'],
sum: 'The Twelve Apostles. Long, long ago, a poor mother has twelve sons. When the youngest goes out to find bread, an angel leads him to a cave, where all twelve brothers fall asleep for three hundred years. When they wake, they become the twelve apostles.',
quest: 'Your quest: find the path, find the tree by the cave, and find the clearing.',
steps: [{ at: [10, 0, 3], hint: 'Find the path.', say: 'A poor mother has twelve sons and no bread.' },
{ at: [10, 1, 14], hint: 'Find the tree by the cave.', say: 'An angel leads the brothers to a cave, and they fall asleep for three hundred years.' },
{ at: [12, 1, 17], hint: 'Find the clearing.', say: 'When they wake, they become the twelve apostles.' }],
win: 'You earned the Little Lamp, and a Sleeping Cave kit to build at home.' },
{ id: 'rose', abc: 'The Rose', title: 'The Rose', place: 'The Rose Cottage', keep: 'Rosebud', color: '#d06080', parts: [967, 1],
tpl: 'cottage', props: [[3, 1, 10, 73]],
ach: ['Little Rosebud', 'A gentle, sad little legend.'],
sum: 'The Rose. A poor woman\'s little child gathers wood in the forest, and another child, kind and beautiful, helps her and gives her a rosebud. When the rose is in bloom, the little child has gone to heaven. It is a gentle, sad little legend.',
quest: 'Your quest: find the path to the forest, find the rosebud, and find the little bed.',
steps: [{ at: [10, 0, 3], hint: 'Find the path to the forest.', say: 'A poor woman\'s little child gathers wood in the forest.' },
{ at: [3, 1, 10], hint: 'Find the rosebud.', say: 'A kind and beautiful child helps her and gives her a rosebud.' },
{ id: 31, hint: 'Find the little bed.', say: 'When the rose is in bloom, the little child has gone to heaven.' }],
win: 'You earned the Rosebud, and a Rose Cottage kit to build at home.' },
{ id: 'poverty', abc: 'Poverty and Humility Lead to Heaven', title: 'Poverty and Humility Lead to Heaven', place: 'The Palace Stairs', keep: 'Wooden Bowl', color: '#a09080', parts: [968, 2],
tpl: 'palace',
ach: ['Humble Heart', 'A king\'s son who chose to be poor.'],
sum: 'Poverty and Humility Lead to Heaven. A king\'s son wants to go to heaven, so he gives up his riches and lives as a poor beggar for years. When he comes home, nobody knows him, and he lives humbly under the stairs of his parents\' palace. When he dies, he goes to heaven.',
quest: 'Your quest: climb the palace stairs, find the light under the stairs, and go to the throne.',
steps: [{ at: [10, 3, 13], hint: 'Climb the palace stairs.', say: 'A king\'s son gives up his riches to live as a poor beggar.' },
{ at: [8, 4, 13], hint: 'Find the light by the stairs.', say: 'When he comes home, nobody knows him, and he lives humbly under the stairs.' },
{ at: [10, 4, 18], hint: 'Go to the throne.', say: 'When he dies, he goes to heaven.' }],
win: 'You earned the Wooden Bowl, and a Palace Stairs kit to build at home.' },
{ id: 'godsfood', abc: "God's Food", title: "God's Food", place: "The Sisters' Houses", keep: 'Loaf of Bread', color: '#c0a070', parts: [970, 1],
tpl: 'cottage',
ach: ['Share Your Bread', 'The rich sister would not share.'],
sum: 'God\'s Food. A poor woman with five hungry children asks her rich sister for bread, and is sent away. When the rich sister\'s husband cuts his own bread, it is red, as a sign. The poor children have gone to heaven to eat God\'s food. It is a short, sad legend about sharing.',
quest: 'Your quest: find the table, find the path between the houses, and find the bed.',
steps: [{ id: 19, hint: 'Find the table.', say: 'A poor woman with five hungry children asks her rich sister for bread.' },
{ at: [10, 0, 3], hint: 'Find the path between the houses.', say: 'The rich sister sends her away with nothing.' },
{ id: 31, hint: 'Find the bed.', say: 'The poor children have gone to heaven to eat God\'s food. Always share your bread.' }],
win: 'You earned the Loaf of Bread, and a Sisters\' Houses kit to build at home.' },
{ id: 'greentwigs', abc: 'The Three Green Twigs', title: 'The Three Green Twigs', place: "The Hermit's Hill", keep: 'Green Twig', color: '#5a8a3a', parts: [971, 3],
tpl: 'forest',
ach: ['Three Green Twigs', 'A dry branch that grew green again.'],
sum: 'The Three Green Twigs. A hermit judges a sinner too harshly, and as a punishment he must carry a dry branch until three green twigs grow on it. He wanders for a long time. At last he helps three robbers turn from their bad ways, and the three green twigs grow.',
quest: 'Your quest: find the hermit\'s tree, find the long road, and find the clearing.',
steps: [{ at: [10, 1, 8], hint: 'Find the hermit\'s tree.', say: 'A hermit judges a sinner too harshly.' },
{ at: [6, 0, 6], hint: 'Find the long road.', say: 'He must carry a dry branch until three green twigs grow on it.' },
{ at: [12, 1, 17], hint: 'Find the clearing.', say: 'He helps three robbers turn good, and the three green twigs grow!' }],
win: 'Green again! You earned the Green Twig, and a Hermit\'s Hill kit to build at home.' },
{ id: 'ladysglass', abc: "Our Lady's Little Glass", title: "Our Lady's Little Glass", place: 'The Bindweed Road', keep: 'Little Flower Glass', color: '#c0a0e0', parts: [974, 1],
tpl: 'forest', props: [[15, 1, 17, 37]],
ach: ['Little Glass', 'Why the bindweed flower is called Our Lady\'s little glass.'],
sum: 'Our Lady\'s Little Glass. A carter\'s wagon full of wine is stuck in the mud. The Virgin Mary comes by and helps him, and asks for a little wine. He has no glass, so she picks a white bindweed flower and drinks from it. That is why the bindweed is called Our Lady\'s little glass.',
quest: 'Your quest: find the muddy road, find the old tree, and find the bindweed flower.',
steps: [{ at: [10, 0, 3], hint: 'Find the muddy road.', say: 'A carter\'s wagon full of wine is stuck in the mud.' },
{ at: [10, 1, 8], hint: 'Find the old tree.', say: 'The Virgin Mary comes by and helps him, and asks for a little wine.' },
{ at: [15, 1, 17], hint: 'Find the bindweed flower.', say: 'He has no glass, so she drinks from a bindweed flower. That is Our Lady\'s little glass!' }],
win: 'You earned the Little Flower Glass, and a Bindweed Road kit to build at home.' },
{ id: 'agedmother', abc: 'The Aged Mother', title: 'The Aged Mother', place: "The Old Mother's House", keep: 'Candle', color: '#9a8aa0', parts: [975, 1],
tpl: 'cottage', props: [[3, 1, 10, 49]],
ach: ['Remember Them', 'A quiet legend about an old mother.'],
sum: 'The Aged Mother. An old woman lives alone, and grieves for her husband and her two sons who have died. Early on Christmas morning she goes to church and sees them there, as they might have been. She understands that God was kind to take them when he did, and goes home in peace.',
quest: 'Your quest: find the old mother\'s fire, find the candle, and find the table.',
steps: [{ id: 20, hint: 'Find the old mother\'s fire.', say: 'An old woman lives alone, and grieves for her husband and her two sons.' },
{ at: [3, 1, 10], hint: 'Find the candle.', say: 'Early on Christmas morning she goes to church, and sees them there.' },
{ id: 19, hint: 'Find the table.', say: 'She understands, and goes home in peace.' }],
win: 'You earned the Candle, and an Old Mother\'s House kit to build at home.' },
{ id: 'heavenlywedding', abc: 'The Heavenly Wedding', title: 'The Heavenly Wedding', place: 'The Little Church', keep: 'Little Bell', color: '#e0e0f0', parts: [976, 2],
tpl: 'castle', wall: 50,
ach: ['Heavenly Wedding', 'A poor boy who listened very carefully.'],
sum: 'The Heavenly Wedding. A poor country boy hears in church that whoever wants to go to heaven must walk straight on. So he walks straight on, over hills and valleys, until he comes to a great church. He takes care of the statue of the Virgin Mary and the little child, and on the day he is promised, he goes to the heavenly wedding.',
quest: 'Your quest: find the long straight road, find the light in the church, and go to the altar.',
steps: [{ at: [10, 0, 3], hint: 'Find the long straight road.', say: 'A poor country boy hears that whoever wants to go to heaven must walk straight on.' },
{ at: [7, 1, 9], hint: 'Find the light in the church.', say: 'He walks straight on until he comes to a great church, and takes care of it.' },
{ at: [10, 1, 17], hint: 'Go to the altar.', say: 'On the day he was promised, he goes to the heavenly wedding.' }],
win: 'You earned the Little Bell, and a Little Church kit to build at home.' },
{ id: 'hazelbranch', abc: 'The Hazel-Branch', title: 'The Hazel-Branch', place: 'The Hazel Bush', keep: 'Hazel Branch', color: '#8a7a4a', parts: [978, 1],
tpl: 'forest', props: [[15, 1, 17, 36]],
ach: ['Safe Under the Hazel', 'The hazel bush keeps the snakes away.'],
sum: 'The Hazel-Branch. One day the Virgin Mary goes into the wood to pick strawberries for the little child. An adder springs up from the grass, and she hides behind a hazel bush until it has gone. Ever since, says the legend, a hazel branch is the best protection against snakes.',
quest: 'Your quest: find the path into the wood, find the strawberries, and find the hazel bush.',
steps: [{ at: [10, 0, 3], hint: 'Find the path into the wood.', say: 'The Virgin Mary goes into the wood to pick strawberries for the little child.' },
{ at: [15, 1, 17], hint: 'Find the strawberries.', say: 'An adder springs up from the grass!' },
{ at: [10, 1, 14], hint: 'Find the hazel bush.', say: 'She hides behind a hazel bush until it has gone. Ever since, a hazel branch protects against snakes.' }],
win: 'Safe! You earned the Hazel Branch, and a Hazel Bush kit to build at home.' },
];
const TALE_IDX = {}; TALES.forEach((T, i) => { TALE_IDX[T.id] = i; });
// where each place goes: [column, row]. The first ten fill two rows of five (row 0 north of the plaza, row 1 south of it);
// later tales add columns, east, then west, then further east, and so on (both rows of a column before the next column).
// Column c starts at x = -82 + 36 c. The hedge round the kingdom (KX0 .. KX1) grows with the columns.
const slotOf = i => { if (i < 10) return [i % 5, i >= 5 ? 1 : 0]; const j = i - 10, p = j >> 1; return [p % 2 ? -1 - (p >> 1) : 5 + (p >> 1), j & 1]; };
const SLOTS = {}; let KC0 = 0, KC1 = 4;
TALES.forEach((T, i) => { const [c, r] = slotOf(i); SLOTS[c + ',' + r] = i; KC0 = Math.min(KC0, c); KC1 = Math.max(KC1, c); });
const KX0 = -96 + 36 * KC0, KX1 = 95 + 36 * (KC1 - 4), COLX = [];
for (let c = KC0; c <= KC1; c++) COLX.push(-72 + 36 * c); // the middle of each column: a gravel path runs from the plaza road to its gates
// name of an owned kit build: a castle type, or 'tale:<id>' for a fairy tale place
const ownedName = type => String(type).startsWith('tale:') ? (TALES[TALE_IDX[type.slice(5)]] || { place: 'Story Place' }).place
: PLAY_KITS[type] ? PLAY_KITS[type].name : (CASTLES[type] || CASTLES.stone).name;
// pets + play add-on kits: a playground and Layla's heart factory, CW x CW like a castle kit, owned by whoever places it.
// block at (lx, dy, lz): dy is the height above the ground (0 = the ground itself); -1 leaves what is there; flag = owner's wool
const PLAY_KITS = {
playground: { name: 'Playground', block(lx, dy, lz, flag) {
const edge = lx === 0 || lz === 0 || lx === CW - 1 || lz === CW - 1, gate = lz === CW - 1 && lx >= 9 && lx <= 11;
if (dy === 0) return lx >= 3 && lx <= 5 && lz >= 3 && lz <= 5 ? 92 : edge ? 5 : 8; // trampolines in the sand, a plank rim
if (dy === 1 && edge) return gate ? 0 : (lx + lz) % 4 === 0 ? 49 : flag; // a low fence in the owner's colour, lights
if (lx === 15 && lz >= 9 && lz <= 13) { const top = 14 - lz; return dy === top ? 93 : dy < top ? 5 : 0; } // the slide comes down
if (lx >= 14 && lx <= 16 && lz >= 3 && lz <= 8) { const top = Math.min(5, lz - 2); return dy <= top ? (dy === top ? 5 : 6) : 0; } // steps up to it
if ((lx === 3 || lx === 7) && lz === 14 && dy <= 4) return 6; // swing posts
if (lx > 3 && lx < 7 && lz === 14 && dy === 4) return 6; // swing bar
if ((lx === 4 || lx === 6) && lz === 14 && dy === 1) return 94; // two swings
if (lx >= 13 && lx <= 17 && lz >= 15 && lz <= 17 && dy === 1) return lx === 15 && lz === 16 ? 49 : 95; // merry-go-round
return dy <= 12 ? 0 : -1;
} },
heart: { name: 'Heart Factory', block(lx, dy, lz) {
const inX = lx >= 4 && lx <= 16, inZ = lz >= 4 && lz <= 16, wall = inX && inZ && (lx === 4 || lx === 16 || lz === 4 || lz === 16);
if (dy === 0) return inX && inZ ? 96 : -1;
if (dy > 12) return -1;
if ((lx === 6 || lx === 14) && lz === 6 && dy >= 7 && dy <= 11) return dy === 11 ? 49 : 96; // two chimneys
if (!(inX && inZ)) return 0;
if (dy === 7) return 96; // roof
if (dy > 7) return 0;
if (wall) {
if (lz === 16 && lx >= 9 && lx <= 11 && dy <= 2) return 0; // the door
const row = { 6: [8, 9, 11, 12], 5: [7, 8, 9, 10, 11, 12, 13], 4: [8, 9, 10, 11, 12], 3: [9, 10, 11] }[dy];
if (lz === 16 && row && row.includes(lx)) return 40; // a big red heart over the door
if ((dy === 3 || dy === 4) && (lx + lz) % 4 === 1) return 11; // windows
return (lx + dy + lz) % 3 === 0 ? 96 : 47; // pink wool and heart blocks
}
if (lx === 10 && lz === 10 && dy === 1) return 97; // the heart machine
if ((lx === 6 || lx === 14) && (lz === 6 || lz === 14) && dy === 1) return 49; // lights
return 0;
} },
};
// rewards: the keepsake and the place kit, both earned only. Tales 0-9: keepsake 200 + i, kit 210 + i; tales 10-99: 290 + i and 390 + i
// (from place 100 on: keepsake 1000 + i, kit 2000 + i, so 290 + i never meets 390 + i; room for 1,000 places, ids stay above 100 = items)
const taleIds = i => i < 10 ? [200 + i, 210 + i] : i < 100 ? [290 + i, 390 + i] : [1000 + i, 2000 + i];
TALES.forEach((T, i) => { [T.keepId, T.kitId] = taleIds(i); I(T.keepId, T.keep, { stack: 1, keep: T.id, tile: T.tile, earn: true }); I(T.kitId, T.place + ' Kit', { stack: 1, tkit: T.id, earn: true }); });
// the 21 x 21 x PH block plan of place i (dy from PY0): ground, the hedge with its gate and story stone, then the tale's own build
// Place templates for the later tales (Grimm batch 3 on): a TALES entry gets tpl: 'cottage' (or castle, forest, well, mill,
// palace), optional wall / roof / floor / leaf block ids, and props: [[x, y, z, id], ...] for its own quest things.
// Local spots: the gate is at (10, 0) and the gravel path runs north from it; y 1 is standing height on the ground.
// Each template lists its free spots for props, and the blocks a step can ask for by id (bed 31, fire 20, table 19 ...).
const PLACE_TPL = {
cottage(T, { s, box, house, roof, tree }) { // timbered cottage, door (10, 1, 7); free inside (7..13, 1, 8..12), yard (2..5, 1, 8..14)
box(9, 0, 1, 11, 0, 6, 9);
house(6, 7, 14, 14, 4, T.wall || 5, T.floor); for (const [x, z] of [[6, 7], [14, 7], [6, 14], [14, 14]]) box(x, 1, z, x, 4, z, 6);
s(10, 1, 7, 23); s(10, 2, 7, 24); s(8, 2, 7, 11); s(12, 2, 7, 11); s(6, 2, 10, 11); s(14, 2, 10, 11); s(10, 2, 14, 11);
roof(6, 7, 14, 14, 5, T.roof || 33, 4);
s(7, 1, 13, 31); s(13, 1, 13, 20); s(10, 1, 11, 19); s(12, 1, 13, 35); s(10, 4, 11, 49); // bed, fire, table, shelf, lamp
tree(3, 4, 4, T.leaf); tree(17, 4, 4, T.leaf); tree(3, 17, 4, T.leaf); tree(17, 17, 4, T.leaf);
for (const [x, z, f] of [[7, 4, 36], [13, 3, 37], [17, 10, 36], [3, 11, 37]]) s(x, 1, z, f);
},
castle(T, { s, box, house, tree }) { // stone hall with four towers, door (10, 1, 8); free inside (6..14, 1, 9..16), throne (10, 1, 17) gold
const w = T.wall || 34;
box(9, 0, 1, 11, 0, 7, 9);
house(4, 8, 16, 18, 6, w, T.floor); box(4, 7, 8, 16, 7, 18, w);
for (let x = 4; x <= 16; x += 2) { s(x, 8, 8, w); s(x, 8, 18, w); }
for (const [x, z] of [[4, 8], [16, 8], [4, 18], [16, 18]]) { box(x - 1, 1, z - 1, x + 1, 9, z + 1, w); s(x - 1, 10, z - 1, w); s(x + 1, 10, z - 1, w); s(x - 1, 10, z + 1, w); s(x + 1, 10, z + 1, w); }
s(10, 1, 8, 23); s(10, 2, 8, 24); s(7, 3, 8, 11); s(13, 3, 8, 11); s(4, 3, 13, 11); s(16, 3, 13, 11);
s(10, 1, 17, 57); s(7, 1, 9, 22); s(13, 1, 9, 22); s(10, 6, 13, 49); s(7, 6, 13, 49); s(13, 6, 13, 49);
tree(2, 3, 4, T.leaf); tree(18, 3, 4, T.leaf);
for (const [x, z, f] of [[6, 4, 36], [14, 4, 37], [1, 13, 36], [19, 13, 37]]) s(x, 1, z, f);
},
forest(T, { s, box, tree }) { // a winding path through a deep wood to a clearing; turns (6, 1, 6), (6, 1, 11), (14, 1, 11); clearing (8..16, 1, 15..19), stump (12, 1, 17)
box(10, 0, 1, 10, 0, 6, 9); box(6, 0, 6, 10, 0, 6, 9); box(6, 0, 6, 6, 0, 11, 9); box(6, 0, 11, 14, 0, 11, 9); box(14, 0, 11, 14, 0, 15, 9);
s(12, 1, 17, 6);
for (const [x, z, h] of [[3, 3, 5], [15, 3, 5], [2, 9, 5], [10, 8, 4], [17, 7, 5], [3, 15, 4], [10, 14, 4], [18, 14, 5], [4, 19, 4], [18, 19, 4]]) tree(x, z, h, T.leaf);
for (const [x, z, f] of [[8, 3, 36], [12, 4, 37], [4, 7, 38], [8, 9, 38], [12, 9, 36], [16, 10, 37], [9, 17, 36], [15, 18, 37], [11, 19, 38]]) s(x, 1, z, f);
},
well(T, { s, box, ring, house, roof, tree }) { // the village well (bottom (10, -2, 10), rim (12, 2, 8)), a little hut at the back left, door (8, 1, 16); free (3..7, 1, 14..18)
box(9, 0, 1, 11, 0, 6, 9);
box(8, PY0, 8, 12, 0, 12, 4); box(9, -2, 9, 11, 0, 11, 10); ring(8, 8, 12, 12, 1, 1, 4);
box(8, 2, 10, 8, 3, 10, 6); box(12, 2, 10, 12, 3, 10, 6); box(8, 4, 10, 12, 4, 10, 6);
s(7, 1, 7, 22); s(13, 1, 7, 22);
house(2, 13, 8, 19, 3, T.wall || 5, T.floor); s(8, 1, 16, 25); s(8, 2, 16, 26); s(5, 2, 13, 11); s(2, 2, 16, 11);
roof(2, 13, 8, 19, 4, T.roof || 40, 3); s(3, 1, 18, 31); s(7, 1, 18, 20); s(5, 3, 16, 49);
tree(4, 5, 5, T.leaf); tree(16, 15, 5, T.leaf); tree(17, 4, 4, T.leaf);
for (const [x, z, f] of [[6, 3, 36], [14, 3, 37], [15, 9, 36], [11, 15, 37], [12, 18, 36]]) s(x, 1, z, f);
},
mill(T, { s, box, house, roof, tree }) { // a mill by a stream: bridge (10, 0, 9..11), mill door (9, 1, 12), water wheel at x 15; free inside (6..12, 1, 13..17), millstone (8, 1, 15)
box(9, 0, 1, 11, 0, 8, 9);
box(2, -2, 9, 18, 0, 11, 10); box(9, 0, 9, 11, 0, 11, 5);
house(5, 12, 13, 18, 5, T.wall || 5, T.floor); for (const [x, z] of [[5, 12], [13, 12], [5, 18], [13, 18]]) box(x, 1, z, x, 5, z, 6);
s(9, 1, 12, 23); s(9, 2, 12, 24); s(7, 3, 12, 11); s(11, 3, 12, 11); s(5, 3, 15, 11); s(13, 3, 16, 11);
roof(5, 12, 13, 18, 6, T.roof || 33, 3);
s(8, 1, 15, 4); s(8, 2, 15, 48); s(11, 1, 17, 67); s(12, 1, 17, 67); s(12, 1, 16, 67); s(6, 1, 17, 21); s(9, 5, 15, 49);
for (let dy = -3; dy <= 3; dy++) for (let dz = -3; dz <= 3; dz++) { const r = Math.hypot(dy, dz); if (r > 2.4 && r < 3.6) s(15, 1 + dy, 11 + dz, 5); else if (r < 2.4 && (dy === 0 || dz === 0)) s(15, 1 + dy, 11 + dz, 6); }
s(14, 1, 11, 6);
tree(3, 4, 4, T.leaf); tree(17, 4, 5, T.leaf); tree(17, 17, 4, T.leaf);
for (const [x, z, f] of [[6, 5, 36], [14, 6, 37], [3, 14, 36], [16, 14, 37]]) s(x, 1, z, f);
},
palace(T, { s, box, tree }) { // a grand palace up wide stairs: stair top (10, 4, 13), door (10, 4, 14); free inside (5..15, 4, 15..18), throne (10, 4, 18) gold
const w = T.wall || 50;
box(9, 0, 1, 11, 0, 9, 9);
box(3, 1, 10, 17, 1, 19, 34); box(3, 2, 11, 17, 2, 19, 34); box(3, 3, 12, 17, 3, 19, 34);
box(3, 4, 14, 17, 10, 19, w); box(4, 4, 15, 16, 9, 18, 0);
for (let x = 3; x <= 17; x += 2) { s(x, 11, 14, 57); s(x, 11, 19, 57); }
s(10, 4, 14, 23); s(10, 5, 14, 24); s(6, 6, 14, 11); s(14, 6, 14, 11); s(3, 6, 16, 11); s(17, 6, 16, 11);
s(10, 4, 18, 57); s(8, 4, 13, 22); s(12, 4, 13, 22); s(7, 9, 16, 49); s(13, 9, 16, 49);
tree(4, 5, 4, T.leaf); tree(16, 5, 4, T.leaf);
for (const [x, z, f] of [[6, 3, 36], [7, 7, 37], [13, 3, 36], [14, 7, 37], [2, 8, 36], [18, 8, 37]]) s(x, 1, z, f);
},
};
const placeCache = [];
const placeArr = i => placeCache[i] || (placeCache[i] = placePlan(TALES[i]));
function placePlan(T) {
const a = new Uint8Array(PW * PW * PH);
const ix = (x, y, z) => ((y - PY0) * PW + z) * PW + x;
const ok = (x, y, z) => x >= 0 && x < PW && z >= 0 && z < PW && y >= PY0 && y < PY0 + PH;
const s = (x, y, z, id) => { if (ok(x, y, z)) a[ix(x, y, z)] = id; };
const g = (x, y, z) => ok(x, y, z) ? a[ix(x, y, z)] : 0;
const box = (x0, y0, z0, x1, y1, z1, id) => { for (let y = y0; y <= y1; y++) for (let z = z0; z <= z1; z++) for (let x = x0; x <= x1; x++) s(x, y, z, id); };
const ring = (x0, z0, x1, z1, y0, y1, id) => { for (let y = y0; y <= y1; y++) for (let z = z0; z <= z1; z++) for (let x = x0; x <= x1; x++) if (x === x0 || x === x1 || z === z0 || z === z1) s(x, y, z, id); };
const house = (x0, z0, x1, z1, h, wall, floor) => { box(x0, 1, z0, x1, h, z1, wall); box(x0 + 1, 1, z0 + 1, x1 - 1, h, z1 - 1, 0); box(x0 + 1, 0, z0 + 1, x1 - 1, 0, z1 - 1, floor || 5); };
const roof = (x0, z0, x1, z1, y, id, n) => { for (let k = 0; k < n; k++) box(x0 + k, y + k, z0 + k, x1 - k, y + k, z1 - k, id); };
const tree = (x, z, h, leaf) => { // an oak (or a magic tree with other leaves): leaves only where nothing else is
for (let y = h - 1; y <= h + 1; y++) { const r = y > h ? 1 : 2;
for (let dz = -r; dz <= r; dz++) for (let dx = -r; dx <= r; dx++) if (!(Math.abs(dx) === r && Math.abs(dz) === r) && !g(x + dx, y, z + dz)) s(x + dx, y, z + dz, leaf || 7); }
box(x, 1, z, x, h, z, 6);
};
box(0, PY0, 0, 20, -1, 20, 2); box(0, 0, 0, 20, 0, 20, 1);
ring(0, 0, 20, 20, 1, 3, 65); s(10, 1, 0, 64); s(10, 2, 0, 64); s(12, 1, 0, 63);
switch (T.id) {
case 'elves': // a little timbered shop with a brick roof; shoes hidden inside, the workbench by the window
box(9, 0, 1, 11, 0, 6, 9);
house(6, 7, 14, 13, 4, 5);
for (const [x, z] of [[6, 7], [14, 7], [6, 13], [14, 13]]) box(x, 1, z, x, 4, z, 6);
s(10, 1, 7, 23); s(10, 2, 7, 24); s(8, 2, 7, 11); s(12, 2, 7, 11); s(6, 2, 10, 11); s(14, 2, 10, 11); s(10, 2, 13, 11);
roof(6, 7, 14, 13, 5, 33, 4); box(13, 6, 11, 13, 9, 11, 33);
s(8, 1, 11, 19); s(12, 1, 12, 35); s(13, 1, 12, 35); s(10, 4, 10, 49);
s(12, 2, 12, 76); s(7, 1, 9, 76); s(13, 1, 9, 76);
for (const [x, z, f] of [[4, 4, 36], [5, 3, 37], [16, 4, 36], [15, 3, 37], [3, 8, 37], [17, 9, 36]]) s(x, 1, z, f);
tree(3, 16, 4); tree(17, 16, 4);
break;
case 'frog': // the deep well with the golden ball at the bottom, a lime tree, the castle wall behind
box(9, 0, 1, 11, 0, 6, 9);
box(8, PY0, 8, 12, 0, 12, 4); box(9, -2, 9, 11, 0, 11, 10); ring(8, 8, 12, 12, 1, 1, 4);
s(10, -2, 10, 66); s(12, 2, 8, 81);
box(8, 2, 10, 8, 3, 10, 6); box(12, 2, 10, 12, 3, 10, 6); box(8, 4, 10, 12, 4, 10, 6);
s(7, 1, 7, 22); s(13, 1, 7, 22);
tree(4, 10, 5);
box(2, 1, 17, 18, 6, 18, 34); for (let x = 2; x <= 18; x += 2) s(x, 7, 17, 34);
box(14, 1, 14, 18, 9, 18, 34); for (let x = 14; x <= 18; x += 2) { s(x, 10, 14, 34); s(x, 10, 18, 34); }
box(16, 10, 16, 16, 12, 16, 6); s(17, 12, 16, 42);
for (const [x, z, f] of [[3, 4, 37], [6, 14, 36], [15, 5, 37], [17, 11, 36]]) s(x, 1, z, f);
break;
case 'redcap': // mother's little house by the gate, a path through the wood, grandmother's cottage at the back
house(2, 2, 7, 7, 3, 5); s(7, 1, 5, 25); s(7, 2, 5, 26); s(2, 2, 4, 11); s(4, 2, 7, 11);
roof(2, 2, 7, 7, 4, 40, 3);
s(8, 1, 4, 77);
box(10, 0, 1, 10, 0, 8, 9); box(10, 0, 8, 14, 0, 8, 9); box(14, 0, 8, 14, 0, 11, 9);
tree(5, 12, 5); tree(17, 4, 5); tree(3, 17, 4); tree(8, 16, 4);
for (const [x, z, f] of [[8, 10, 36], [9, 13, 36], [6, 9, 36], [11, 15, 37], [12, 10, 37], [7, 14, 36]]) s(x, 1, z, f);
house(12, 12, 18, 18, 3, 4); for (const [x, z] of [[12, 12], [18, 12], [12, 18], [18, 18]]) box(x, 1, z, x, 3, z, 6);
s(14, 1, 12, 23); s(14, 2, 12, 24); s(16, 2, 12, 11); s(18, 2, 15, 11);
roof(12, 12, 18, 18, 4, 5, 3);
s(16, 1, 16, 31); s(13, 1, 17, 35); s(15, 3, 15, 49);
break;
case 'bremen': // the robbers' log house deep in the wood, lit window, the four animals underneath
box(9, 0, 1, 11, 0, 7, 9);
tree(3, 4, 5); tree(17, 4, 5); tree(2, 13, 5); tree(18, 13, 5); tree(10, 19, 4);
house(5, 8, 15, 16, 4, 6); s(12, 1, 8, 23); s(12, 2, 8, 24); s(8, 2, 8, 11); s(15, 2, 12, 11);
roof(5, 8, 15, 16, 5, 5, 3);
s(8, 1, 7, 78); s(10, 1, 13, 5); s(10, 2, 13, 77); s(14, 1, 15, 20); s(10, 4, 12, 49); s(7, 1, 15, 35);
break;
case 'rumpel': // the king's spinning room full of straw, with gold; the little man's fire in the wood behind
box(9, 0, 1, 11, 0, 5, 9);
house(4, 6, 16, 15, 6, 34); s(10, 1, 6, 23); s(10, 2, 6, 24);
s(7, 3, 6, 11); s(13, 3, 6, 11); s(4, 3, 10, 11); s(16, 3, 10, 11);
box(4, 7, 6, 16, 7, 15, 34); for (let x = 4; x <= 16; x += 2) { s(x, 8, 6, 34); s(x, 8, 15, 34); }
s(10, 5, 10, 49);
box(5, 1, 12, 7, 1, 14, 67); box(5, 2, 13, 6, 2, 14, 67); s(5, 3, 14, 67);
s(10, 1, 11, 68);
box(13, 1, 12, 15, 1, 14, 57); s(14, 2, 13, 57); s(15, 2, 14, 57);
box(5, 0, 17, 7, 0, 19, 4); s(6, 1, 18, 22); tree(2, 17, 4); tree(16, 18, 4); tree(18, 3, 4);
break;
case 'holle': // the meadow under the well: bread oven, apple tree, Mother Holle's snowy house with the featherbed
box(9, 0, 1, 11, 0, 4, 9);
ring(14, 2, 16, 4, 1, 1, 4); s(15, 0, 3, 10);
box(2, 1, 5, 4, 3, 7, 33); s(3, 1, 5, 20); s(3, 4, 6, 33);
tree(5, 13, 5); s(3, 4, 13, 40); s(6, 5, 12, 40); s(5, 4, 15, 40); s(7, 4, 14, 40);
house(10, 10, 18, 18, 4, 51); for (const [x, z] of [[10, 10], [18, 10], [10, 18], [18, 18]]) box(x, 1, z, x, 4, z, 6);
s(14, 1, 10, 23); s(14, 2, 10, 24); s(12, 2, 10, 11); s(16, 2, 10, 11); s(18, 2, 14, 11);
roof(10, 10, 18, 18, 5, 51, 3);
s(17, 1, 14, 75); s(17, 1, 15, 75); s(11, 1, 17, 35); s(14, 4, 14, 49);
for (const [x, z, f] of [[7, 3, 37], [5, 9, 36], [8, 17, 37], [2, 18, 36]]) s(x, 1, z, f);
break;
case 'briar': // a second ring of thorns with a rose in it, a sleeping castle tower: spinning wheel and bed at the top
box(9, 0, 1, 11, 0, 2, 9);
ring(3, 3, 17, 17, 1, 4, 65); box(10, 1, 3, 10, 3, 3, 0); s(10, 1, 3, 73);
for (let k = 3; k <= 17; k += 2) { s(k, 5, 3, 73); s(k, 5, 17, 73); s(3, 5, k, 73); s(17, 5, k, 73); }
box(4, 0, 4, 16, 0, 16, 34);
box(8, 1, 9, 12, 11, 13, 34); box(9, 1, 10, 11, 7, 12, 0); box(9, 8, 10, 11, 8, 12, 5); box(9, 9, 10, 11, 11, 12, 0);
s(10, 1, 9, 23); s(10, 2, 9, 24); s(8, 4, 11, 11); s(12, 4, 11, 11); s(10, 10, 9, 11); s(8, 10, 11, 11); s(12, 10, 11, 11);
box(10, 1, 12, 10, 9, 12, 52);
s(9, 9, 11, 68); s(11, 9, 11, 31); s(10, 11, 11, 49);
box(8, 12, 9, 12, 12, 13, 48); box(9, 13, 10, 11, 13, 12, 34); s(10, 14, 11, 6); s(10, 15, 11, 6); s(11, 15, 11, 47);
for (const [x, z] of [[5, 6], [15, 7], [6, 15], [14, 15]]) s(x, 1, z, 73);
break;
case 'rapunzel': // a tall tower with no door; the golden braid hangs from the window at the top
box(9, 0, 1, 11, 0, 6, 9);
box(8, 1, 8, 12, 18, 12, 34); box(9, 1, 9, 11, 18, 11, 0); box(9, 15, 9, 11, 15, 11, 5);
box(10, 16, 8, 10, 17, 8, 0); s(8, 17, 10, 11); s(12, 17, 10, 11);
roof(8, 8, 12, 12, 19, 46, 3); s(10, 22, 10, 6); s(10, 23, 10, 6); s(11, 23, 10, 44);
box(10, 1, 7, 10, 16, 7, 79);
s(11, 16, 11, 73); s(10, 18, 10, 49);
ring(2, 13, 7, 18, 1, 1, 4); box(3, 1, 14, 6, 1, 17, 38);
tree(16, 4, 4); tree(16, 16, 5);
break;
case 'cinder': // the little kitchen with the hearth, the hazel tree with the white bird, the palace stairs
box(9, 0, 1, 11, 0, 13, 9);
house(2, 3, 7, 9, 3, 4); s(7, 1, 6, 25); s(7, 2, 6, 26); s(2, 2, 6, 11); s(4, 2, 3, 11);
roof(2, 3, 7, 9, 4, 48, 2);
s(4, 1, 8, 20); s(5, 0, 8, 9); s(3, 0, 8, 9);
tree(14, 6, 4); s(13, 3, 6, 6); s(13, 4, 6, 80);
box(3, 1, 14, 17, 1, 19, 34); box(3, 2, 15, 17, 2, 19, 34); box(3, 3, 16, 17, 3, 19, 34);
box(3, 4, 18, 17, 8, 19, 34); for (let x = 3; x <= 17; x += 2) s(x, 9, 18, 57);
s(10, 4, 18, 23); s(10, 5, 18, 24); s(6, 6, 18, 11); s(14, 6, 18, 11); s(8, 4, 17, 22); s(12, 4, 17, 22);
s(10, 4, 16, 74);
break;
case 'hansel': // the forest path of white pebbles to the house of bread and cake
tree(4, 4, 5); tree(16, 4, 5); tree(3, 10, 4); tree(16, 9, 4); tree(4, 16, 5); tree(18, 18, 4);
for (const st of T.steps) if (st.at) s(st.at[0], st.at[1], st.at[2], 72);
house(8, 12, 16, 18, 4, 69);
for (const [x, z] of [[8, 12], [16, 12], [8, 18], [16, 18]]) box(x, 1, z, x, 4, z, 70);
s(12, 1, 12, 23); s(12, 2, 12, 24); s(10, 2, 12, 11); s(14, 2, 12, 11); s(8, 2, 15, 11); s(16, 2, 15, 11);
for (let k = 0; k < 4; k++) box(8 + k, 5 + k, 12 + k, 16 - k, 5 + k, 18 - k, k % 2 ? 70 : 71); s(12, 9, 15, 70);
s(14, 1, 16, 60); s(12, 4, 15, 49);
s(6, 1, 13, 6); s(6, 2, 13, 71); s(18, 1, 11, 6); s(18, 2, 11, 70);
break;
case 'wolf': // the goats' cottage with the tall clock, little goats hiding in and around it, the well at the back
box(9, 0, 1, 11, 0, 6, 9);
house(5, 7, 15, 15, 4, 5); for (const [x, z] of [[5, 7], [15, 7], [5, 15], [15, 15]]) box(x, 1, z, x, 4, z, 6);
s(10, 1, 7, 23); s(10, 2, 7, 24); s(7, 2, 7, 11); s(13, 2, 7, 11); s(5, 2, 11, 11); s(15, 2, 11, 11);
roof(5, 7, 15, 15, 5, 33, 4);
box(13, 1, 14, 13, 4, 14, 5); s(13, 2, 14, 84); s(13, 3, 14, 11); // the tall clock with the youngest goat inside
s(6, 1, 9, 31); s(14, 1, 10, 20); s(6, 1, 14, 35); s(10, 1, 11, 19); s(10, 4, 11, 49);
for (const [x, z] of [[7, 9], [14, 9], [7, 14], [3, 4], [18, 10], [12, 18]]) s(x, 1, z, 84);
ring(1, 16, 3, 18, 1, 1, 4); box(2, -2, 17, 2, 0, 17, 10); s(4, 1, 17, 85);
tree(17, 4, 4); tree(2, 10, 4); tree(17, 17, 4);
for (const [x, z, f] of [[3, 7, 36], [7, 3, 37], [14, 3, 36], [18, 7, 37]]) s(x, 1, z, f);
break;
case 'snow': // the dwarfs' long low cottage with seven little beds, the mountain with their mine behind it
box(9, 0, 1, 11, 0, 6, 9);
house(3, 7, 17, 13, 3, 5); for (const [x, z] of [[3, 7], [17, 7], [3, 13], [17, 13]]) box(x, 1, z, x, 3, z, 6);
s(10, 1, 7, 23); s(10, 2, 7, 24); s(6, 2, 7, 11); s(14, 2, 7, 11); s(3, 2, 10, 11); s(17, 2, 10, 11);
roof(3, 7, 17, 13, 4, 40, 3);
for (let x = 4; x <= 16; x += 2) s(x, 1, 12, 31);
s(10, 1, 10, 19); s(10, 3, 10, 49); s(5, 3, 9, 49); s(15, 3, 9, 49);
box(2, 1, 15, 18, 3, 19, 3); box(4, 4, 16, 16, 5, 19, 3); box(7, 6, 17, 13, 7, 19, 3);
box(9, 1, 15, 11, 2, 17, 0); s(10, 1, 18, 56); s(9, 2, 18, 14); s(11, 2, 18, 55); s(11, 1, 16, 22);
tree(4, 3, 4); tree(16, 3, 4);
for (const [x, z, f] of [[7, 4, 36], [13, 5, 37], [1, 6, 36], [19, 5, 37]]) s(x, 1, z, f);
break;
case 'goose': // the wood with the old tree and the golden goose in its roots, the sad princess's castle at the back
box(9, 0, 1, 11, 0, 9, 9); box(11, 0, 9, 14, 0, 9, 9); box(14, 0, 9, 14, 0, 12, 9);
s(8, 1, 6, 77);
s(4, 1, 10, 6); s(5, 1, 9, 6); s(5, 1, 11, 6); s(6, 1, 10, 86); tree(5, 10, 6);
house(10, 13, 18, 19, 6, 34); box(14, 0, 14, 14, 0, 16, 40);
s(14, 1, 13, 23); s(14, 2, 13, 24); s(12, 3, 13, 11); s(16, 3, 13, 11); s(10, 3, 16, 11); s(18, 3, 16, 11);
s(14, 1, 17, 57); s(11, 1, 14, 22); s(17, 1, 14, 22); s(14, 6, 16, 49);
box(10, 7, 13, 18, 7, 19, 34); for (let x = 10; x <= 18; x += 2) { s(x, 8, 13, 34); s(x, 8, 19, 34); }
tree(3, 3, 4); tree(17, 4, 5); tree(3, 17, 4);
for (const [x, z, f] of [[7, 8, 36], [12, 4, 37], [15, 8, 36], [7, 15, 37]]) s(x, 1, z, f);
break;
case 'shoes': // the silver, golden and diamond trees, the dark lake with a bridge, the ballroom where the princesses dance
box(9, 0, 1, 11, 0, 9, 9);
tree(4, 4, 4, 89); tree(16, 4, 4, 90); tree(4, 9, 4, 91);
box(2, -2, 10, 18, 0, 12, 10); box(10, 0, 10, 10, 0, 12, 5);
house(3, 13, 17, 19, 5, 34, 39); for (let z = 14; z <= 18; z++) for (let x = 4; x <= 16; x++) if ((x + z) % 2) s(x, 0, z, 47);
s(10, 1, 13, 23); s(10, 2, 13, 24); s(6, 3, 13, 11); s(14, 3, 13, 11); s(3, 3, 16, 11); s(17, 3, 16, 11);
roof(3, 13, 17, 19, 6, 34, 3); s(7, 5, 16, 49); s(13, 5, 16, 49);
s(10, 1, 17, 87); s(4, 1, 18, 35); s(16, 1, 18, 35);
break;
case 'thumb': // the farmer's little house with the fire, the barn full of hay, the field where the snail shell lies
box(9, 0, 1, 11, 0, 9, 9); box(11, 0, 6, 15, 0, 6, 9);
house(2, 6, 8, 11, 3, 5); for (const [x, z] of [[2, 6], [8, 6], [2, 11], [8, 11]]) box(x, 1, z, x, 3, z, 6);
s(8, 1, 8, 25); s(8, 2, 8, 26); s(4, 2, 6, 11); s(2, 2, 9, 11); s(5, 2, 11, 11);
roof(2, 6, 8, 11, 4, 33, 3);
s(3, 1, 10, 20); s(6, 1, 10, 31); s(4, 1, 7, 19); s(5, 3, 8, 49);
house(12, 7, 18, 14, 4, 40); s(15, 1, 7, 23); s(15, 2, 7, 24); s(12, 2, 10, 11); s(18, 2, 10, 11);
roof(12, 7, 18, 14, 5, 5, 4);
box(13, 1, 11, 17, 1, 13, 67); box(14, 2, 12, 17, 2, 13, 67); s(17, 3, 13, 67); s(15, 4, 9, 49);
for (let z = 14; z <= 19; z++) for (let x = 2; x <= 9; x++) if ((x * 3 + z) % 4 === 0) s(x, 1, z, 38);
s(5, 1, 17, 0); s(7, 1, 17, 0); s(6, 1, 16, 0); s(6, 1, 18, 0); s(6, 1, 17, 88);
tree(4, 3, 4); tree(16, 3, 4); tree(17, 18, 4);
for (const [x, z, f] of [[13, 17, 36], [11, 16, 37], [14, 19, 36]]) s(x, 1, z, f);
break;
default: // a later tale: one of the templates, then the tale's own quest props [x, y, z, id]
if (PLACE_TPL[T.tpl]) PLACE_TPL[T.tpl](T, { s, box, ring, house, roof, tree });
for (const [x, y, z, id] of T.props || []) s(x, y, z, id);
}
return a;
}
// the place (and place-local spot) that world (x, z) is in. Row A (z near KZ+10) faces south onto the plaza, so it is turned round.
function placeAt(x, z) {
const row = z >= KZ + 10 && z <= KZ + 30 ? 0 : z >= KZ + 96 && z <= KZ + 116 ? 1 : -1;
if (row < 0) return null;
const c = Math.floor((x + 82) / 36), x0 = -82 + 36 * c, i = SLOTS[c + ',' + row];
if (i == null || x - x0 > 20) return null;
const z0 = row ? KZ + 96 : KZ + 10, rot = !row;
return { i, x0, z0, rot, lx: rot ? x0 + 20 - x : x - x0, lz: rot ? z0 + 20 - z : z - z0 };
}
function placeWorld(i, lx, lz) { // world x, z of a place-local spot
const [c, row] = slotOf(i), x0 = -82 + 36 * c, z0 = row ? KZ + 96 : KZ + 10;
return row ? [x0 + lx, z0 + lz] : [x0 + 20 - lx, z0 + 20 - lz];
}
function taleGate(i) { // standing on the path just outside place i's gate, facing it (row A's gate is on its south side, so look north)
const [x, z] = placeWorld(i, 10, -1);
return { x: x + 0.5, y: KY + 1, z: z + 0.5, yaw: slotOf(i)[1] ? Math.PI : 0 };
}
const placeBlock = (i, lx, dy, lz) => dy < PY0 || dy >= PY0 + PH ? -1 : placeArr(i)[((dy - PY0) * PW + lz) * PW + lx];
// the land between the places: meadow, gravel paths, the round plaza with the Way Home, lamps, trees and flowers
const nearPath = (x, z, m) => (Math.abs(z - PLAZA.z) <= 1 + m && x >= KX0 + 6 && x <= KX1 - 5) ||
COLX.some(cx => Math.abs(x - cx) <= 1 + m && z >= KZ + 30 && z <= KZ + 96);
function kTreeAt(x, z) { // oak trees on a loose grid, kept off the paths, places and plaza
const gx = Math.floor(x / 10), gz = Math.floor(z / 10);
for (let a = gz - 1; a <= gz + 1; a++) for (let b = gx - 1; b <= gx + 1; b++) {
if (hash(b, 41, a, 7) > 0.55) continue;
const tx = b * 10 + 2 + Math.floor(hash(b, 42, a, 7) * 6), tz = a * 10 + 2 + Math.floor(hash(b, 43, a, 7) * 6);
if (Math.abs(x - tx) > 2 || Math.abs(z - tz) > 2) continue;
if (tx < KX0 + 4 || tx > KX1 - 4 || tz < KZ + 4 || tz > KZ1 - 4 || nearPath(tx, tz, 3) || Math.hypot(tx - PLAZA.x, tz - PLAZA.z) < 11) continue;
let clear = true;
for (let dz = -3; dz <= 3 && clear; dz += 3) for (let dx = -3; dx <= 3; dx += 3) if (placeAt(tx + dx, tz + dz)) { clear = false; break; }
if (clear) return [tx, tz];
}
return null;
}
function kingdomColumn(b, x, z, wx, wz) {
const set = (y, id) => { b[(y * CS + z) * CS + x] = id; };
set(0, 16);
if (wx < KX0 || wx > KX1 || wz < KZ || wz > KZ1) { for (let y = 1; y <= 18; y++) set(y, 3); set(19, 8); set(20, 8); for (let y = 21; y <= SEA; y++) set(y, 10); return; }
for (let y = 1; y < KY - 3; y++) set(y, 3);
for (let y = KY - 3; y < KY; y++) set(y, 2);
if (wx === KX0 || wx === KX1 || wz === KZ || wz === KZ1) { set(KY, 2); for (let y = KY + 1; y <= KY + 5; y++) set(y, 65); return; } // thorn hedge all round
const p = placeAt(wx, wz);
if (p) { const a = placeArr(p.i); for (let dy = PY0; dy < PY0 + PH; dy++) set(KY + dy, a[((dy - PY0) * PW + p.lz) * PW + p.lx]); return; }
const dx = wx - PLAZA.x, dz = wz - PLAZA.z, r2 = dx * dx + dz * dz;
if (r2 <= 56) { // the plaza: the Way Home in the middle, lamps around it
set(KY, r2 > 42 ? 54 : 34);
if (!dx && !dz) set(KY + 1, 83);
if (Math.abs(dx) === 4 && Math.abs(dz) === 4) { set(KY + 1, 4); set(KY + 2, 22); }
return;
}
if (nearPath(wx, wz, 0)) { set(KY, 9); return; }
set(KY, 1);
if ((Math.abs(wz - PLAZA.z) === 3 && ((wx % 12) + 12) % 12 === 6) || (COLX.some(cx => Math.abs(wx - cx) === 3) && wz % 12 === 6 && wz > KZ + 30 && wz < KZ + 96)) { set(KY + 1, 4); set(KY + 2, 22); return; }
const t = kTreeAt(wx, wz);
if (t) {
const ddx = Math.abs(wx - t[0]), ddz = Math.abs(wz - t[1]);
if (!ddx && !ddz) { for (let y = KY + 1; y <= KY + 4; y++) set(y, 6); set(KY + 5, 7); set(KY + 6, 7); return; }
if (!(ddx === 2 && ddz === 2)) { set(KY + 4, 7); set(KY + 3, 7); }
if (ddx <= 1 && ddz <= 1 && !(ddx && ddz)) set(KY + 5, 7);
return;
}
const r = hash(wx, 11, wz, 5);
if (r < 0.07) set(KY + 1, 38); else if (r < 0.085) set(KY + 1, 36); else if (r < 0.1) set(KY + 1, 37);
}
// every spoken line of the add-on (rendered to tales/<key>.mp3 on the PC; the page shows the same words)
const TALE_LINES = {
locked: 'This gate is still locked. Read this whole story in ABC Books, and the gate will open for you.',
done: 'You finished this quest. Well done! You can read the story again in ABC Books any time.',
welcome: 'Welcome to the Fairy Tale Kingdom! Every story has its own place. Tap a story stone to hear its story. Read a story in ABC Books, and its gate opens for you.',
};
function taleClips() {
const l = Object.keys(TALE_LINES).map(k => ({ key: k, text: TALE_LINES[k] }));
for (const T of TALES) {
l.push({ key: T.id + '-sum', text: T.sum }, { key: T.id + '-quest', text: T.quest }, { key: T.id + '-win', text: T.win });
T.steps.forEach((st, k) => {
l.push({ key: T.id + '-h' + k, text: st.hint });
if (Array.isArray(st.say)) st.say.forEach((w, j) => l.push({ key: T.id + '-s' + k + '-' + j, text: w }));
else l.push({ key: T.id + '-s' + k, text: st.say });
});
}
return l;
}
// the page sets this: (x, z) => true when this player may walk through the story gate at (x, z)
let gateOpen = null;
const setGateOpen = f => { gateOpen = f; };
class Chunk {
constructor(cx, cz) {
this.cx = cx; this.cz = cz; this.b = new Uint8Array(CS * CS * CH); this.hm = new Uint8Array(CS * CS);
this.torches = []; this.mesh = null; this.dirty = true; this.map = null;
}
static idx(x, y, z) { return (y * CS + z) * CS + x; }
get(x, y, z) { return this.b[(y * CS + z) * CS + x]; }
updateColumn(x, z) {
let y = CH - 1;
while (y > 0 && !isOpaque[this.b[(y * CS + z) * CS + x]]) y--;
this.hm[z * CS + x] = y;
}
rebuildMeta() {
this.torches.length = 0;
for (let z = 0; z < CS; z++) for (let x = 0; x < CS; x++) this.updateColumn(x, z);
for (let i = 0; i < this.b.length; i++) if (BLOCKS[this.b[i]] && BLOCKS[this.b[i]].light) {
const x = i % CS, z = ((i / CS) | 0) % CS, y = (i / (CS * CS)) | 0;
this.torches.push(this.cx * CS + x, y, this.cz * CS + z);
}
}
}
function generateChunk(cx, cz, seed) {
const c = new Chunk(cx, cz), b = c.b, X0 = cx * CS, Z0 = cz * CS;
if (inDungeon(X0)) {
for (let y = 0; y < CH; y++) for (let z = 0; z < CS; z++) for (let x = 0; x < CS; x++) b[(y * CS + z) * CS + x] = dungeonBlock(X0 + x, y, Z0 + z, seed);
return c;
}
if (inKingdom(Z0)) {
for (let z = 0; z < CS; z++) for (let x = 0; x < CS; x++) kingdomColumn(b, x, z, X0 + x, Z0 + z);
return c;
}
const P = 3, W = CS + P * 2;
const hts = new Int16Array(W * W), bio = new Uint8Array(W * W);
for (let z = 0; z < W; z++) for (let x = 0; x < W; x++) {
hts[z * W + x] = heightAt(X0 + x - P, Z0 + z - P, seed);
bio[z * W + x] = biomeAt(X0 + x - P, Z0 + z - P, seed);
}
const set = (x, y, z, id) => { if (x >= 0 && x < CS && z >= 0 && z < CS && y > 0 && y < CH) b[(y * CS + z) * CS + x] = id; };
for (let z = 0; z < CS; z++) for (let x = 0; x < CS; x++) {
const wx = X0 + x, wz = Z0 + z, h = hts[(z + P) * W + x + P], bm = bio[(z + P) * W + x + P];
const beach = h <= SEA + 1 && bm !== 3;
for (let y = 0; y <= Math.max(h, SEA); y++) {
let id = 0;
if (y === 0) id = 16;
else if (y < h - 3) id = 3;
else if (y < h) id = (bm === 2 || beach) ? (y < h - 2 && bm === 2 ? 50 : 8) : 2;
else if (y === h) id = h < SEA ? (hash(wx, 3, wz, seed) < 0.3 ? 9 : 8) : (bm === 2 || beach) ? 8 : bm === 3 ? 17 : 1;
else if (y <= SEA) id = 10;
if (id === 3) {
const r = hash(wx, y, wz, seed + 9), cl = hash(wx >> 1, y >> 1, wz >> 1, seed + 10);
if (y < 16 && r < 0.01 && cl < 0.55) id = 15;
else if (y < 22 && r < 0.008 && cl < 0.5) id = 14;
else if (y < 44 && r < 0.02 && cl < 0.55) id = 13;
else if (r < 0.035 && cl < 0.6) id = 12;
else if (y < 30 && r < 0.043 && cl < 0.55) id = 55;
else if (y < 14 && r < 0.048 && cl < 0.6) id = 56;
}
if (id) b[(y * CS + z) * CS + x] = id;
}
// caves: two crossing noise "tubes"
for (let y = 2; y < h - 3; y++) {
const n1 = noise3(wx / 18, y / 11, wz / 18, seed + 300), n2 = noise3(wx / 18, y / 11, wz / 18, seed + 400);
if (Math.abs(n1 - 0.5) < 0.055 && Math.abs(n2 - 0.5) < 0.09) {
const i = (y * CS + z) * CS + x; if (b[i] !== 16) b[i] = 0;
}
}
// plants
const top = b[(h * CS + z) * CS + x];
if (h > SEA && b[((h + 1) * CS + z) * CS + x] === 0) {
const r = hash(wx, 11, wz, seed);
if (top === 1) {
if (r < 0.08) b[((h + 1) * CS + z) * CS + x] = 38;
else if (r < 0.088) b[((h + 1) * CS + z) * CS + x] = 36;
else if (r < 0.096) b[((h + 1) * CS + z) * CS + x] = 37;
} else if (top === 8 && bm === 2 && r < 0.006) {
const ch = 1 + Math.floor(hash(wx, 12, wz, seed) * 3);
for (let k = 1; k <= ch; k++) b[((h + k) * CS + z) * CS + x] = 18;
}
}
}
// trees can hang over chunk borders, so look a little outside
for (let z = -P; z < CS + P; z++) for (let x = -P; x < CS + P; x++) {
const h = hts[(z + P) * W + x + P], bm = bio[(z + P) * W + x + P];
const th = treeAt(X0 + x, Z0 + z, seed, bm, h);
if (!th) continue;
if (x >= 0 && x < CS && z >= 0 && z < CS) { const tp = b[(h * CS + z) * CS + x]; if (tp !== 1 && tp !== 17) continue; }
for (let y = h + th - 2; y <= h + th + 1; y++) {
const r = y > h + th - 1 ? 1 : 2;
for (let dz = -r; dz <= r; dz++) for (let dx = -r; dx <= r; dx++) {
if (Math.abs(dx) === r && Math.abs(dz) === r && (r === 1 || hash(X0 + x + dx, y, Z0 + z + dz, seed) < 0.5)) continue;
const lx = x + dx, lz = z + dz;
if (lx >= 0 && lx < CS && lz >= 0 && lz < CS && y < CH && b[(y * CS + lz) * CS + lx] === 0) set(lx, y, lz, 7);
}
}
for (let k = 1; k <= th; k++) set(x, h + k, z, 6);
}
// castles that reach into this chunk
for (let rz = Math.floor((Z0 - CW) / REG); rz <= Math.floor((Z0 + CS) / REG); rz++)
for (let rx = Math.floor((X0 - CW) / REG); rx <= Math.floor((X0 + CS) / REG); rx++) {
const cs = castleAt(rx, rz, seed);
if (!cs || cs.x0 >= X0 + CS || cs.x0 + CW <= X0 || cs.z0 >= Z0 + CS || cs.z0 + CW <= Z0) continue;
for (let z = Math.max(0, cs.z0 - Z0); z < Math.min(CS, cs.z0 + CW - Z0); z++)
for (let x = Math.max(0, cs.x0 - X0); x < Math.min(CS, cs.x0 + CW - X0); x++)
for (let y = Math.max(1, cs.base - 6); y < Math.min(CH, cs.base + 17); y++) {
const id = castleBlock(cs, X0 + x - cs.x0, y, Z0 + z - cs.z0);
if (id >= 0) b[(y * CS + z) * CS + x] = id;
}
}
return c;
}
// ---------------------------------------------------------------- world
const key = (cx, cz) => cx + ',' + cz;
class World {
constructor(seed) { this.seed = seed | 0; this.chunks = new Map(); this.edits = new Map(); this.onChange = null; }
chunk(cx, cz, make) {
const k = key(cx, cz); let c = this.chunks.get(k);
if (!c && make) {
c = generateChunk(cx, cz, this.seed);
const e = this.edits.get(k);
if (e) e.forEach((id, i) => { c.b[i] = id; });
c.rebuildMeta(); this.chunks.set(k, c);
}
return c;
}
get(x, y, z) {
if (y < 0) return 16; if (y >= CH) return 0;
const c = this.chunk(Math.floor(x / CS), Math.floor(z / CS), true);
return c.b[(y * CS + (z - c.cz * CS)) * CS + (x - c.cx * CS)];
}
peek(x, y, z) { // like get, but never generates (0 when not loaded)
if (y < 0) return 16; if (y >= CH) return 0;
const c = this.chunks.get(key(Math.floor(x / CS), Math.floor(z / CS)));
return c ? c.b[(y * CS + (z - c.cz * CS)) * CS + (x - c.cx * CS)] : 0;
}
set(x, y, z, id) {
if (y < 1 || y >= CH) return false;
const cx = Math.floor(x / CS), cz = Math.floor(z / CS), c = this.chunk(cx, cz, true);
const lx = x - cx * CS, lz = z - cz * CS, i = Chunk.idx(lx, y, lz), old = c.b[i];
if (old === id) return false;
c.b[i] = id;
const k = key(cx, cz); let e = this.edits.get(k); if (!e) { e = new Map(); this.edits.set(k, e); }
e.set(i, id);
c.updateColumn(lx, lz);
if (blk(old).light || blk(id).light) c.rebuildMeta();
c.dirty = true;
if (this.onChange) this.onChange(x, y, z, old, id);
return true;
}
topY(x, z) { // highest solid block in a column
for (let y = CH - 1; y > 0; y--) if (isSolid[this.get(x, y, z)]) return y;
return 0;
}
skyAt(x, y, z) { // 1 in open air, falling off with depth below the sky line
const c = this.chunks.get(key(Math.floor(x / CS), Math.floor(z / CS)));
if (!c) return 1;
const d = c.hm[(z - c.cz * CS) * CS + (x - c.cx * CS)] - y;
return d < 0 ? 1 : Math.max(0.04, 0.85 - d * 0.14);
}
torchLightAt(x, y, z) {
let best = 0;
const cx = Math.floor(x / CS), cz = Math.floor(z / CS);
for (let dz = -1; dz <= 1; dz++) for (let dx = -1; dx <= 1; dx++) {
const c = this.chunks.get(key(cx + dx, cz + dz)); if (!c) continue;
const ts = c.torches;
for (let i = 0; i < ts.length; i += 3) {
const ddx = ts[i] + 0.5 - x, ddy = ts[i + 1] + 0.5 - y, ddz = ts[i + 2] + 0.5 - z;
const l = 1 - Math.sqrt(ddx * ddx + ddy * ddy + ddz * ddz) / 8;
if (l > best) best = l;
}
}
return best;
}
encodeEdits() {
const o = {};
this.edits.forEach((m, k) => { const a = []; m.forEach((id, i) => a.push(i.toString(36) + '.' + id.toString(36))); if (a.length) o[k] = a.join(','); });
return o;
}
decodeEdits(o) {
this.edits.clear();
for (const k in o) {
const m = new Map();
o[k].split(',').forEach(p => { const s = p.split('.'); if (s.length === 2) m.set(parseInt(s[0], 36), parseInt(s[1], 36)); });
this.edits.set(k, m);
}
}
}
// ---------------------------------------------------------------- physics
function blockBox(id) { // [y0, y1] of the collision box, or null
if (!isSolid[id]) return null;
const d = BLOCKS[id];
return d.h < 1 ? d.h : 1;
}
function boxHits(world, x0, y0, z0, x1, y1, z1) {
for (let y = Math.floor(y0); y <= Math.floor(y1 - 1e-6); y++)
for (let z = Math.floor(z0); z <= Math.floor(z1 - 1e-6); z++)
for (let x = Math.floor(x0); x <= Math.floor(x1 - 1e-6); x++) {
const id = world.get(x, y, z), h = id === 64 && gateOpen && gateOpen(x, z) ? null : blockBox(id); // an open story gate
if (h !== null && y + h > y0 + 1e-6) return true;
}
return false;
}
// b: {x,y,z (feet centre), vx,vy,vz, w, h}; sets b.onGround / b.hitWall / b.inWater
function moveBody(world, b, dt, canStep) {
const hw = b.w / 2;
b.hitWall = false;
const feetBlock = world.get(Math.floor(b.x), Math.floor(b.y + 0.2), Math.floor(b.z));
const midBlock = world.get(Math.floor(b.x), Math.floor(b.y + b.h * 0.6), Math.floor(b.z));
b.inWater = feetBlock === 10 || midBlock === 10;
b.onLadder = blk(feetBlock).shape === 'ladder' || blk(midBlock).shape === 'ladder';
const steps = Math.max(1, Math.ceil(Math.max(Math.abs(b.vx), Math.abs(b.vy), Math.abs(b.vz)) * dt / 0.4));
const sdt = dt / steps;
let ground = false;
for (let s = 0; s < steps; s++) {
// y
const ny = b.y + b.vy * sdt;
if (b.vy !== 0 && boxHits(world, b.x - hw, ny, b.z - hw, b.x + hw, ny + b.h, b.z + hw)) {
const x0 = Math.floor(b.x - hw), x1 = Math.floor(b.x + hw - 1e-6), z0 = Math.floor(b.z - hw), z1 = Math.floor(b.z + hw - 1e-6);
if (b.vy < 0) { // land on the highest top below our feet
let top = ny;
for (let yy = Math.floor(ny); yy <= Math.floor(b.y + 0.01); yy++)
for (let zz = z0; zz <= z1; zz++) for (let xx = x0; xx <= x1; xx++) {
const id = world.get(xx, yy, zz), h = id === 64 && gateOpen && gateOpen(xx, zz) ? null : blockBox(id);
if (h !== null && yy + h <= b.y + 0.01 && yy + h > top) top = yy + h;
}
b.y = top; ground = true;
} else { // bump the head
let bottom = ny + b.h;
for (let yy = Math.floor(b.y + b.h - 0.01); yy <= Math.floor(ny + b.h); yy++)
for (let zz = z0; zz <= z1; zz++) for (let xx = x0; xx <= x1; xx++)
if (blockBox(world.get(xx, yy, zz)) !== null && !(world.get(xx, yy, zz) === 64 && gateOpen && gateOpen(xx, zz)) && yy >= b.y + b.h - 0.01 && yy < bottom) bottom = yy;
b.y = bottom - b.h;
}
b.vy = 0;
} else b.y = ny;
// x then z (with step-up for slabs, beds and other half blocks)
for (const ax of ['x', 'z']) {
const v = ax === 'x' ? b.vx : b.vz; if (!v) continue;
const nx = ax === 'x' ? b.x + v * sdt : b.x, nz = ax === 'z' ? b.z + v * sdt : b.z;
if (boxHits(world, nx - hw, b.y, nz - hw, nx + hw, b.y + b.h, nz + hw)) {
if (canStep && (ground || b.onGround) && !boxHits(world, nx - hw, b.y + 0.55, nz - hw, nx + hw, b.y + 0.55 + b.h, nz + hw)) {
// find the exact step height
let sy = b.y + 0.55;
while (sy - 0.05 > b.y && !boxHits(world, nx - hw, sy - 0.05, nz - hw, nx + hw, sy - 0.05 + b.h, nz + hw)) sy -= 0.05;
b.y = sy; b.x = nx; b.z = nz;
} else {
b.hitWall = true;
if (ax === 'x') b.vx = 0; else b.vz = 0;
}
} else { b.x = nx; b.z = nz; }
}
}
b.onGround = ground || (b.vy <= 0 && boxHits(world, b.x - hw, b.y - 0.05, b.z - hw, b.x + hw, b.y, b.z + hw));
}
// DDA ray through blocks. Returns {x,y,z, nx,ny,nz, id, d} of the first targetable block.
function raycast(world, ox, oy, oz, dx, dy, dz, maxD, hitWater) {
let x = Math.floor(ox), y = Math.floor(oy), z = Math.floor(oz);
const sx = dx > 0 ? 1 : -1, sy = dy > 0 ? 1 : -1, sz = dz > 0 ? 1 : -1;
const tdx = Math.abs(1 / dx), tdy = Math.abs(1 / dy), tdz = Math.abs(1 / dz);
let tx = (dx > 0 ? x + 1 - ox : ox - x) * tdx, ty = (dy > 0 ? y + 1 - oy : oy - y) * tdy, tz = (dz > 0 ? z + 1 - oz : oz - z) * tdz;
let nx = 0, ny = 0, nz = 0, d = 0;
for (let i = 0; i < 64 && d <= maxD; i++) {
const id = world.peek(x, y, z);
if (id && (id !== 10 || hitWater)) {
const def = BLOCKS[id];
let ok = true;
if (def.shape === 'slab' || def.shape === 'bed') { // only the lower part is there
const hy = oy + dy * d - y;
if (hy > def.h + 0.01 && dy >= 0) ok = false;
}
if (ok) return { x, y, z, nx, ny, nz, id, d };
}
if (tx < ty && tx < tz) { x += sx; d = tx; tx += tdx; nx = -sx; ny = 0; nz = 0; }
else if (ty < tz) { y += sy; d = ty; ty += tdy; nx = 0; ny = -sy; nz = 0; }
else { z += sz; d = tz; tz += tdz; nx = 0; ny = 0; nz = -sz; }
}
return null;
}
function rayBox(ox, oy, oz, dx, dy, dz, x0, y0, z0, x1, y1, z1) {
let tmin = 0, tmax = 1e9;
const o = [ox, oy, oz], d = [dx, dy, dz], lo = [x0, y0, z0], hi = [x1, y1, z1];
for (let i = 0; i < 3; i++) {
if (Math.abs(d[i]) < 1e-9) { if (o[i] < lo[i] || o[i] > hi[i]) return -1; continue; }
let a = (lo[i] - o[i]) / d[i], b = (hi[i] - o[i]) / d[i];
if (a > b) { const tt = a; a = b; b = tt; }
tmin = Math.max(tmin, a); tmax = Math.min(tmax, b);
if (tmin > tmax) return -1;
}
return tmin;
}
// ---------------------------------------------------------------- mobs
const MOBS = {
zombie: { hp: 20, w: 0.6, h: 1.9, speed: 1.9, hostile: true, burns: true, drops: [[110, 0, 2]] },
skeleton: { hp: 20, w: 0.6, h: 1.9, speed: 1.6, hostile: true, burns: true, drops: [[111, 0, 2], [112, 0, 2]] },
creeper: { hp: 20, w: 0.6, h: 1.7, speed: 1.7, hostile: true, drops: [[113, 0, 2]] },
spider: { hp: 16, w: 1.3, h: 0.9, speed: 2.8, hostile: true, drops: [[116, 0, 2]] },
pig: { hp: 10, w: 0.9, h: 0.9, speed: 1.2, drops: [[106, 1, 3]] },
cow: { hp: 10, w: 0.9, h: 1.4, speed: 1.1, drops: [[108, 1, 3], [114, 0, 2]] },
sheep: { hp: 8, w: 0.9, h: 1.3, speed: 1.1, drops: [[39, 1, 1]] },
trex: { hp: 60, w: 1.6, h: 3.0, speed: 3.0, hostile: true, dino: true, dmg: 6, reach: 2.2, drops: [[140, 2, 5], [142, 1, 2]] },
raptor: { hp: 16, w: 0.7, h: 1.3, speed: 4.0, hostile: true, dino: true, dmg: 2, drops: [[140, 1, 2]] },
trike: { hp: 30, w: 1.4, h: 1.9, speed: 1.2, dino: true, charges: true, dmg: 4, reach: 1.8, drops: [[140, 2, 4], [114, 1, 2]] },
brachio: { hp: 50, w: 2.0, h: 5.3, speed: 0.9, dino: true, drops: [[140, 3, 6]] },
// pets: follow their owner, fight monsters near them, can't be hurt
cat: { hp: 1, w: 0.5, h: 0.6, speed: 5, pet: true, drops: [] },
dog: { hp: 1, w: 0.6, h: 0.85, speed: 5, pet: true, drops: [] },
babydino: { hp: 1, w: 0.6, h: 1.0, speed: 5, pet: true, base: 'trex', scale: 0.35, drops: [] },
// dungeon floor bosses: a big version of a monster (base = how it looks and fights)
zking: { name: 'THE ZOMBIE KING', hp: 80, w: 1.1, h: 3.4, speed: 2.2, hostile: true, boss: true, base: 'zombie', scale: 1.8, dmg: 5, reach: 2.4, drops: [[104, 2, 4], [102, 4, 8]] },
squeen: { name: 'THE SPIDER QUEEN', hp: 100, w: 2.8, h: 1.9, speed: 3.2, hostile: true, boss: true, base: 'spider', scale: 2.2, dmg: 4, reach: 2.6, drops: [[104, 3, 5], [116, 6, 12]] },
slord: { name: 'THE SKELETON LORD', hp: 110, w: 1.0, h: 3.2, speed: 1.8, hostile: true, boss: true, base: 'skeleton', scale: 1.7, dmg: 4, drops: [[104, 3, 6], [112, 10, 20]] },
ralpha: { name: 'THE RAPTOR ALPHA', hp: 120, w: 1.3, h: 2.5, speed: 4.6, hostile: true, boss: true, dino: true, base: 'raptor', scale: 1.9, dmg: 5, reach: 2.2, drops: [[104, 4, 7], [140, 4, 8]] },
dlord: { name: 'THE DINO OVERLORD', hp: 220, w: 2.4, h: 4.5, speed: 3.2, hostile: true, boss: true, dino: true, base: 'trex', scale: 1.5, dmg: 8, reach: 3.2, drops: [[104, 6, 10], [142, 2, 4]] },
// pets + play add-on: wild white wolves in the snowy lands (feed one 3 times to tame it), and the tame pet
wolf: { hp: 14, w: 0.6, h: 0.9, speed: 1.6, drops: [] },
whitewolf: { hp: 1, w: 0.6, h: 0.9, speed: 5.5, pet: true, base: 'wolf', scale: 1.1, drops: [] },
};
const PET_NAMES = { cat: 'Whiskers', dog: 'Buddy', babydino: 'Chomper', whitewolf: 'Snowy' };
const PET_KINDS = { cat: 'cat', dog: 'dog', babydino: 'baby dino', whitewolf: 'white wolf' };
// pets get hungry while their owner plays (never while they are away or on a break): full to empty in 40 minutes of play.
// Pet Food fills 40. Five feedings of a pet that was not full earn room for one more pet, up to 4. A pet left empty dies.
const PET_HUNGER = 100 / (40 * 60), MAX_PETS = 4, FEEDS_PER_SLOT = 5;
const BOSSES = ['zking', 'squeen', 'slord', 'ralpha', 'dlord'];
const MOB_TYPES = Object.keys(MOBS);
// ---------------------------------------------------------------- vehicles
// Placed from the Airplane / Helicopter items. The rider's page flies it and reports where it is;
// the sim only keeps the list, who is riding, and lets an empty one settle onto the ground.
// w/h: collision box while flying; bw/bh: the box you tap to get in.
const VEHICLES = {
plane: { item: 144, w: 1.2, h: 1.2, bw: 3.6, bh: 1.8, plane: true, max: 20, name: 'Airplane' },
heli: { item: 145, w: 1.4, h: 1.6, bw: 2.4, bh: 2.4, name: 'Helicopter' },
// jets: found parked on airfields out in the world (the first to climb in keeps it); they fly like the airplane, only faster
jet: { item: 224, w: 1.2, h: 1.2, bw: 4.0, bh: 1.8, plane: true, max: 32, name: 'Fighter Jet' },
stunt: { item: 225, w: 1.2, h: 1.2, bw: 3.4, bh: 1.8, plane: true, max: 28, name: 'Stunt Jet', turn: 1.6 },
spy: { item: 226, w: 1.2, h: 1.2, bw: 4.4, bh: 1.6, plane: true, max: 40, name: 'Spy Jet' },
};
const VEH_TYPES = Object.keys(VEHICLES);
// each player's colour, picked from their name: index into the page's 8 paint colours, and the matching wool for flags
const paintOf = owner => { if (!owner) return 0; const s = owner.toLowerCase(); let h = 2166136261; for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return (h >>> 0) % 8; };
const PAINT_WOOL = [40, 44, 43, 45, 42, 41, 47, 39];
const fin = v => typeof v === 'number' && isFinite(v);
const dayLight = time => { const s = Math.sin(time * Math.PI * 2); return Math.max(0.12, Math.min(1, 0.55 + s * 1.6)); };
// ---------------------------------------------------------------- simulation
// One Sim per world. `send(msg, playerId|null)` delivers messages (null = everyone).
class Sim {
constructor(opts) {
this.world = new World(opts.seed);
this.diff = opts.difficulty || 'normal'; // peaceful | easy | normal
this.time = opts.time != null ? opts.time : 0.02;
this.players = new Map(); this.mobs = new Map(); this.arrows = []; this.tnts = [];
this.chests = opts.chests || {};
this.nextId = 1; this.send = opts.send || (() => {}); this.spawnTimer = 0; this.snapTimer = 0;
this.rand = Math.random;
this.pendingBlocks = [];
this.world.onChange = (x, y, z, old, id) => this.pendingBlocks.push(x, y, z, id);
this.vehicles = new Map();
for (const v of opts.vehicles || []) if (VEHICLES[v.kind]) this.addVehicle(v.kind, v.x, v.y, v.z, v.yaw, v.owner);
this.owned = opts.owned || []; // castles built from kits: { x0, z0, base, type, owner }
this.dungeon = Object.assign({ entrance: null, unlocked: {}, lastKill: {} }, opts.dungeon || {});
this.petData = opts.pets || {}; // lower-case owner name -> { kind, name, lvl, xp }
this.kingdom = Object.assign({ gate: null }, opts.kingdom || {}); // gate: bottom middle block of the Story Book arch
}
// the way to the Fairy Tale Kingdom: an arch of bookshelves with a gold top and a glowing story book portal, the other
// side of the spawn from the dungeon shrine (built once, rebuilt if the portal goes missing)
ensureKingdomGate(spawn) {
const W = this.world, old = this.kingdom.gate;
if (old && W.get(old.x, old.y, old.z) === 82) return;
// first time: a spot near spawn that is not inside a castle, standing on the natural ground (not on a wall or a treetop)
const sx = Math.floor(spawn.x), sz = Math.floor(spawn.z), seed = W.seed;
const inCastle = (x, z) => { for (let a = -1; a <= 1; a++) for (let b = -1; b <= 1; b++) { const c = castleAt(Math.floor(x / REG) + a, Math.floor(z / REG) + b, seed); if (c && x > c.x0 - 6 && x < c.x0 + CW + 6 && z > c.z0 - 6 && z < c.z0 + CW + 6) return true; } return false; };
const spot = [[-7, 7], [-7, -7], [7, -7], [-14, 7], [-14, -7], [-7, 14], [-21, 0], [0, -21]].find(([dx, dz]) => !inCastle(sx + dx, sz + dz)) || [-7, 7];
const gx = old ? old.x : sx + spot[0], gz = old ? old.z : sz + spot[1];
const gy = old ? old.y - 1 : Math.max(heightAt(gx, gz, seed), SEA);
for (let dz = -5; dz <= 5; dz++) for (let dx = -5; dx <= 5; dx++) for (let y = gy + 1; y <= gy + 9; y++) // trees and plants out of the way
if ([6, 7, 18, 36, 37, 38].includes(W.get(gx + dx, y, gz + dz))) W.set(gx + dx, y, gz + dz, 0);
for (let dz = -2; dz <= 2; dz++) for (let dx = -3; dx <= 3; dx++) {
for (let y = gy - 1; y <= gy; y++) W.set(gx + dx, y, gz + dz, 5); // wooden platform
for (let y = gy + 1; y <= gy + 6; y++) W.set(gx + dx, y, gz + dz, 0);
}
for (let y = gy + 1; y <= gy + 4; y++) { W.set(gx - 2, y, gz, 35); W.set(gx + 2, y, gz, 35); } // bookshelf pillars
for (let dx = -2; dx <= 2; dx++) W.set(gx + dx, gy + 5, gz, 57);
for (let dx = -1; dx <= 1; dx++) for (let y = gy + 1; y <= gy + 4; y++) W.set(gx + dx, y, gz, 82);
W.set(gx - 3, gy + 1, gz + 1, 22); W.set(gx + 3, gy + 1, gz + 1, 22);
this.kingdom.gate = { x: gx, y: gy + 1, z: gz };
}
// the dungeon entrance: a small mossy shrine with the glowing stairwell, a few steps from the world spawn (built once)
ensureEntrance(spawn) {
const W = this.world, old = this.dungeon.entrance;
if (old && W.get(old.x, old.y, old.z) === 61) return;
// first time: build next to spawn; if the stairs went missing (old TNT bug), rebuild in the same spot
const ex = old ? old.x : Math.floor(spawn.x) + 7, ez = old ? old.z : Math.floor(spawn.z) + 7;
let gy = old ? old.y : W.topY(ex, ez);
if (!old) while (gy > 2 && [6, 7, 18].includes(W.get(ex, gy, ez))) gy--;
for (let dz = -3; dz <= 3; dz++) for (let dx = -3; dx <= 3; dx++) {
const x = ex + dx, z = ez + dz, edge = Math.abs(dx) === 3 || Math.abs(dz) === 3, corner = Math.abs(dx) === 3 && Math.abs(dz) === 3;
for (let y = gy - 2; y <= gy; y++) W.set(x, y, z, 54); // platform
for (let y = gy + 1; y <= gy + 6; y++) {
let id = 0;
if (corner && y <= gy + 4) id = 34; // pillars
else if (y === gy + 5 && edge) id = 48; // roof rim
else if (y === gy + 5 && dx === 0 && dz === 0) id = 49; // light
W.set(x, y, z, id);
}
}
W.set(ex, gy, ez, 61);
W.set(ex - 2, gy + 1, ez - 2, 22); W.set(ex + 2, gy + 1, ez - 2, 22); W.set(ex - 2, gy + 1, ez + 2, 22); W.set(ex + 2, gy + 1, ez + 2, 22);
this.dungeon.entrance = { x: ex, y: gy, z: ez };
}
// ---- pets
// petData[lower-case name] = { pets: [{ kind, name, lvl, xp, food }], slots, fed }. Older saves had one pet { kind, name, lvl, xp }.
petsOf(name, make) {
const k = String(name).toLowerCase(); let pd = this.petData[k];
if (pd && pd.kind) pd = this.petData[k] = { pets: [Object.assign({ food: 100 }, pd)], slots: 1, fed: 0 };
if (!pd && make) pd = this.petData[k] = { pets: [], slots: 1, fed: 0 };
return pd || null;
}
spawnPet(pid) { // (re)spawns all of this player's pets
const p = this.players.get(pid); if (!p) return;
for (const m of [...this.mobs.values()]) if (m.owner === pid) this.mobs.delete(m.id);
const pd = this.petsOf(p.name); if (!pd) return;
pd.pets.forEach((pt, i) => {
if (!MOBS[pt.kind]) return;
const m = this.spawnMob(pt.kind, p.x + 1 + i * 0.6, p.y + 0.5, p.z + 1);
m.owner = pid; m.petIdx = i; m.petName = pt.name; m.lvl = pt.lvl || 1;
});
}
petOf(pid) { for (const m of this.mobs.values()) if (m.owner === pid) return m; return null; }
petsOut(pid) { return [...this.mobs.values()].filter(m => m.owner === pid); }
petNews(pid, extra) { const p = this.players.get(pid); if (p) this.send(Object.assign({ t: 'petinfo', pets: this.petsOf(p.name) }, extra || {}), pid); }
addPet(pid, kind) { // '' when it worked, else why not
const p = this.players.get(pid), pd = this.petsOf(p.name, true);
if (pd.pets.length >= pd.slots) return pd.slots >= MAX_PETS ? 'You already have ' + MAX_PETS + ' pets, the most you can have.'
: 'You have room for ' + pd.slots + (pd.slots === 1 ? ' pet' : ' pets') + '. Feed your pets Pet Food to earn room for another!';
const n = pd.pets.filter(q => q.kind === kind).length;
pd.pets.push({ kind, name: PET_NAMES[kind] + (n ? ' ' + (n + 1) : ''), lvl: 1, xp: 0, food: 100 });
this.spawnPet(pid); this.petNews(pid, { got: pd.pets.length - 1 });
return '';
}
feedPet(pid, amount, all) { // Pet Food feeds the hungriest pet; a Heart cheers up all of them
const p = this.players.get(pid), pd = p && this.petsOf(p.name);
if (!pd || !pd.pets.length) return false;
const list = all ? pd.pets : [pd.pets.reduce((a, b) => (b.food < a.food ? b : a))];
for (const pt of list) {
if (pt.food < 80) pd.fed = (pd.fed || 0) + 1; // feeding a pet that was really hungry-ish counts toward room for one more
pt.food = Math.min(100, pt.food + amount); pt.warned = 0;
}
let roomMsg = '';
if (pd.slots < MAX_PETS && pd.fed >= FEEDS_PER_SLOT) { pd.fed = 0; pd.slots++; roomMsg = 'Your pets are happy! You earned room for ' + pd.slots + ' pets.'; }
this.petNews(pid, { fed: list.map(q => q.name).join(' and '), room: roomMsg });
return true;
}
tickPetFood(dt) { // only for players who are here: pets never get hungry while their owner is away or on a break
for (const p of this.players.values()) {
const pd = this.petsOf(p.name); if (!pd || !pd.pets.length) continue;
for (const pt of [...pd.pets]) {
const before = pt.food == null ? 100 : pt.food; pt.food = Math.max(0, before - PET_HUNGER * dt);
if (pt.food <= 50 && before > 50) this.send({ t: 'petwarn', name: pt.name, level: 1 }, p.id);
else if (pt.food <= 20 && before > 20) this.send({ t: 'petwarn', name: pt.name, level: 2 }, p.id);
else if (pt.food <= 0) {
pd.pets.splice(pd.pets.indexOf(pt), 1);
this.send({ t: 'petwarn', name: pt.name, level: 3 }, p.id);
this.send({ t: 'msg', text: p.name + "'s pet " + pt.name + ' was too hungry and died.' }, null);
this.spawnPet(p.id); this.petNews(p.id);
}
}
}
}
// ---- airfields (pets + play add-on): three runways out in the world with jets parked on them, built once like the dungeon
// shrine (saved as block changes; the list lives in this.dungeon.air so it is saved with the dungeon). The first player to
// climb into a parked jet keeps it; an empty airfield gets a new jet after a while.
ensureAirfields(spawn) {
const W = this.world, d = this.dungeon;
if (d.air && d.air.length) { this.parkJets(); return; }
d.air = [];
const a0 = hash(this.world.seed, 7, 7, 91) * Math.PI * 2;
// never on top of anything a player built: skip land whose chunks (plus a margin) have block changes, or near owned builds
const untouched = (cx, cz) => {
for (let kz = Math.floor((cz - 12) / CS); kz <= Math.floor((cz + 12) / CS); kz++)
for (let kx = Math.floor((cx - 28) / CS); kx <= Math.floor((cx + 28) / CS); kx++) { const e = W.edits.get(key(kx, kz)); if (e && e.size) return false; }
for (const c of this.owned) if (Math.abs(c.x0 + CW / 2 - cx) < 50 && Math.abs(c.z0 + CW / 2 - cz) < 40) return false;
return true;
};
for (let i = 0; i < 3; i++) {
const a = a0 + i * Math.PI * 2 / 3;
let cx = 0, cz = 0, ok = false;
for (let r = 90 + i * 35; r < 600 && !ok; r += 30) {
cx = Math.floor(spawn.x + Math.cos(a) * r); cz = Math.floor(spawn.z + Math.sin(a) * r);
ok = !inKingdom(cz) && !inDungeon(cx) && untouched(cx, cz);
}
if (!ok) continue;
let gy = W.topY(cx, cz); while (gy > 2 && [6, 7, 18].includes(W.get(cx, gy, cz))) gy--;
if (gy < SEA || gy > CH - 14) gy = SEA + 2;
// a 9 x 41 runway along x: grey stone bricks, a yellow middle line, lights along the sides, cleared air above
for (let dz = -4; dz <= 4; dz++) for (let dx = -20; dx <= 20; dx++) {
const x = cx + dx, z = cz + dz, side = Math.abs(dz) === 4;
for (let y = gy - 3; y < gy; y++) if (!isSolid[W.get(x, y, z)]) W.set(x, y, z, 4);
W.set(x, gy, z, side ? 4 : dz === 0 && dx % 4 !== 0 ? 42 : 34);
for (let y = gy + 1; y <= gy + 10 && y < CH; y++) W.set(x, y, z, side && y === gy + 1 && dx % 5 === 0 ? 49 : 0);
}
d.air.push({ x: cx, y: gy, z: cz });
}
this.parkJets(true);
}
parkJets(first) {
const kinds = ['jet', 'stunt', 'spy'];
(this.dungeon.air || []).forEach((f, i) => {
let parked = 0;
for (const v of this.vehicles.values()) if (!v.owner && Math.abs(v.x - f.x) < 22 && Math.abs(v.z - f.z) < 6) parked++;
const want = first ? 2 : 1;
for (let n = parked; n < want; n++) {
const kind = kinds[(i + n + (first ? 0 : Math.floor(this.rand() * 3))) % 3];
this.addVehicle(kind, f.x - 12 + n * 9 + 0.5, f.y + 1, f.z + 0.5, Math.PI / 2, '');
}
});
}
ownerAt(x, z) { // whose kit castle (x, z) is in, or ''
for (const c of this.owned) if (x >= c.x0 && x < c.x0 + CW && z >= c.z0 && z < c.z0 + CW) return c.owner;
return '';
}
blockedFor(p, x, z) { const o = this.ownerAt(x, z); return o && (!p || o.toLowerCase() !== p.name.toLowerCase()) ? o : ''; }
buildKit(pid, type, cx, cz) {
const p = this.players.get(pid), W = this.world;
cx = Math.floor(cx); cz = Math.floor(cz);
const x0 = cx - 10, z0 = cz - 10;
if (inKingdom(cz) || inDungeon(cx)) return 'Build it at home, out in your own world';
let base = W.topY(cx, cz);
while (base > 2 && [6, 7, 18].includes(W.get(cx, base, cz))) base--; // stand on the ground, not on a treetop
for (const c of this.owned) if (x0 < c.x0 + CW + 2 && x0 + CW + 2 > c.x0 && z0 < c.z0 + CW + 2 && z0 + CW + 2 > c.z0) return 'Too close to ' + c.owner + "'s " + ownedName(c.type);
if (base > CH - 18 || base < 3) return 'The ground is too high or too low here';
if (type.startsWith('tale:')) { // a fairy tale place from the kingdom: the same blocks, gate left open, quests just for show
const ti = TALE_IDX[type.slice(5)];
if (ti == null) return 'Unknown kit';
for (let dy = PY0; dy < PY0 + PH && base + dy < CH; dy++) for (let lz = 0; lz < PW; lz++) for (let lx = 0; lx < PW; lx++) {
if (base + dy < 1) continue;
const id = placeBlock(ti, lx, dy, lz);
W.set(x0 + lx, base + dy, z0 + lz, id === 64 ? 0 : id);
}
this.owned.push({ x0, z0, base, type, owner: p.name });
this.send({ t: 'owned', list: this.owned }, null);
this.send({ t: 'msg', text: p.name + ' built ' + TALES[ti].place + '!' }, null);
return '';
}
if (PLAY_KITS[type]) { // playground / heart factory
const flag = PAINT_WOOL[paintOf(p.name)];
for (let dy = 0; dy <= 12 && base + dy < CH; dy++) for (let lz = 0; lz < CW; lz++) for (let lx = 0; lx < CW; lx++) {
const id = PLAY_KITS[type].block(lx, dy, lz, flag);
if (id >= 0) W.set(x0 + lx, base + dy, z0 + lz, id);
}
this.owned.push({ x0, z0, base, type, owner: p.name });
this.send({ t: 'owned', list: this.owned }, null);
this.send({ t: 'msg', text: p.name + ' built a ' + PLAY_KITS[type].name + '!' }, null);
return '';
}
const c = { x0, z0, base, seed: W.seed, type, kit: true, flag: PAINT_WOOL[paintOf(p.name)] };
for (let y = Math.max(1, base - 6); y < Math.min(CH, base + 17); y++)
for (let lz = 0; lz < CW; lz++) for (let lx = 0; lx < CW; lx++) {
const id = castleBlock(c, lx, y, lz);
if (id >= 0) W.set(x0 + lx, y, z0 + lz, id);
}
this.owned.push({ x0, z0, base, type, owner: p.name });
this.chests[(x0 + 10) + ',' + (base + 1) + ',' + (z0 + 14)] = []; // its treasure chest starts empty: fill it yourself
this.send({ t: 'owned', list: this.owned }, null);
this.send({ t: 'msg', text: p.name + ' built a ' + CASTLES[type].name + '!' }, null);
return '';
}
// owner: the name of the player who placed it; only they can fly it or pick it up
addVehicle(kind, x, y, z, yaw, owner) {
const d = VEHICLES[kind];
const v = { id: this.nextId++, kind, owner: String(owner || ''), x, y, z, yaw: yaw || 0, pitch: 0, roll: 0, vx: 0, vy: 0, vz: 0, w: d.w, h: d.h, rider: null, settle: true };
this.vehicles.set(v.id, v); return v;
}
ownsVehicle(p, v) { return !v.owner || (p && p.name.toLowerCase() === v.owner.toLowerCase()); }
saveVehicles() { return [...this.vehicles.values()].map(v => ({ kind: v.kind, owner: v.owner, x: v.x, y: v.y, z: v.z, yaw: v.yaw })); }
addPlayer(id, name, pos) {
const p = { id, name, x: pos.x, y: pos.y, z: pos.z, yaw: 0, pitch: 0, dead: false, sleepAt: 0, skin: hash(name.length, name.charCodeAt(0) || 1, name.charCodeAt(1) || 2, 77) };
this.players.set(id, p); this.spawnPet(id); return p;
}
removePlayer(id) {
this.players.delete(id);
for (const m of [...this.mobs.values()]) if (m.owner === id) this.mobs.delete(m.id);
for (const v of this.vehicles.values()) if (v.rider === id) { v.rider = null; v.settle = true; }
}
spawnPoint() {
const s = this.world.seed;
for (let r = 0; r < 400; r += 4) for (let a = 0; a < 8; a++) {
const x = Math.round(Math.cos(a) * r), z = Math.round(Math.sin(a) * r);
const h = heightAt(x, z, s), bm = biomeAt(x, z, s);
if (h > SEA + 1 && (bm === 0 || bm === 1)) {
const top = this.world.topY(x, z);
if (this.world.get(x, top, z) !== 1 || isSolid[this.world.get(x, top + 1, z)] || isSolid[this.world.get(x, top + 2, z)]) continue;
return { x: x + 0.5, y: top + 1, z: z + 0.5 };
}
}
return { x: 0.5, y: CH - 4, z: 0.5 };
}
handle(pid, m) {
const p = this.players.get(pid);
switch (m.t) {
case 'move': if (p) { p.x = m.x; p.y = m.y; p.z = m.z; p.yaw = m.yaw; p.pitch = m.pitch; p.dead = !!m.dead; } break;
case 'block': {
const x = m.x | 0, y = m.y | 0, z = m.z | 0, old = this.world.get(x, y, z), o = this.blockedFor(p, x, z);
const doorSwing = blk(old).shape === 'door' && blk(m.id | 0).shape === 'door';
// stairwells, dungeon walls, unbreakable story blocks and the whole fairy tale kingdom (except its doors) stay as they are
if (old === 61 || old === 62 || (old === 16 && inDungeon(x)) || (old >= 63 && blk(old).hard < 0) || (inKingdom(z) && !doorSwing)) {
this.send({ t: 'blocks', l: [x, y, z, old] }, pid);
if (inKingdom(z) && !doorSwing) this.send({ t: 'msg', text: 'This is the Fairy Tale Kingdom: look, but no digging or building here' }, pid);
break;
}
// someone else's kit castle: only its doors may be opened and closed
if (o && !doorSwing) {
this.send({ t: 'msg', text: 'This is ' + o + "'s " + ownedName((this.owned.find(c => c.owner === o && x >= c.x0 && x < c.x0 + CW && z >= c.z0 && z < c.z0 + CW) || {}).type) }, pid);
this.send({ t: 'blocks', l: [x, y, z, old] }, pid); break;
}
this.world.set(x, y, z, m.id | 0); break;
}
case 'kit': {
const it = ITEMS[m.item];
if (!p || !it || !(it.kit || it.tkit) || !fin(m.x) || !fin(m.z)) break;
const why = this.buildKit(pid, it.kit || 'tale:' + it.tkit, m.x, m.z);
if (why) { this.send({ t: 'msg', text: why }, pid); this.send({ t: 'drop', items: [[m.item, 1]] }, pid); }
break;
}
case 'hit': this.hitMob(pid, m.id, m.dmg, m.kx, m.kz); break;
case 'shoot': this.arrows.push({ x: m.x, y: m.y, z: m.z, vx: m.vx, vy: m.vy, vz: m.vz, owner: pid, life: 6, id: this.nextId++, dmg: Math.min(14, +m.dmg || 6) }); break;
case 'stairs': { // tap a stairwell: down a floor, or back up to the entrance
const x = m.x | 0, y = m.y | 0, z = m.z | 0, id = this.world.get(x, y, z);
if (!p || (id !== 61 && id !== 62 && id !== 82 && id !== 83) || Math.hypot(p.x - x - 0.5, p.z - z - 0.5) > 7) break;
let to, floor = 0, kingdom = 0; // kingdom: 1 = into the Fairy Tale Kingdom, 2 = back home from it
if (id === 62) { const e = this.dungeon.entrance || this.spawnPoint(); to = { x: e.x + 0.5, y: e.y + 1, z: e.z + 2.5 }; }
else if (id === 82) { kingdom = 1; to = Object.assign({}, KSTART); }
else if (id === 83) { kingdom = 2; const g = this.kingdom.gate; to = g ? { x: g.x + 0.5, y: g.y, z: g.z + 2.5 } : this.spawnPoint(); }
else { floor = floorAt(x) + 1; to = floorStart(floor, this.world.seed); }
for (let dz = -1; dz <= 1; dz++) for (let dx = -1; dx <= 1; dx++) this.world.chunk(Math.floor(to.x / CS) + dx, Math.floor(to.z / CS) + dz, true);
p.x = to.x; p.y = to.y; p.z = to.z;
this.send({ t: 'tp', x: to.x, y: to.y, z: to.z, floor, kingdom }, pid);
this.send({ t: 'msg', text: p.name + (floor ? ' went down to Floor ' + floor : kingdom === 1 ? ' went to the Fairy Tale Kingdom' : kingdom === 2 ? ' came home from the Fairy Tale Kingdom' : ' climbed back up to the surface') }, null);
for (const pet of this.petsOut(pid)) { pet.x = to.x + 1; pet.y = to.y; pet.z = to.z; }
break;
}
case 'travel': { // fast travel inside the kingdom (HERO > FAIRY TALES > Go there): to the gravel path outside a place's gate
const i = m.i | 0; if (!p || !inKingdom(p.z) || !TALES[i]) break;
const to = taleGate(i);
for (let dz = -1; dz <= 1; dz++) for (let dx = -1; dx <= 1; dx++) this.world.chunk(Math.floor(to.x / CS) + dx, Math.floor(to.z / CS) + dz, true);
p.x = to.x; p.y = to.y; p.z = to.z;
this.send({ t: 'tp', x: to.x, y: to.y, z: to.z, yaw: to.yaw, floor: 0, kingdom: 3, place: i }, pid);
for (const pet of this.petsOut(pid)) { pet.x = to.x + 1; pet.y = to.y; pet.z = to.z; }
break;
}
case 'pet': { // use a pet basket/egg: one more pet, if there is room (else the basket comes back)
const it = ITEMS[m.item]; if (!p || !it || !it.pet) break;
const why = this.addPet(pid, it.pet);
if (why) { this.send({ t: 'msg', text: why }, pid); this.send({ t: 'drop', items: [[m.item, 1]] }, pid); }
break;
}
case 'petname': {
const pd = p && this.petsOf(p.name), nm = String(m.name || '').replace(/[^A-Za-z0-9 _-]/g, '').trim().slice(0, 16);
const pt = pd && pd.pets[m.idx | 0]; if (!pt || !nm) break;
pt.name = nm; for (const pet of this.petsOut(pid)) if (pet.petIdx === (m.idx | 0)) pet.petName = nm;
this.petNews(pid); break;
}
case 'feed': { // Pet Food (the page already took it; it comes back if there is nobody to feed) or a Heart
if (!p) break;
if (!this.feedPet(pid, m.heart ? 25 : 40, !!m.heart) && !m.heart) {
this.send({ t: 'msg', text: 'You have no pet to feed yet' }, pid); if (m.took) this.send({ t: 'drop', items: [[220, 1]] }, pid);
}
break;
}
case 'petgift': { // once per name: 6 Pet Food so pets don't go hungry before the kids learn to make it
const pd = p && this.petsOf(p.name, true);
if (!pd || pd.gift) break;
pd.gift = 1; this.send({ t: 'drop', items: [[220, 6]] }, pid);
this.send({ t: 'msg', text: 'A gift: 6 Pet Food! Tap it to feed your pets.' }, pid); this.petNews(pid);
break;
}
case 'tame': { // feed a wild white wolf: three times and it is your pet (if you have room)
const w = this.mobs.get(m.id);
if (!p || !TAME_FOOD.includes(m.item)) break;
if (!w || w.type !== 'wolf' || Math.hypot(w.x - p.x, w.z - p.z) > 6) { if (m.took) this.send({ t: 'drop', items: [[m.item, 1]] }, pid); break; }
w.tame = Math.min(3, (w.tame || 0) + 1); w.panic = 0; w.angry = 0;
if (w.tame < 3) { this.send({ t: 'msg', text: 'The white wolf likes that! (' + w.tame + ' of 3)' }, pid); break; }
const why = this.addPet(pid, 'whitewolf');
if (why) { this.send({ t: 'msg', text: 'The white wolf wants to come with you. ' + why }, pid); break; }
this.mobs.delete(w.id);
this.send({ t: 'msg', text: p.name + ' tamed a white wolf!' }, null); break;
}
case 'wake': if (p) p.sleeping = false; break;
case 'ignite': {
const x = m.x | 0, y = m.y | 0, z = m.z | 0;
if (this.world.get(x, y, z) === 32) { this.world.set(x, y, z, 0); this.tnts.push({ x: x + 0.5, y, z: z + 0.5, vx: 0, vy: 2, vz: 0, w: 0.98, h: 0.98, fuse: 3, id: this.nextId++ }); }
break;
}
case 'chest': {
const q0 = String(m.k).split(',').map(Number), o = this.blockedFor(p, q0[0], q0[2]);
if (o) { this.send({ t: 'msg', text: 'Only ' + o + ' can open this chest' }, pid); break; }
if (!this.chests[m.k]) { const q = String(m.k).split(',').map(Number); const loot = castleLoot(q[0], q[1], q[2], this.world.seed) || dungeonLoot(q[0], q[1], q[2], this.world.seed); if (loot) this.chests[m.k] = loot; }
this.send({ t: 'chest', k: m.k, slots: this.chests[m.k] || [] }, pid); break;
}
case 'chestSet': { const q1 = String(m.k).split(',').map(Number); if (!this.blockedFor(p, q1[0], q1[2])) this.chests[m.k] = m.slots; break; }
case 'sleep': if (p) { p.sleepAt = Date.now(); this.trySleep(pid); } break;
case 'chat': if (p) this.send({ t: 'msg', text: p.name + ': ' + String(m.text).slice(0, 80) }, null); break;
case 'vplace': {
if (!p || !VEHICLES[m.kind] || !fin(m.x) || !fin(m.y) || !fin(m.z) || this.vehicles.size >= 60) break;
this.addVehicle(m.kind, m.x, m.y, m.z, fin(m.yaw) ? m.yaw : 0, p.name); break;
}
case 'vride': {
const v = this.vehicles.get(m.id); if (!v || !p) break;
if (!this.ownsVehicle(p, v)) { this.send({ t: 'msg', text: 'This is ' + v.owner + "'s. Make your own at a crafting table!" }, pid); break; }
if (!v.owner) { v.owner = p.name; this.send({ t: 'msg', text: p.name + ' found a ' + VEHICLES[v.kind].name + '! It is theirs now.' }, null); }
if (v.rider != null && v.rider !== pid && this.players.has(v.rider)) { this.send({ t: 'msg', text: 'Someone is already in it' }, pid); break; }
for (const o of this.vehicles.values()) if (o.rider === pid) o.rider = null;
v.rider = pid; v.settle = false;
this.send({ t: 'vride', id: v.id, kind: v.kind, x: v.x, y: v.y, z: v.z, yaw: v.yaw }, pid); break;
}
case 'vmove': {
const v = this.vehicles.get(m.id);
if (!v || v.rider !== pid || !fin(m.x) || !fin(m.y) || !fin(m.z)) break;
v.x = m.x; v.y = m.y; v.z = m.z; v.yaw = +m.yaw || 0; v.pitch = +m.pitch || 0; v.roll = +m.roll || 0; break;
}
case 'vleave': {
const v = this.vehicles.get(m.id); if (!v || v.rider !== pid) break;
if (fin(m.x) && fin(m.y) && fin(m.z)) { v.x = m.x; v.y = m.y; v.z = m.z; }
v.rider = null; v.pitch = 0; v.roll = 0; v.vy = 0; v.settle = true; break;
}
case 'vpickup': {
const v = this.vehicles.get(m.id);
if (!v || (v.rider != null && this.players.has(v.rider))) break;
if (!this.ownsVehicle(p, v)) { this.send({ t: 'msg', text: 'Only ' + v.owner + ' can pick that up' }, pid); break; }
this.vehicles.delete(v.id);
this.send({ t: 'drop', items: [[VEHICLES[v.kind].item, 1]] }, pid); break;
}
}
}
// lie down in a bed: the page shows you asleep until you tap WAKE UP. A nap in the day; at night, once everyone here
// is in bed, it skips to morning.
trySleep(pid) {
const p = this.players.get(pid);
for (const mob of this.mobs.values()) if (MOBS[mob.type].hostile && Math.hypot(mob.x - p.x, mob.z - p.z) < 8) {
p.sleeping = false; this.send({ t: 'nosleep', text: 'You may not rest now, there are monsters nearby' }, pid); return;
}
p.sleeping = true;
const night = dayLight(this.time) < 0.5;
if (!night) { this.send({ t: 'msg', text: 'Nap time! Sleeping heals you.' }, pid); return; }
const all = [...this.players.values()], asleep = all.filter(q => q.sleeping).length;
if (asleep < all.length) {
this.send({ t: 'msg', text: p.name + ' is in bed (' + asleep + ' of ' + all.length + '). When everyone is in bed, the night is skipped.' }, null); return;
}
for (const q of all) q.sleeping = false;
this.time = 0.01;
for (const mob of [...this.mobs.values()]) if (MOBS[mob.type].hostile) this.mobs.delete(mob.id);
this.send({ t: 'time', time: this.time }, null);
this.send({ t: 'msg', text: 'Good morning!' }, null); this.send({ t: 'wakeup' }, null);
}
hitMob(pid, id, dmg, kx, kz) {
const m = this.mobs.get(id); if (!m || MOBS[m.type].pet) return; // pets can't be hurt
const boss = MOBS[m.type].boss;
m.hp -= Math.max(0.5, Math.min(40, +dmg || 1)); // up to 40: strength potion + warrior + points on a diamond sword
m.hurt = 0.35; m.vx += (kx || 0) * (boss ? 1.5 : 6); m.vz += (kz || 0) * (boss ? 1.5 : 6); if (!boss) m.vy = 4.5;
m.target = pid; m.angry = 20; m.panic = 4;
if (m.hp <= 0) this.killMob(m, pid);
}
// pid: who gets the drops and XP; byPet: the pet of pid did it
killMob(m, pid, byPet) {
this.mobs.delete(m.id);
if (pid == null) return;
const d = MOBS[m.type], items = [];
for (const q of d.drops) { const n = q[1] + Math.floor(this.rand() * (q[2] - q[1] + 1)); if (n > 0) items.push([q[0], n]); }
if (items.length) this.send({ t: 'drop', items }, pid);
this.send({ t: 'kill', type: m.type, pet: !!byPet, floor: m.floor || 0 }, pid);
if (d.boss) { // a floor boss: open the stairs down, and everyone nearby gets the reward
const f = m.floor || 1, br = bossRoom(f, this.world.seed);
this.dungeon.unlocked[f] = true; this.dungeon.lastKill[f] = Date.now();
this.world.set(br.cx, FY + 1, br.cz, 61);
for (const p of this.players.values()) if (p.id !== pid && Math.hypot(p.x - m.x, p.z - m.z) < 30) this.send({ t: 'kill', type: m.type, floor: f, helped: true }, p.id);
this.send({ t: 'msg', text: d.name + ' IS DEFEATED! The stairs to Floor ' + (f + 1) + ' are open.' }, null);
}
}
spawnMob(type, x, y, z) {
const d = MOBS[type];
const m = { id: this.nextId++, type, x, y, z, vx: 0, vy: 0, vz: 0, w: d.w, h: d.h, hp: d.hp, maxHp: d.hp, yaw: this.rand() * 6.28,
hurt: 0, fuse: 0, cool: 1, wander: 0, wx: 0, wz: 0, target: null, angry: 0, panic: 0, burning: false, onGround: false };
this.mobs.set(m.id, m); return m;
}
nearestPlayer(x, y, z, maxD) {
let best = null, bd = maxD;
for (const p of this.players.values()) {
if (p.dead) continue;
const d = Math.hypot(p.x - x, p.y - y, p.z - z);
if (d < bd) { bd = d; best = p; }
}
return best ? { p: best, d: bd } : null;
}
lineOfSight(x0, y0, z0, x1, y1, z1) {
const dx = x1 - x0, dy = y1 - y0, dz = z1 - z0, len = Math.hypot(dx, dy, dz);
if (len < 0.01) return true;
const h = raycast(this.world, x0, y0, z0, dx / len, dy / len, dz / len, len, false);
return !h || h.d >= len - 0.5 || !isOpaque[h.id];
}
hurtPlayer(p, amt, fx, fz, src) {
if (p.dead) return;
const f = floorAt(p.x), scale = (this.diff === 'easy' ? 0.6 : 1) * (1 + Math.max(0, f - 1) * 0.15); // deeper floors hit harder
const dx = p.x - fx, dz = p.z - fz, l = Math.hypot(dx, dz) || 1;
this.send({ t: 'hurt', amt: Math.max(1, Math.round(amt * scale)), kx: dx / l, kz: dz / l, src: src || '' }, p.id);
}
explode(x, y, z, r, owner) {
const W = this.world;
for (let dy = -r; dy <= r; dy++) for (let dz = -r; dz <= r; dz++) for (let dx = -r; dx <= r; dx++) {
const d = Math.hypot(dx, dy, dz);
if (d > r + 0.3 - this.rand() * 0.8) continue;
const bx = Math.floor(x + dx), by = Math.floor(y + dy), bz = Math.floor(z + dz), id = W.get(bx, by, bz);
if (!id || blk(id).hard < 0 || this.ownerAt(bx, bz) || inKingdom(bz)) continue; // kit builds, stairs, portals and the kingdom can't be blown up
if (id === 32) { W.set(bx, by, bz, 0); this.tnts.push({ x: bx + 0.5, y: by, z: bz + 0.5, vx: (this.rand() - 0.5) * 6, vy: 5, vz: (this.rand() - 0.5) * 6, w: 0.98, h: 0.98, fuse: 0.6 + this.rand() * 1.2, id: this.nextId++ }); continue; }
W.set(bx, by, bz, 0);
}
const reach = r * 2;
for (const p of this.players.values()) {
const d = Math.hypot(p.x - x, p.y + 0.9 - y, p.z - z);
if (d < reach) this.hurtPlayer(p, (1 - d / reach) * (r >= 4 ? 20 : 16), x, z, 'boom');
}
for (const m of [...this.mobs.values()]) {
if (MOBS[m.type].pet) continue;
const d = Math.hypot(m.x - x, m.y - y, m.z - z);
if (d < reach) { m.hp -= (1 - d / reach) * 18; m.vy = 6; m.vx += (m.x - x) / (d || 1) * 8; m.vz += (m.z - z) / (d || 1) * 8; if (m.hp <= 0) this.killMob(m, typeof owner === 'number' ? owner : null); }
}
this.send({ t: 'boom', x, y, z, r }, null);
}
darkEnough(x, y, z) {
const sky = this.world.skyAt(x, y, z) * dayLight(this.time);
return sky < 0.35 && this.world.torchLightAt(x + 0.5, y + 0.5, z + 0.5) < 0.2;
}
trySpawn() {
const W = this.world;
let hostile = 0, passive = 0;
for (const m of this.mobs.values()) { if (MOBS[m.type].hostile) hostile++; else if (!MOBS[m.type].pet) passive++; }
const np = Math.max(1, this.players.size);
for (const p of this.players.values()) {
if (p.dead) continue;
if (inDungeon(p.x)) { this.dungeonTick(p); continue; }
if (inKingdom(p.z)) continue; // the fairy tale kingdom is peaceful
const a = this.rand() * Math.PI * 2, r = 20 + this.rand() * 18;
const x = Math.floor(p.x + Math.cos(a) * r), z = Math.floor(p.z + Math.sin(a) * r);
if (!W.chunks.has(key(Math.floor(x / CS), Math.floor(z / CS)))) continue;
const top = W.topY(x, z);
if (this.diff !== 'peaceful' && hostile < 10 * np) {
// surface at night, or somewhere dark underground
let y = top + 1;
if (this.rand() < 0.5) y = 3 + Math.floor(this.rand() * Math.max(1, top - 6));
if (isSolid[W.get(x, y - 1, z)] && !isSolid[W.get(x, y, z)] && !isSolid[W.get(x, y + 1, z)] && W.get(x, y, z) !== 10 && this.darkEnough(x, y, z)) {
const r2 = this.rand();
const type = r2 < 0.38 ? 'zombie' : r2 < 0.62 ? 'skeleton' : r2 < 0.84 ? 'creeper' : 'spider';
this.spawnMob(type, x + 0.5, y, z + 0.5); hostile++;
continue;
}
}
// white wolves live on the snowy grass (up to 2 per player, day or night)
if (W.get(x, top, z) === 17 && !isSolid[W.get(x, top + 1, z)] && this.rand() < 0.35) {
let wolves = 0; for (const mo of this.mobs.values()) if (mo.type === 'wolf') wolves++;
if (wolves < 2 * np) { this.spawnMob('wolf', x + 0.5, top + 1, z + 0.5); passive++; continue; }
}
if (passive < 6 * np && dayLight(this.time) > 0.6 && W.get(x, top, z) === 1 && !isSolid[W.get(x, top + 1, z)]) {
// dinosaurs: about one daytime spawn in four
if (this.rand() < 0.25) {
let dinos = 0, trex = false;
for (const mo of this.mobs.values()) if (MOBS[mo.type].dino) { dinos++; if (mo.type === 'trex') trex = true; }
if (dinos < 4 * np) {
const r3 = this.rand(), safe = this.diff === 'peaceful';
let type, n;
if (!safe && r3 < 0.12 && !trex) { type = 'trex'; n = 1; }
else if (!safe && r3 < 0.35) { type = 'raptor'; n = 2 + Math.floor(this.rand() * 2); }
else if (r3 < 0.75) { type = 'trike'; n = 1 + Math.floor(this.rand() * 2); }
else { type = 'brachio'; n = 1; }
for (let i = 0; i < n; i++) this.spawnMob(type, x + 0.5 + i * 1.5, top + 1, z + 0.5);
passive += n;
continue;
}
}
const type = ['pig', 'cow', 'sheep'][Math.floor(this.rand() * 3)];
const n = 1 + Math.floor(this.rand() * 3);
for (let i = 0; i < n; i++) this.spawnMob(type, x + 0.5 + i * 0.7, top + 1, z + 0.5);
passive += n;
}
}
}
// a pet: follow the owner (jump to them when far away) and fight monsters close to them
tickPet(m, dt) {
const p = this.players.get(m.owner), d = MOBS[m.type];
if (!p) { this.mobs.delete(m.id); return; }
m.cool -= dt;
const dist = Math.hypot(p.x - m.x, p.z - m.z);
if (dist > 20 || Math.abs(p.y - m.y) > 8) { m.x = p.x + 1; m.y = p.y + 0.3; m.z = p.z + 1; m.vx = m.vz = m.vy = 0; return; }
let foe = null, fd = 10;
for (const o of this.mobs.values()) {
if (!MOBS[o.type].hostile) continue;
const od = Math.hypot(o.x - m.x, o.z - m.z);
if (od < fd && Math.hypot(o.x - p.x, o.z - p.z) < 12) { fd = od; foe = o; }
}
let tx = p.x, tz = p.z, stop = 2.2;
if (foe) { tx = foe.x; tz = foe.z; stop = foe.w / 2 + 0.6; }
const dx = tx - m.x, dz = tz - m.z, hd = Math.hypot(dx, dz) || 1;
let mx = 0, mz = 0;
if (hd > stop) { mx = dx / hd; mz = dz / hd; m.yaw = Math.atan2(dx, dz); }
if (foe && hd < stop + 0.8 && m.cool <= 0) {
m.cool = 0.9; foe.hp -= 2 + (m.lvl || 1); foe.hurt = 0.35; foe.vx += mx * 3; foe.vz += mz * 3; foe.target = m.owner; foe.angry = 20;
this.send({ t: 'sfx', s: 'hit', x: m.x, y: m.y, z: m.z }, null);
if (foe.hp <= 0) {
this.killMob(foe, m.owner, true);
const pd = this.petsOf(p.name), pt = pd && pd.pets[m.petIdx || 0];
if (pt) { pt.xp = (pt.xp || 0) + 10; if (pt.xp >= 30 * pt.lvl) { pt.xp = 0; pt.lvl++; m.lvl = pt.lvl; this.petNews(p.id, { up: m.petIdx || 0 }); } }
}
}
const acc = m.onGround ? 12 : 3, sp = d.speed * (hd > 6 ? 1.3 : 1);
m.vx += (mx * sp - m.vx) * Math.min(1, acc * dt); m.vz += (mz * sp - m.vz) * Math.min(1, acc * dt);
m.vy -= (m.inWater ? 6 : 26) * dt; if (m.inWater) m.vy = Math.max(m.vy, 1.5);
moveBody(this.world, m, dt, true);
if (m.hitWall && m.onGround && (mx || mz)) m.vy = 7.6;
}
tickMob(m, dt) {
const d = MOBS[m.type], W = this.world, kind = d.base || m.type; // kind: how it fights (a boss fights like its base monster)
if (d.pet) { this.tickPet(m, dt); return; }
m.hurt = Math.max(0, m.hurt - dt); m.cool -= dt; m.angry -= dt; m.panic -= dt;
if (d.hostile && inSafeRoom(m.x, m.z, W.seed)) { this.mobs.delete(m.id); this.send({ t: 'sfx', s: 'pop', x: m.x, y: m.y, z: m.z }, null); return; } // safe rooms: monsters vanish
const near = this.nearestPlayer(m.x, m.y, m.z, d.hostile || (d.charges && m.angry > 0) ? (d.boss ? 40 : 22) : 10);
let mx = 0, mz = 0, speed = d.speed;
if (near && ((d.hostile && (kind !== 'spider' || d.boss || dayLight(this.time) < 0.5 || m.angry > 0 || inDungeon(m.x))) || (d.charges && m.angry > 0))) {
const p = near.p, dx = p.x - m.x, dz = p.z - m.z, hd = Math.hypot(dx, dz) || 1;
m.yaw = Math.atan2(dx, dz);
if (kind === 'trex' && !m.roared) { m.roared = true; this.send({ t: 'sfx', s: 'roar', x: m.x, y: m.y, z: m.z }, null); }
if (d.charges) speed = d.speed * 3;
if (kind === 'skeleton') {
const see = this.lineOfSight(m.x, m.y + 1.6, m.z, p.x, p.y + 1.5, p.z);
if (hd > 9 || !see) { mx = dx / hd; mz = dz / hd; } else if (hd < 5) { mx = -dx / hd; mz = -dz / hd; }
if (see && hd < 16 && m.cool <= 0) {
m.cool = d.boss ? 1.1 : 2.2;
const sy = m.y + (d.boss ? 2.6 : 1.5), ty = p.y + 1.4, tt = hd / 18;
this.arrows.push({ x: m.x + dx / hd * 0.6, y: sy, z: m.z + dz / hd * 0.6, vx: dx / hd * 18, vy: (ty - sy) / tt + 10 * tt, vz: dz / hd * 18, owner: 'mob', life: 5, id: this.nextId++, dmg: d.dmg });
this.send({ t: 'sfx', s: 'bow', x: m.x, y: m.y, z: m.z }, null);
}
} else if (kind === 'creeper') {
if (hd < 3 && Math.abs(p.y - m.y) < 2.5) {
if (m.fuse === 0) this.send({ t: 'sfx', s: 'hiss', x: m.x, y: m.y, z: m.z }, null);
m.fuse += dt;
if (m.fuse > 1.5) { this.mobs.delete(m.id); this.explode(m.x, m.y + 0.8, m.z, 3, 'creeper'); return; }
} else {
if (m.fuse > 0 && hd > 6) m.fuse = 0;
if (m.fuse > 0) m.fuse = Math.max(0, m.fuse - dt * 0.5);
mx = dx / hd; mz = dz / hd;
}
} else {
const reach = d.reach || 1.6;
if (hd > reach * 0.6) { mx = dx / hd; mz = dz / hd; }
if (hd < reach && Math.abs(p.y - m.y) < Math.max(1.6, d.h * 0.6) && m.cool <= 0) {
m.cool = kind === 'trex' ? 1.4 : 1;
this.hurtPlayer(p, d.dmg || (kind === 'spider' ? 2 : this.diff === 'normal' ? 3 : 2), m.x, m.z, m.type);
if (kind === 'trex') this.send({ t: 'sfx', s: 'roar', x: m.x, y: m.y, z: m.z }, null);
if (kind === 'spider' && m.onGround) m.vy = 5;
}
}
} else if (!d.hostile && !d.charges && m.panic > 0) {
if (m.wander <= 0 || m.wander > 1) { m.wander = 1; const a = this.rand() * 6.28; m.wx = Math.sin(a); m.wz = Math.cos(a); }
mx = m.wx; mz = m.wz; speed = d.speed * 2; m.yaw = Math.atan2(mx, mz);
} else {
m.roared = false;
m.wander -= dt;
if (m.wander <= 0) {
m.wander = 3 + this.rand() * 5;
if (this.rand() < 0.55) { const a = this.rand() * 6.28; m.wx = Math.sin(a); m.wz = Math.cos(a); } else { m.wx = 0; m.wz = 0; }
}
mx = m.wx; mz = m.wz; speed = d.speed * 0.6;
if (mx || mz) m.yaw = Math.atan2(mx, mz);
}
// movement + physics
const acc = m.onGround ? 10 : 2;
m.vx += (mx * speed - m.vx) * Math.min(1, acc * dt);
m.vz += (mz * speed - m.vz) * Math.min(1, acc * dt);
m.vy -= (m.inWater ? 6 : 26) * dt;
if (m.inWater) { m.vy = Math.max(m.vy, -2); if (mx || mz || d.hostile) m.vy += 14 * dt; }
moveBody(W, m, dt, true);
if (m.hitWall && m.onGround && (mx || mz)) m.vy = 7.6;
if (m.y < -10) { this.mobs.delete(m.id); return; }
// sunlight burns zombies and skeletons
m.burning = false;
if (d.burns && dayLight(this.time) > 0.6 && !m.inWater && W.skyAt(Math.floor(m.x), Math.floor(m.y + 1.5), Math.floor(m.z)) >= 1) {
m.burning = true; m.hp -= dt * 1.2; if (m.hp <= 0) { this.killMob(m, null); return; }
}
// despawn far away
const any = this.nearestPlayer(m.x, m.y, m.z, d.boss ? 60 : 90);
if (!any) this.mobs.delete(m.id);
}
// dungeon: monsters in the dark halls, and the floor boss when someone walks into the boss room
dungeonTick(p) {
const W = this.world, f = floorAt(p.x); if (f < 1) return;
const br = bossRoom(f, W.seed), inBoss = p.x >= br.x0 && p.x <= br.x1 + 1 && p.z >= br.z0 && p.z <= br.z1 + 1;
if (inBoss && Date.now() - (this.dungeon.lastKill[f] || 0) > 120000 && ![...this.mobs.values()].some(m => MOBS[m.type].boss && m.floor === f)) {
const type = BOSSES[(f - 1) % BOSSES.length], m = this.spawnMob(type, br.cx + 0.5, FY + 1, br.cz + 0.5);
m.floor = f; m.hp = m.maxHp = Math.round(MOBS[type].hp * (1 + Math.floor((f - 1) / BOSSES.length) * 0.6));
this.send({ t: 'msg', text: MOBS[type].name + ' HAS APPEARED!' }, null);
this.send({ t: 'sfx', s: 'roar', x: br.cx, y: FY + 1, z: br.cz }, null);
}
if (this.diff === 'peaceful') return;
let near = 0;
for (const m of this.mobs.values()) if (MOBS[m.type].hostile && Math.hypot(m.x - p.x, m.z - p.z) < 40) near++;
if (near >= 3 + f * 2) return;
const a = this.rand() * Math.PI * 2, r = 10 + this.rand() * 14;
const x = Math.floor(p.x + Math.cos(a) * r), z = Math.floor(p.z + Math.sin(a) * r), y = FY + 1;
if (inSafeRoom(x + 0.5, z + 0.5, W.seed) || (x >= br.x0 && x <= br.x1 && z >= br.z0 && z <= br.z1)) return;
if (!W.chunks.has(key(Math.floor(x / CS), Math.floor(z / CS))) || isSolid[W.get(x, y, z)] || isSolid[W.get(x, y + 1, z)] || !isSolid[W.get(x, y - 1, z)]) return;
const pool = ['zombie', 'spider', 'zombie'].concat(f >= 2 ? ['skeleton', 'skeleton'] : [], f >= 3 ? ['creeper', 'raptor'] : [], f >= 5 ? ['trike'] : []);
this.spawnMob(pool[Math.floor(this.rand() * pool.length)], x + 0.5, y, z + 0.5);
}
tickArrow(a, dt) {
a.life -= dt;
const steps = 4, sdt = dt / steps;
for (let s = 0; s < steps; s++) {
a.vy -= 20 * sdt;
a.x += a.vx * sdt; a.y += a.vy * sdt; a.z += a.vz * sdt;
if (isSolid[this.world.get(Math.floor(a.x), Math.floor(a.y), Math.floor(a.z))]) { a.life = Math.min(a.life, 0.01); a.vx = a.vy = a.vz = 0; return; }
if (a.owner === 'mob') {
for (const p of this.players.values()) {
if (!p.dead && Math.abs(p.x - a.x) < 0.4 && Math.abs(p.z - a.z) < 0.4 && a.y > p.y && a.y < p.y + 1.8) {
this.hurtPlayer(p, a.dmg || (this.diff === 'normal' ? 3 : 2), a.x - a.vx, a.z - a.vz, 'arrow'); a.life = 0; return;
}
}
} else {
for (const m of this.mobs.values()) {
if (MOBS[m.type].pet) continue;
const hw = m.w / 2 + 0.1;
if (Math.abs(m.x - a.x) < hw && Math.abs(m.z - a.z) < hw && a.y > m.y && a.y < m.y + m.h) {
const sp = Math.hypot(a.vx, a.vz) || 1;
this.hitMob(a.owner, m.id, a.dmg || 6, a.vx / sp, a.vz / sp); a.life = 0; return;
}
}
}
}
}
tick(dt) {
this.time = (this.time + dt / DAY_SECONDS) % 1;
this.tickPetFood(dt);
this.jetTimer = (this.jetTimer || 0) + dt; if (this.jetTimer > 300) { this.jetTimer = 0; this.parkJets(); } // empty airfields get a new jet
this.spawnTimer -= dt;
if (this.spawnTimer <= 0) {
this.spawnTimer = 1.5;
// keep the land around every player loaded (the server has no renderer doing it) and forget far chunks
for (const p of this.players.values()) {
const pcx = Math.floor(p.x / CS), pcz = Math.floor(p.z / CS);
for (let dz = -3; dz <= 3; dz++) for (let dx = -3; dx <= 3; dx++) this.world.chunk(pcx + dx, pcz + dz, true);
}
if (this.unloadFar) for (const [k, c] of this.world.chunks) {
let keep = false;
for (const p of this.players.values()) if (Math.abs(c.cx - Math.floor(p.x / CS)) <= 6 && Math.abs(c.cz - Math.floor(p.z / CS)) <= 6) keep = true;
if (!keep) this.world.chunks.delete(k);
}
this.trySpawn();
}
for (const m of [...this.mobs.values()]) this.tickMob(m, dt);
for (const a of this.arrows) this.tickArrow(a, dt);
this.arrows = this.arrows.filter(a => a.life > 0);
for (const tn of this.tnts) {
tn.fuse -= dt; tn.vy -= 20 * dt; tn.vx *= 0.9; tn.vz *= 0.9;
moveBody(this.world, tn, dt, false);
if (tn.fuse <= 0) { tn.dead = true; this.explode(tn.x, tn.y + 0.5, tn.z, 4, 'tnt'); }
}
this.tnts = this.tnts.filter(tn => !tn.dead);
// an empty vehicle left in the air drops down onto the ground (only where the land is loaded)
for (const v of this.vehicles.values()) {
if (v.rider != null || !v.settle || !this.world.chunks.has(key(Math.floor(v.x / CS), Math.floor(v.z / CS)))) continue;
v.vx = 0; v.vz = 0; v.vy = Math.max(-20, v.vy - 20 * dt);
moveBody(this.world, v, dt, false);
if (v.onGround || v.inWater || v.y < 1) { v.vy = 0; v.settle = false; }
}
if (this.pendingBlocks.length) { const l = this.pendingBlocks; this.pendingBlocks = []; this.send({ t: 'blocks', l }, null); }
this.snapTimer -= dt;
if (this.snapTimer <= 0) { this.snapTimer = 0.1; this.send(this.snapshot(), null); }
}
snapshot() {
const r = v => Math.round(v * 100) / 100;
const mobs = [];
for (const m of this.mobs.values()) {
const e = [m.id, MOB_TYPES.indexOf(m.type), r(m.x), r(m.y), r(m.z), r(m.yaw),
(m.hurt > 0 ? 1 : 0) | (m.fuse > 0 && (m.fuse * 6 | 0) % 2 ? 2 : 0) | (m.burning ? 4 : 0) | (Math.hypot(m.vx, m.vz) > 0.3 ? 8 : 0)];
if (MOBS[m.type].boss) e.push(Math.max(0, Math.round(m.hp / m.maxHp * 100)), m.floor || 1); // boss health bar
else if (m.owner != null) { const o = this.players.get(m.owner); e.push(m.petName || '', o ? o.name : '', m.lvl || 1); } // pet name tag
mobs.push(e);
}
const arrows = this.arrows.map(a => [a.id, r(a.x), r(a.y), r(a.z), r(a.vx), r(a.vy), r(a.vz)]);
const tnts = this.tnts.map(tn => [tn.id, r(tn.x), r(tn.y), r(tn.z), (tn.fuse * 4 | 0) % 2]);
const players = [];
for (const p of this.players.values()) players.push([p.id, p.name, r(p.x), r(p.y), r(p.z), r(p.yaw), r(p.pitch), p.dead ? 1 : 0, p.skin]);
const vehicles = [];
for (const v of this.vehicles.values()) vehicles.push([v.id, VEH_TYPES.indexOf(v.kind), r(v.x), r(v.y), r(v.z), r(v.yaw), r(v.pitch), r(v.roll), v.rider || 0, v.owner]);
return { t: 'snap', time: r(this.time * 1000) / 1000, mobs, arrows, tnts, players, vehicles };
}
}
return { CS, CH, SEA, DAY_SECONDS, TILES, T, BLOCKS, NBLOCKS, ITEMS, WOOL, blk, isOpaque, isSolid, itemName, stackSize,
isItem, allCreative, RECIPES, FUEL, hash, noise2, heightAt, biomeAt, Chunk, World, generateChunk, moveBody, raycast,
rayBox, MOBS, MOB_TYPES, VEHICLES, VEH_TYPES, dayLight, Sim, key,
CASTLES, castleAt, REG, CW, isChest, paintOf, inDungeon, floorAt, inSafeRoom, bossRoom, floorStart, FY,
PLAY_KITS, PET_NAMES, PET_KINDS, MAX_PETS, FEEDS_PER_SLOT, TAME_FOOD,
TALES, TALE_IDX, TALE_LINES, taleClips, inKingdom, placeAt, placeWorld, taleGate, placeBlock, placePlan, PLACE_TPL, taleIds, PW, PY0, ownedName, setGateOpen, KY, KZ, KSTART, PLAZA };
});
EOF
game.js: the browser side. New: textures and bag icons for everything new, drinking potions, wearing armor, damage protection, the effects list, fruit from leaves, jewel drops, placing castle kits, castle name labels and the “You found a …” message.
cat > /root/blockcraft/game.js <<'EOF'
// BlockCraft client: textures, WebGL rendering, controls, inventory/crafting, menus, saving and networking.
(() => {
'use strict';
const E = window.BC;
const { CS, CH, BLOCKS, ITEMS, blk, isOpaque, isSolid, T } = E;
const $ = id => document.getElementById(id);
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const cv = $('gl'), hud = $('hud'), hx = hud.getContext('2d');
const isTouch = matchMedia('(pointer:coarse)').matches || 'ontouchstart' in window;
if (isTouch) document.body.classList.add('touch');
const BASE = location.pathname.replace(/[^/]*$/, '');
// ---------------------------------------------------------------- settings (per device)
const cfg = { sound: true, dist: isTouch ? 3 : 4, coords: false, name: '', code: '', mpMode: 'survival' };
try { Object.assign(cfg, JSON.parse(localStorage.getItem('blockcraft_cfg') || '{}')); } catch (e) {}
const saveCfg = () => { try { localStorage.setItem('blockcraft_cfg', JSON.stringify(cfg)); return true; } catch (e) { return false; } };
// this tablet's id: the server lets a name play on only one tablet at a time, but the same tablet may reconnect
if (!cfg.dev) { cfg.dev = Math.random().toString(36).slice(2, 12) + Date.now().toString(36); saveCfg(); }
// ---------------------------------------------------------------- sound (synthesised)
let actx = null, noiseBuf = null;
function audio() {
if (!cfg.sound) return null;
if (!actx) { try { actx = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) { return null; } }
if (actx.state === 'suspended') actx.resume();
return actx;
}
function tone(f0, f1, dur, type, vol, delay) {
const a = audio(); if (!a) return;
const t0 = a.currentTime + (delay || 0), o = a.createOscillator(), g = a.createGain();
o.type = type || 'square'; o.frequency.setValueAtTime(f0, t0); o.frequency.exponentialRampToValueAtTime(Math.max(20, f1), t0 + dur);
g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.0005, t0 + dur);
o.connect(g).connect(a.destination); o.start(t0); o.stop(t0 + dur);
}
function noise(dur, vol, f0, f1, delay) {
const a = audio(); if (!a) return;
if (!noiseBuf) { noiseBuf = a.createBuffer(1, a.sampleRate, a.sampleRate); const d = noiseBuf.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; }
const t0 = a.currentTime + (delay || 0), s = a.createBufferSource(), f = a.createBiquadFilter(), g = a.createGain();
s.buffer = noiseBuf; f.type = 'lowpass'; f.frequency.setValueAtTime(f0, t0); f.frequency.exponentialRampToValueAtTime(Math.max(30, f1), t0 + dur);
g.gain.setValueAtTime(vol, t0); g.gain.exponentialRampToValueAtTime(0.001, t0 + dur);
s.connect(f).connect(g).connect(a.destination); s.start(t0, Math.random() * 0.5); s.stop(t0 + dur);
}
function sfx(name, x, y, z) {
let v = 1;
if (x != null && pl) { const d = Math.hypot(x - pl.x, y - pl.y, z - pl.z); v = 1 - d / 28; if (v <= 0) return; }
switch (name) {
case 'dig': noise(0.12, 0.25 * v, 1400, 300); break;
case 'break': noise(0.22, 0.35 * v, 2200, 200); break;
case 'place': noise(0.09, 0.3 * v, 900, 200); break;
case 'step': noise(0.05, 0.06 * v, 700, 300); break;
case 'hurt': tone(420, 180, 0.22, 'sawtooth', 0.12 * v); break;
case 'hit': noise(0.08, 0.3 * v, 3000, 500); tone(260, 120, 0.12, 'square', 0.05 * v); break;
case 'pop': tone(500, 1100, 0.08, 'sine', 0.12 * v); break;
case 'eat': for (let i = 0; i < 3; i++) noise(0.07, 0.2 * v, 1800, 600, i * 0.12); break;
case 'fanfare': [523, 659, 784, 1046].forEach((f, i) => tone(f, f, 0.16, 'square', 0.05, i * 0.1)); break;
case 'drink': for (let i = 0; i < 3; i++) tone(300 + i * 60, 200, 0.1, 'sine', 0.12 * v, i * 0.13); tone(700, 1400, 0.3, 'triangle', 0.06, 0.4); break;
case 'boom': noise(1.4, 0.7 * v, 900, 40); break;
case 'hiss': noise(1.4, 0.18 * v, 6000, 3000); break;
case 'bow': tone(300, 900, 0.12, 'triangle', 0.1 * v); break;
case 'door': noise(0.1, 0.25 * v, 600, 150); tone(140, 90, 0.1, 'square', 0.05 * v); break;
case 'splash': noise(0.4, 0.2 * v, 2500, 300); break;
case 'groan': tone(140, 90, 0.7, 'sawtooth', 0.05 * v); tone(150, 80, 0.7, 'square', 0.02 * v, 0.05); break;
case 'tool': tone(900, 300, 0.25, 'square', 0.06); break;
case 'craft': tone(600, 900, 0.07, 'square', 0.05); tone(900, 1200, 0.07, 'square', 0.05, 0.08); break;
case 'die': tone(400, 60, 0.9, 'sawtooth', 0.15); break;
case 'roar': tone(110, 45, 1.3, 'sawtooth', 0.22 * v); tone(160, 60, 1.1, 'square', 0.08 * v, 0.05); noise(1.2, 0.35 * v, 900, 120); break;
}
}
// ---------------------------------------------------------------- textures
function rng(seed) { let s = seed >>> 0 || 1; return () => { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; return (s >>> 0) / 4294967296; }; }
const hashStr = s => { let h = 2166136261; for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return h >>> 0; };
const hexRgb = h => { const n = parseInt(h.slice(1), 16); return [n >> 16 & 255, n >> 8 & 255, n & 255]; };
const PAINTS = ['#d23a32', '#2f6fd8', '#3fae3a', '#8932b8', '#f0c020', '#f07d19', '#f38baa', '#20b8b0'];
const paintFor = E.paintOf;
const atlas = document.createElement('canvas'); atlas.width = atlas.height = 256;
const ac = atlas.getContext('2d');
function drawTile(name, i) {
const img = ac.createImageData(16, 16), d = img.data, r = rng(hashStr(name) + 7);
const P = (x, y, c, a) => { if (x < 0 || y < 0 || x > 15 || y > 15) return; const k = (y * 16 + x) * 4; d[k] = c[0]; d[k + 1] = c[1]; d[k + 2] = c[2]; d[k + 3] = a == null ? 255 : a; };
const V = (c, f) => [clamp(c[0] * f, 0, 255) | 0, clamp(c[1] * f, 0, 255) | 0, clamp(c[2] * f, 0, 255) | 0];
const C = hexRgb;
const fillN = (hex, amt) => { const c = C(hex); for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(c, 1 + (r() - 0.5) * amt)); };
const rect = (x0, y0, x1, y1, hex, amt) => { const c = C(hex); for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) P(x, y, V(c, 1 + (r() - 0.5) * (amt || 0))); };
const clear = () => { for (let k = 0; k < d.length; k++) d[k] = 0; };
const voronoi = (n, cols, edge, edgeW) => {
const pts = []; for (let k = 0; k < n; k++) pts.push([r() * 16, r() * 16, C(cols[k % cols.length]), 0.85 + r() * 0.3]);
for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) {
let d1 = 99, d2 = 99, best = 0;
for (let k = 0; k < n; k++) for (let oy = -16; oy <= 16; oy += 16) for (let ox = -16; ox <= 16; ox += 16) {
const dd = Math.hypot(x + 0.5 - pts[k][0] - ox, y + 0.5 - pts[k][1] - oy);
if (dd < d1) { d2 = d1; d1 = dd; best = k; } else if (dd < d2) d2 = dd;
}
if (edge && d2 - d1 < edgeW) P(x, y, V(C(edge), 0.9 + r() * 0.2)); else P(x, y, V(pts[best][2], pts[best][3] + (r() - 0.5) * 0.12));
}
};
const ore = hex => { fillN('#7f7f7f', 0.22); for (let k = 0; k < 4; k++) { const cx = 2 + (r() * 12 | 0), cy = 2 + (r() * 12 | 0); for (let j = 0; j < 5; j++) P(cx + (r() * 3 | 0) - 1, cy + (r() * 3 | 0) - 1, V(C(hex), 0.8 + r() * 0.4)); } };
const planks = (hex) => {
const c = C(hex);
for (let y = 0; y < 16; y++) { const row = y >> 2, f = 0.88 + ((row * 7919) % 5) * 0.05; for (let x = 0; x < 16; x++) P(x, y, V(c, f + (r() - 0.5) * 0.1)); }
for (let x = 0; x < 16; x++) for (const y of [3, 7, 11, 15]) P(x, y, V(c, 0.62));
for (let row = 0; row < 4; row++) { const sx = (row * 5 + 3) % 16; for (let y = row * 4; y < row * 4 + 3; y++) P(sx, y, V(c, 0.7)); }
};
const face = (skin, eyes) => { fillN(skin, 0.15); for (const [x, y] of eyes) P(x, y, [20, 20, 20]); };
switch (name) {
case 'grass_top': fillN('#5f9e3c', 0.32); break;
case 'dirt': fillN('#866043', 0.42); for (let k = 0; k < 14; k++) P(r() * 16 | 0, r() * 16 | 0, V(C('#866043'), 0.65)); break;
case 'grass_side': fillN('#866043', 0.42); for (let x = 0; x < 16; x++) { const h = 3 + (r() < 0.45 ? 1 : 0) + (r() < 0.2 ? 1 : 0); for (let y = 0; y < h; y++) P(x, y, V(C('#5f9e3c'), 1 + (r() - 0.5) * 0.3)); } break;
case 'stone': fillN('#7f7f7f', 0.22); for (let k = 0; k < 6; k++) { const x = r() * 14 | 0, y = r() * 16 | 0; P(x, y, [98, 98, 98]); P(x + 1, y, [98, 98, 98]); } break;
case 'cobble': voronoi(9, ['#8a8a8a', '#7a7a7a', '#6c6c6c', '#949494'], '#4c4c4c', 1.1); break;
case 'planks': planks('#a8844f'); break;
case 'log_side': { const c = C('#6b5130'); for (let x = 0; x < 16; x++) { const f = 0.8 + r() * 0.35; for (let y = 0; y < 16; y++) P(x, y, V(c, f + (r() - 0.5) * 0.15)); } break; }
case 'log_top': for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) { const dd = Math.max(Math.abs(x - 7.5), Math.abs(y - 7.5)); P(x, y, V(C(dd > 6.5 ? '#6b5130' : (Math.floor(dd) % 2 ? '#b8945f' : '#a07c4a')), 1 + (r() - 0.5) * 0.12)); } break;
case 'leaves': for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) { if (r() < 0.16) P(x, y, [0, 0, 0], 0); else P(x, y, V(C('#3f7f28'), 0.7 + r() * 0.6)); } break;
case 'sand': fillN('#dbcf9c', 0.14); break;
case 'gravel': voronoi(18, ['#8f8a86', '#7a7470', '#a09a94', '#6a6460'], '#5a5450', 0.6); break;
case 'water': { const c = C('#3a66d0'); for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(c, ((x + y * 3) % 8 < 2 ? 1.2 : 1) + (r() - 0.5) * 0.08)); break; }
case 'glass': clear(); for (let k = 0; k < 16; k++) { P(k, 0, [216, 240, 248]); P(k, 15, [216, 240, 248]); P(0, k, [216, 240, 248]); P(15, k, [216, 240, 248]); } for (let k = 3; k < 7; k++) P(k, k, [255, 255, 255], 200); P(9, 4, [255, 255, 255], 160); P(10, 5, [255, 255, 255], 160); break;
case 'coal_ore': ore('#222222'); break;
case 'iron_ore': ore('#d8af93'); break;
case 'gold_ore': ore('#fcee4b'); break;
case 'diamond_ore': ore('#5decf5'); break;
case 'bedrock': for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(C('#555555'), 0.4 + r() * 1.1)); break;
case 'snow': fillN('#f2f6f6', 0.06); break;
case 'snow_side': fillN('#866043', 0.42); for (let x = 0; x < 16; x++) { const h = 3 + (r() < 0.5 ? 1 : 0); for (let y = 0; y < h; y++) P(x, y, V(C('#f2f6f6'), 1 - r() * 0.06)); } break;
case 'cactus_side': { const c = C('#3f7f2a'); for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(c, (x % 4 === 0 ? 0.75 : 1) + (r() - 0.5) * 0.15)); for (let k = 0; k < 10; k++) P(r() * 16 | 0, r() * 16 | 0, C('#d8eaa8')); break; }
case 'cactus_top': for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) { const dd = Math.max(Math.abs(x - 7.5), Math.abs(y - 7.5)); P(x, y, V(C(dd > 5.5 ? '#3f7f2a' : '#5a9a3a'), 1 + (r() - 0.5) * 0.12)); } break;
case 'table_top': planks('#a8844f'); for (let k = 0; k < 16; k++) { P(k, 0, [90, 60, 30]); P(k, 15, [90, 60, 30]); P(0, k, [90, 60, 30]); P(15, k, [90, 60, 30]); P(k, 7, [110, 76, 40]); P(7, k, [110, 76, 40]); } break;
case 'table_side': case 'table_front': planks('#a8844f'); rect(0, 0, 15, 2, '#6b4a26', 0.1);
if (name === 'table_front') { rect(3, 6, 7, 8, '#9a9a9a'); rect(3, 9, 4, 12, '#6b4a26'); rect(10, 5, 13, 6, '#9a9a9a'); rect(11, 7, 12, 13, '#6b4a26'); } break;
case 'furnace_front': fillN('#6f6f6f', 0.22); rect(4, 8, 11, 13, '#1a1a1a'); rect(5, 12, 10, 13, '#3a2a1a'); rect(3, 3, 12, 4, '#4f4f4f'); break;
case 'furnace_side': fillN('#707070', 0.22); for (let k = 0; k < 16; k++) { P(k, 0, [80, 80, 80]); P(k, 15, [80, 80, 80]); } break;
case 'furnace_top': fillN('#8a8a8a', 0.15); break;
case 'chest_front': case 'chest_side': case 'chest_top': {
const c = C('#a2702d');
for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(c, (y % 4 === 3 ? 0.82 : 1) + (r() - 0.5) * 0.1));
for (let k = 0; k < 16; k++) { P(k, 0, [80, 50, 20]); P(k, 15, [80, 50, 20]); P(0, k, [80, 50, 20]); P(15, k, [80, 50, 20]); }
if (name !== 'chest_top') for (let k = 1; k < 15; k++) P(k, 5, [80, 50, 20]);
if (name === 'chest_front') rect(7, 4, 8, 7, '#c8c8c8');
break;
}
case 'torch': clear(); rect(7, 9, 8, 15, '#7a5a32'); rect(7, 6, 8, 6, '#ff9d2a'); rect(7, 7, 8, 8, '#ffe066'); break;
case 'door_bottom': case 'door_top': {
planks('#8a6234');
for (let k = 0; k < 16; k++) { P(0, k, [70, 45, 20]); P(15, k, [70, 45, 20]); P(k, name === 'door_top' ? 0 : 15, [70, 45, 20]); }
if (name === 'door_top') { for (let y = 3; y <= 8; y++) for (let x = 3; x <= 12; x++) if (x !== 7 && x !== 8 && y !== 5) P(x, y, [0, 0, 0], 0); }
else rect(12, 1, 13, 2, '#c8c8c8');
break;
}
case 'bed_top': fillN('#c43a3a', 0.12); rect(1, 1, 14, 4, '#e8e8e8', 0.05); break;
case 'bed_side': clear(); rect(0, 7, 15, 10, '#c43a3a', 0.1); rect(0, 11, 15, 12, '#e0e0e0', 0.05); rect(0, 13, 15, 15, '#8a6234', 0.1); break;
case 'tnt_side': fillN('#d44030', 0.12); rect(0, 6, 15, 9, '#eeeeee', 0.04);
for (const [x, y] of [[2, 6], [3, 6], [4, 6], [3, 7], [3, 8], [3, 9], [6, 6], [6, 7], [6, 8], [6, 9], [7, 7], [8, 6], [8, 7], [8, 8], [8, 9], [10, 6], [11, 6], [12, 6], [11, 7], [11, 8], [11, 9]]) P(x, y, [20, 20, 20]);
break;
case 'tnt_top': fillN('#d44030', 0.12); rect(7, 7, 8, 8, '#333333'); break;
case 'tnt_bottom': fillN('#a83020', 0.12); break;
case 'bricks': { fillN('#b5b0a8', 0.08); for (let row = 0; row < 4; row++) for (let b = 0; b < 3; b++) { const x0 = b * 8 - (row % 2) * 4; for (let y = row * 4; y < row * 4 + 3; y++) for (let x = x0; x < x0 + 7; x++) if (x >= 0 && x < 16) P(x, y, V(C('#975a49'), 1 + (r() - 0.5) * 0.2)); } break; }
case 'stone_bricks': fillN('#7a7a7a', 0.15); for (let k = 0; k < 16; k++) { P(k, 7, [88, 88, 88]); P(k, 15, [88, 88, 88]); } for (let y = 0; y < 7; y++) P(7, y, [88, 88, 88]); for (let y = 8; y < 15; y++) P(15, y, [88, 88, 88]); break;
case 'bookshelf': { planks('#a8844f'); const cols = ['#a83232', '#3250a8', '#32a850', '#a88a32', '#7a32a8']; for (const [y0, y1] of [[2, 6], [9, 13]]) for (let x = 1; x < 15; x += 2) { const c = cols[r() * 5 | 0]; rect(x, y0 + (r() < 0.3 ? 1 : 0), x + 1, y1, c, 0.15); } break; }
case 'flower_red': case 'flower_yellow': { clear(); rect(7, 8, 7, 15, '#3f8a28'); P(6, 11, C('#3f8a28')); const pc = name === 'flower_red' ? '#d42020' : '#f0e020'; rect(6, 4, 8, 6, pc); P(7, 3, C(pc)); P(5, 5, C(pc)); P(9, 5, C(pc)); P(7, 5, C(name === 'flower_red' ? '#f0e020' : '#c08010')); break; }
case 'tall_grass': clear(); for (let k = 0; k < 7; k++) { const x0 = 1 + (r() * 14 | 0), h = 6 + (r() * 9 | 0), lean = r() < 0.5 ? -1 : 1; for (let y = 0; y < h; y++) P(x0 + (y > h * 0.6 ? lean : 0), 15 - y, V(C('#5f9e3c'), 0.75 + r() * 0.5)); } break;
case 'glowstone': voronoi(10, ['#f4d27a', '#ffe9a6', '#e8b85a'], '#9c7a3a', 0.8); break;
case 'sandstone_side': fillN('#d8c98e', 0.1); rect(0, 0, 15, 2, '#e2d49c', 0.05); for (let k = 0; k < 16; k++) { P(k, 3, [180, 165, 115]); P(k, 12, [180, 165, 115]); } break;
case 'sandstone_top': fillN('#dccf96', 0.1); break;
case 'slab_side': fillN('#a8a8a8', 0.08); for (let k = 0; k < 16; k++) { P(k, 8, [120, 120, 120]); P(k, 15, [120, 120, 120]); } break;
case 'slab_top': fillN('#b0b0b0', 0.08); for (let k = 0; k < 16; k++) { P(k, 0, [130, 130, 130]); P(k, 15, [130, 130, 130]); P(0, k, [130, 130, 130]); P(15, k, [130, 130, 130]); } break;
case 'snow_block': fillN('#f6fafa', 0.05); break;
case 'ladder': clear(); rect(2, 0, 3, 15, '#7a5a32', 0.1); rect(12, 0, 13, 15, '#7a5a32', 0.1); for (const y of [2, 6, 10, 14]) rect(2, y, 13, y, '#9a7a48', 0.1); break;
case 'zombie_face': face('#5f9f4a', [[4, 6], [5, 6], [10, 6], [11, 6], [4, 7], [11, 7]]); rect(0, 0, 15, 2, '#3f7a30', 0.15); rect(7, 8, 8, 9, '#4a8038'); rect(5, 11, 10, 11, '#3a6a2a'); break;
case 'zombie_skin': fillN('#5f9f4a', 0.2); break;
case 'zombie_shirt': fillN('#2fa8a8', 0.15); break;
case 'zombie_pants': fillN('#3b3f9f', 0.15); break;
case 'skeleton_face': face('#c6c6c6', [[4, 6], [5, 6], [4, 7], [5, 7], [10, 6], [11, 6], [10, 7], [11, 7], [7, 9], [8, 9]]); for (let x = 4; x <= 11; x += 2) P(x, 12, [40, 40, 40]); break;
case 'bone': fillN('#c6c6c6', 0.12); for (let k = 0; k < 10; k++) P(r() * 16 | 0, r() * 16 | 0, [138, 138, 138]); break;
case 'creeper_face': case 'creeper_skin': {
for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(C(r() < 0.3 ? '#7cd36a' : r() < 0.5 ? '#3f9a2f' : '#4fae3a'), 1));
if (name === 'creeper_face') { rect(3, 4, 6, 7, '#101010'); rect(9, 4, 12, 7, '#101010'); rect(6, 8, 9, 11, '#101010'); rect(4, 10, 5, 13, '#101010'); rect(10, 10, 11, 13, '#101010'); }
break;
}
case 'spider_face': fillN('#2e2620', 0.3); for (const [x, y] of [[3, 6], [4, 6], [11, 6], [12, 6], [6, 8], [9, 8], [5, 5], [10, 5]]) P(x, y, [200, 20, 20]); break;
case 'spider_body': fillN('#2e2620', 0.35); for (let k = 0; k < 8; k++) P(r() * 16 | 0, r() * 16 | 0, [70, 60, 50]); break;
case 'pig_face': face('#f0a5a2', [[3, 5], [12, 5]]); P(4, 5, [240, 240, 240]); P(11, 5, [240, 240, 240]); rect(5, 8, 10, 11, '#e58c8a'); P(6, 9, [120, 60, 60]); P(9, 9, [120, 60, 60]); break;
case 'pig_skin': fillN('#f0a5a2', 0.1); break;
case 'cow_face': fillN('#4a3424', 0.15); rect(5, 0, 10, 5, '#e8e8e8', 0.05); P(3, 6, [10, 10, 10]); P(12, 6, [10, 10, 10]); rect(4, 10, 11, 15, '#c8a890', 0.08); P(6, 12, [60, 40, 30]); P(9, 12, [60, 40, 30]); break;
case 'cow_skin': for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(C(E.noise2(x / 5, y / 5, 9) > 0.55 ? '#4a3424' : '#e8e8e8'), 1 + (r() - 0.5) * 0.08)); break;
case 'sheep_face': face('#d6bfa3', [[4, 7], [11, 7]]); rect(7, 10, 8, 10, '#c08a80'); rect(0, 0, 15, 3, '#e8e8e8', 0.1); break;
case 'sheep_wool': fillN('#e8e8e8', 0.16); break;
case 'player_face': fillN('#c99a7a', 0.08); rect(0, 0, 15, 3, '#4a3220', 0.15); rect(0, 4, 0, 6, '#4a3220'); rect(15, 4, 15, 6, '#4a3220');
rect(3, 8, 4, 8, '#ffffff'); rect(11, 8, 12, 8, '#ffffff'); P(4, 8, [40, 70, 160]); P(11, 8, [40, 70, 160]); rect(6, 12, 9, 12, '#8a5040'); break;
case 'player_hair': fillN('#4a3220', 0.2); break;
case 'player_skin': fillN('#c99a7a', 0.08); break;
case 'player_shirt': fillN('#2fa8c8', 0.12); break;
case 'player_pants': fillN('#3b3f9f', 0.12); break;
case 'arrow_tex': fillN('#8a6a40', 0.2); break;
case 'tnt_lit': fillN('#ffffff', 0.04); break;
case 'diamond_block': fillN('#5decf5', 0.1); for (let k = 0; k < 16; k++) { P(k, 0, [30, 160, 170]); P(k, 15, [30, 160, 170]); P(0, k, [30, 160, 170]); P(15, k, [30, 160, 170]); } rect(3, 3, 5, 5, '#c8fbff'); rect(9, 8, 10, 9, '#c8fbff'); P(12, 3, [200, 250, 255]); break;
case 'mossy_bricks': fillN('#7a7a7a', 0.15); for (let k = 0; k < 16; k++) { P(k, 7, [88, 88, 88]); P(k, 15, [88, 88, 88]); } for (let y = 0; y < 7; y++) P(7, y, [88, 88, 88]); for (let y = 8; y < 15; y++) P(15, y, [88, 88, 88]);
for (let k = 0; k < 40; k++) { const x = r() * 16 | 0, y = r() * 16 | 0; if (E.noise2(x / 4, y / 4, 5) > 0.45) P(x, y, V(C('#4f7a2f'), 0.8 + r() * 0.4)); } break;
case 'trex_skin': case 'raptor_skin': case 'trike_skin': case 'brachio_skin': {
const base = { trex_skin: '#5a6b3a', raptor_skin: '#a8743a', trike_skin: '#7a8a5a', brachio_skin: '#7f907a' }[name];
for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(C(base), (name !== 'brachio_skin' && (x + y * 2) % 7 < 2 ? 0.75 : 1) + (r() - 0.5) * 0.2));
break;
}
case 'trex_face': case 'raptor_face': {
fillN(name === 'trex_face' ? '#5a6b3a' : '#a8743a', 0.2);
rect(2, 3, 4, 5, '#f0d020'); P(3, 4, [10, 10, 10]); rect(11, 3, 13, 5, '#f0d020'); P(12, 4, [10, 10, 10]);
rect(5, 2, 10, 3, '#3a4a20'); P(6, 8, [30, 20, 20]); P(9, 8, [30, 20, 20]);
rect(1, 11, 14, 12, '#401010'); for (let x = 1; x <= 14; x += 2) { P(x, 10, [245, 245, 230]); P(x + 1, 13, [245, 245, 230]); }
break;
}
case 'trike_face': fillN('#7a8a5a', 0.15); rect(3, 5, 4, 6, '#101010'); rect(11, 5, 12, 6, '#101010'); rect(5, 10, 10, 15, '#5a4a3a', 0.1); P(7, 12, [30, 20, 20]); P(8, 12, [30, 20, 20]); break;
case 'brachio_face': fillN('#7f907a', 0.12); rect(3, 5, 4, 6, '#101010'); rect(11, 5, 12, 6, '#101010'); rect(4, 12, 11, 12, '#4a5a40'); break;
case 'paint0': case 'paint1': case 'paint2': case 'paint3': case 'paint4': case 'paint5': case 'paint6': case 'paint7': {
// each player's vehicles get their own colour (PAINTS, picked from the owner's name)
const c = PAINTS[+name.slice(5)];
fillN(c, 0.08); rect(0, 6, 15, 8, '#f4f4f4', 0.03); for (let k = 0; k < 16; k += 4) P(k, 2, V(C(c), 0.7)); break;
}
case 'plane_wing': fillN('#e8e8e8', 0.06); for (let k = 0; k < 16; k++) P(k, 8, [190, 190, 190]); break;
case 'metal': fillN('#9aa0a6', 0.12); for (const [x, y] of [[2, 2], [13, 2], [2, 13], [13, 13]]) P(x, y, [70, 74, 80]); break;
case 'cockpit': clear(); for (let k = 0; k < 16; k++) { P(k, 0, [60, 64, 70]); P(k, 15, [60, 64, 70]); P(0, k, [60, 64, 70]); P(15, k, [60, 64, 70]); P(7, k, [60, 64, 70]); }
for (let k = 2; k < 6; k++) P(k, k - 1, [220, 245, 255], 255); P(10, 2, [220, 245, 255]); break;
case 'rotor': fillN('#2a2c30', 0.15); break;
case 'stairs_down': case 'stairs_up': { // a glowing stairwell seen from above: steps going down into the light
const up = name === 'stairs_up', c = C(up ? '#40d0a0' : '#8a40d0');
fillN('#3a3a44', 0.1);
for (let k = 0; k < 6; k++) { const v = up ? 0.55 + k * 0.12 : 1.25 - k * 0.12; rect(2, 2 + k * 2, 13, 3 + k * 2, '#000'); for (let x = 2; x <= 13; x++) for (let y = 2 + k * 2; y <= 3 + k * 2; y++) P(x, y, V(c, v)); }
for (let k = 0; k < 16; k++) { P(k, 0, [200, 200, 220]); P(k, 15, [200, 200, 220]); P(0, k, [200, 200, 220]); P(15, k, [200, 200, 220]); }
break;
}
case 'stairs_side': fillN('#4a4a55', 0.15); for (let k = 0; k < 16; k++) { P(k, 7, [70, 70, 80]); P(k, 15, [70, 70, 80]); } rect(5, 3, 10, 5, '#b080f0'); break;
case 'cat_skin': fillN('#e8964a', 0.12); for (let y = 1; y < 16; y += 4) for (let x = 0; x < 16; x++) if ((x + y) % 5 < 2) P(x, y, [190, 110, 40]); break;
case 'cat_face': fillN('#e8964a', 0.1); rect(2, 0, 4, 2, '#c87a3a'); rect(11, 0, 13, 2, '#c87a3a'); rect(3, 6, 5, 7, '#60c040'); P(4, 6, [10, 10, 10]); rect(10, 6, 12, 7, '#60c040'); P(11, 6, [10, 10, 10]);
rect(7, 9, 8, 10, '#f0a0b0'); P(6, 12, [60, 40, 30]); P(9, 12, [60, 40, 30]); for (const yy of [10, 11]) { P(1, yy, [250, 250, 250]); P(14, yy, [250, 250, 250]); } break;
case 'dog_skin': fillN('#c8a070', 0.12); for (let k = 0; k < 6; k++) rect(r() * 12 | 0, r() * 12 | 0, (r() * 12 | 0) + 3, (r() * 12 | 0) + 2, '#8a6038', 0.1); break;
case 'dog_face': fillN('#c8a070', 0.1); rect(0, 0, 3, 8, '#8a6038'); rect(12, 0, 15, 8, '#8a6038'); P(5, 5, [20, 20, 20]); P(10, 5, [20, 20, 20]); rect(5, 9, 10, 13, '#e0c8a0'); rect(7, 9, 8, 10, '#202020'); rect(7, 13, 8, 15, '#e05070'); break;
case 'silver_ore': ore('#eef2f8'); break;
case 'gem_ore': fillN('#7f7f7f', 0.22); for (const col of ['#e0115f', '#2ecc71', '#2f6fd8', '#9b59b6']) { const cx = 2 + (r() * 12 | 0), cy = 2 + (r() * 12 | 0); P(cx, cy, C(col)); P(cx + 1, cy, C(col)); P(cx, cy + 1, C(col)); P(cx + 1, cy + 1, V(C(col), 1.3)); } break;
case 'gold_block': case 'silver_block': { const c = name === 'gold_block' ? '#f5d742' : '#d8dee6', e = name === 'gold_block' ? [184, 150, 28] : [150, 158, 170];
fillN(c, 0.08); for (let k = 0; k < 16; k++) { P(k, 0, e); P(k, 15, e); P(0, k, e); P(15, k, e); } rect(3, 3, 5, 4, '#ffffff'); P(10, 9, [255, 255, 255]); break; }
case 'ice_bricks': fillN('#a8d8f0', 0.08); for (let k = 0; k < 16; k++) { P(k, 7, [120, 170, 210]); P(k, 15, [120, 170, 210]); } for (let y = 0; y < 7; y++) P(7, y, [120, 170, 210]); for (let y = 8; y < 15; y++) P(15, y, [120, 170, 210]);
for (let k = 1; k < 5; k++) P(k + 1, k, [230, 248, 255]); break;
case 'treasure_front': case 'treasure_side': case 'treasure_top': {
const c = C('#8a5a24');
for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(c, (y % 4 === 3 ? 0.82 : 1) + (r() - 0.5) * 0.1));
for (let k = 0; k < 16; k++) { P(k, 0, [245, 200, 60]); P(k, 15, [245, 200, 60]); P(0, k, [245, 200, 60]); P(15, k, [245, 200, 60]); }
if (name !== 'treasure_top') for (let k = 1; k < 15; k++) P(k, 5, [245, 200, 60]); else { rect(7, 1, 8, 14, '#f5c83c'); }
if (name === 'treasure_front') { rect(6, 4, 9, 8, '#f5d742'); P(7, 6, [60, 40, 10]); P(8, 6, [60, 40, 10]); P(4, 10, [224, 17, 95]); P(11, 10, [46, 204, 113]); }
break;
}
// fairy tale kingdom add-on
case 'story_top': fillN('#6a6a72', 0.15); rect(2, 3, 7, 12, '#f4ecd8', 0.04); rect(8, 3, 13, 12, '#f4ecd8', 0.04); rect(7, 3, 8, 12, '#8a6a40');
for (let y = 5; y <= 11; y += 2) { rect(3, y, 6, y, '#9a8a70'); rect(9, y, 12, y, '#9a8a70'); } P(11, 4, C('#f5d742')); P(4, 4, C('#e0306a')); break;
case 'story_side': fillN('#7a7480', 0.18); for (const y of [4, 7, 10]) rect(3, y, 12 - (y === 7 ? 3 : 0), y, '#f5d742'); P(12, 7, [255, 255, 255]); P(13, 6, [255, 240, 160]);
for (let k = 0; k < 16; k++) { P(k, 15, [90, 84, 96]); P(k, 0, [150, 140, 160]); } break;
case 'gate': clear(); for (const x of [1, 5, 10, 14]) rect(x, 0, x, 15, '#f5d742'); rect(0, 1, 15, 1, '#d8b030'); rect(0, 14, 15, 14, '#d8b030');
for (let k = 0; k < 14; k++) P(r() * 16 | 0, 2 + (r() * 12 | 0), r() < 0.5 ? [230, 200, 255] : [255, 255, 255]); P(7, 7, [255, 220, 120]); P(8, 8, [255, 220, 120]); break;
case 'thorns': for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) { if (r() < 0.12) P(x, y, [0, 0, 0], 0); else P(x, y, V(C('#2f5a20'), 0.6 + r() * 0.6)); }
for (let k = 0; k < 7; k++) { const x = r() * 15 | 0, y = r() * 15 | 0; P(x, y, [110, 74, 38]); P(x + 1, y + 1, [200, 190, 160]); } break;
case 'golden_ball': clear(); for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) { const q = Math.hypot(x - 7.5, y - 10.5); if (q < 4.6) P(x, y, q > 3.6 ? [184, 150, 28] : [245, 215, 66]); }
P(6, 8, [255, 255, 255]); P(5, 9, [255, 250, 210]); break;
case 'straw_top': case 'straw_side': fillN('#e0c060', 0.25); for (let k = 0; k < 22; k++) { const x = r() * 16 | 0, y = r() * 16 | 0; P(x, y, [184, 150, 64]); P(x, Math.min(15, y + 1), [240, 214, 120]); }
if (name === 'straw_side') { rect(0, 4, 15, 4, '#8a6a30'); rect(0, 11, 15, 11, '#8a6a30'); } break;
case 'wheel': clear(); for (let a = 0; a < 32; a++) { const ang = a / 32 * Math.PI * 2; P(Math.round(8 + Math.cos(ang) * 5), Math.round(6 + Math.sin(ang) * 5), [138, 98, 52]); }
for (let a = 0; a < 4; a++) { const ang = a * Math.PI / 4; for (let k = -4; k <= 4; k++) P(Math.round(8 + Math.cos(ang) * k), Math.round(6 + Math.sin(ang) * k), [170, 130, 80]); }
rect(3, 11, 3, 15, '#6b4a26'); rect(12, 11, 12, 15, '#6b4a26'); rect(3, 12, 12, 12, '#6b4a26'); rect(14, 3, 14, 9, '#e8e0c8'); P(13, 6, [138, 98, 52]); break;
case 'ginger': fillN('#a0602a', 0.18); for (let x = 0; x < 16; x++) P(x, 1 + (x % 4 < 2 ? 0 : 1), [250, 250, 250]); for (let k = 0; k < 6; k++) P(r() * 16 | 0, 4 + (r() * 12 | 0), [250, 240, 240]);
P(4, 8, [224, 64, 80]); P(11, 11, [46, 160, 220]); break;
case 'icing': fillN('#fff4f8', 0.05); for (let k = 0; k < 12; k++) P(r() * 16 | 0, r() * 16 | 0, C(['#f38baa', '#7ad0f0', '#f5d742', '#8ce08c'][k % 4])); break;
case 'candy': for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, (x + y) % 6 < 3 ? [224, 64, 80] : [250, 250, 250]); break;
case 'pebbles': clear(); for (const [cx, cy, rx] of [[4, 13, 2.2], [9, 14, 1.8], [12, 12.5, 2], [7, 11.5, 1.4]]) for (let y = 9; y < 16; y++) for (let x = 0; x < 16; x++) {
const q = ((x - cx) / rx) ** 2 + ((y - cy) / 1.3) ** 2; if (q < 1) P(x, y, q > 0.6 ? [176, 176, 184] : [244, 244, 250]); } break;
case 'rose': clear(); rect(7, 8, 7, 15, '#3f8a28'); P(6, 11, C('#3f8a28')); P(5, 10, C('#3f8a28')); P(8, 13, C('#3f8a28')); P(9, 12, C('#3f8a28'));
for (let y = 2; y < 9; y++) for (let x = 3; x < 12; x++) { const q = Math.hypot(x - 7, y - 5); if (q < 3.4) P(x, y, q < 1.2 ? [150, 16, 50] : (x + y) % 3 ? [224, 48, 106] : [190, 30, 80]); } break;
case 'slipper': clear(); rect(2, 12, 13, 13, '#f5d742'); rect(9, 9, 13, 11, '#f5d742'); rect(2, 10, 6, 11, '#f5d742'); rect(12, 14, 13, 15, '#b8961c'); rect(2, 14, 4, 14, '#b8961c');
P(10, 10, [255, 255, 255]); P(4, 9, [255, 250, 200]); rect(7, 11, 9, 11, '#fff6c0'); break;
case 'quilt': fillN('#fafafa', 0.04); for (let k = 0; k < 16; k++) { P(k, k, [214, 214, 232]); P(15 - k, k, [214, 214, 232]); } rect(1, 1, 14, 3, '#ffffff'); break;
case 'quilt_side': clear(); rect(0, 7, 15, 11, '#f4f4fa', 0.05); for (let x = 0; x < 16; x += 4) P(x, 9, [210, 210, 230]); rect(0, 12, 15, 15, '#8a6234', 0.1); break;
case 'shoes': clear(); for (const x0 of [2, 9]) { rect(x0, 12, x0 + 4, 14, '#8a3a2a'); rect(x0, 10, x0 + 1, 11, '#8a3a2a'); rect(x0, 15, x0 + 4, 15, '#3a2010'); P(x0 + 1, 10, [240, 220, 160]); P(x0 + 3, 12, [240, 220, 160]); } break;
case 'basket': clear(); for (let y = 9; y <= 15; y++) for (let x = 3; x <= 12; x++) P(x, y, (x + y) % 2 ? [168, 122, 64] : [130, 90, 44]);
for (let a = 0; a <= 10; a++) { const ang = Math.PI * a / 10; P(Math.round(7.5 + Math.cos(ang) * 4.5), Math.round(9 - Math.sin(ang) * 5), [130, 90, 44]); }
rect(4, 7, 7, 8, '#f8e0e8'); P(5, 6, [224, 48, 80]); rect(9, 5, 10, 8, '#3f8a28'); P(9, 4, [200, 200, 200]); break;
case 'musicians': clear(); rect(2, 11, 13, 14, '#8a8a8a'); rect(12, 9, 14, 12, '#8a8a8a'); P(14, 8, [90, 90, 90]); P(13, 10, [20, 20, 20]); rect(3, 15, 3, 15, '#555'); rect(11, 15, 11, 15, '#555');
rect(4, 7, 11, 10, '#b8865a'); rect(10, 6, 12, 8, '#b8865a'); P(11, 7, [20, 20, 20]); rect(5, 4, 10, 6, '#e8964a'); P(5, 3, C('#e8964a')); P(7, 3, C('#e8964a')); P(6, 4, [40, 160, 40]);
rect(7, 1, 9, 3, '#f4f4f4'); P(8, 0, [220, 30, 30]); P(9, 0, [220, 30, 30]); P(10, 2, [240, 170, 30]); P(8, 2, [20, 20, 20]); break;
case 'braid': clear(); for (let y = 0; y < 16; y++) { const o = y % 4 < 2 ? 0 : 1; rect(6 + o, y, 8 + o, y, y % 2 ? '#f5d742' : '#d8b030'); } P(7, 15, [224, 48, 106]); P(8, 15, [224, 48, 106]); break;
case 'bird': clear(); for (let y = 6; y < 16; y++) for (let x = 0; x < 16; x++) { const q = ((x - 7) / 4.5) ** 2 + ((y - 11) / 3) ** 2; if (q < 1) P(x, y, q > 0.7 ? [200, 200, 212] : [250, 250, 250]); }
rect(10, 6, 12, 9, '#fafafa'); P(11, 7, [20, 20, 20]); P(13, 8, [240, 150, 40]); rect(2, 9, 4, 10, '#e8e8f0'); P(6, 14, [240, 150, 40]); P(8, 14, [240, 150, 40]); P(6, 15, [240, 150, 40]); P(8, 15, [240, 150, 40]); break;
case 'frog': clear(); for (let y = 8; y < 16; y++) for (let x = 0; x < 16; x++) { const q = ((x - 7.5) / 5.5) ** 2 + ((y - 12.5) / 3.4) ** 2; if (q < 1) P(x, y, q > 0.7 ? [47, 122, 36] : [79, 174, 58]); }
for (const ex of [4, 10]) { rect(ex, 7, ex + 2, 9, '#4fae3a'); P(ex + 1, 8, [250, 250, 250]); P(ex + 1, 7, [20, 20, 20]); } rect(6, 12, 9, 12, '#2f6a20');
rect(6, 5, 9, 5, '#f5d742'); P(6, 4, C('#f5d742')); P(8, 4, C('#f5d742')); P(9, 4, C('#f5d742')); break;
case 'goat': case 'mother_goat': { clear(); const big = name === 'mother_goat', b = big ? [216, 208, 192] : [240, 236, 224], e = big ? [150, 140, 120] : [190, 184, 170], y0 = big ? 7 : 9; // a goat looking right
for (let y = y0; y <= 12; y++) for (let x = 2; x <= 11; x++) P(x, y, y === 12 || x === 2 ? e : b);
for (const lx of [3, 5, 9, 11]) { P(lx, 13, e); P(lx, 14, e); P(lx, 15, [80, 70, 60]); }
rect(11, y0 - 3, 14, y0, big ? '#d8d0c0' : '#f0ece0'); P(13, y0 - 2, [20, 20, 20]); P(14, y0, [240, 160, 170]); P(11, y0 - 4, C('#8a7a60')); P(12, y0 - 5, C('#8a7a60'));
P(12, y0 + 1, [240, 240, 240]); if (big) { P(12, y0 + 2, [245, 215, 66]); P(13, y0 + 2, [245, 215, 66]); P(13, y0 + 3, [184, 150, 28]); } break; }
case 'goose': clear(); for (let y = 8; y < 15; y++) for (let x = 1; x < 13; x++) { const q = ((x - 6.5) / 5.5) ** 2 + ((y - 11.5) / 3.2) ** 2; if (q < 1) P(x, y, q > 0.65 ? [200, 160, 30] : [245, 215, 66]); }
rect(10, 3, 11, 9, '#f5d742'); rect(11, 2, 13, 4, '#f5d742'); P(12, 3, [20, 20, 20]); rect(14, 3, 15, 4, '#f08a20'); for (let x = 3; x <= 8; x += 2) P(x, 10, [255, 250, 210]);
P(6, 15, [240, 138, 32]); P(8, 15, [240, 138, 32]); break;
case 'dshoes': clear(); for (const x0 of [1, 8]) { rect(x0, 11, x0 + 6, 13, '#e0306a'); rect(x0, 9, x0 + 1, 10, '#e0306a'); rect(x0, 14, x0 + 6, 14, '#801838');
P(x0 + 3, 12, [255, 255, 255]); P(x0 + 5, 12, [0, 0, 0], 0); P(x0 + 4, 13, [0, 0, 0], 0); P(x0 + 4, 11, [245, 215, 66]); } P(4, 6, [255, 240, 160]); P(12, 5, [255, 255, 255]); P(8, 3, [255, 240, 160]); break; // full of holes
case 'snail': clear(); for (let y = 4; y < 15; y++) for (let x = 2; x < 14; x++) { const dd = Math.hypot(x - 7.5, y - 9), a = Math.atan2(y - 9, x - 7.5); if (dd < 5.6) P(x, y, (dd + a * 0.9 + 6) % 2.2 < 0.8 ? [122, 80, 40] : dd > 4.8 ? [138, 96, 52] : [200, 154, 90]); }
rect(1, 14, 14, 14, '#9a7a58'); break;
// pets + play add-on
case 'trampoline': fillN('#2a6ad0', 0.06); rect(0, 0, 15, 1, '#f03a5a'); rect(0, 14, 15, 15, '#f03a5a'); rect(0, 0, 1, 15, '#f03a5a'); rect(14, 0, 15, 15, '#f03a5a'); for (let k = 3; k < 13; k += 3) { P(k, 7, [120, 170, 240]); P(7, k, [120, 170, 240]); } break;
case 'trampoline_side': clear(); rect(0, 0, 15, 3, '#f03a5a', 0.05); for (const lx of [1, 7, 14]) rect(lx, 4, lx, 15, '#909090'); break;
case 'slide': fillN('#f5c020', 0.05); rect(0, 0, 1, 15, '#e08a10'); rect(14, 0, 15, 15, '#e08a10'); for (let k = 2; k < 16; k += 4) rect(4, k, 11, k, '#ffe070'); break;
case 'swing': clear(); for (let y = 0; y < 11; y++) { P(4, y, [60, 60, 60]); P(11, y, [60, 60, 60]); } rect(2, 11, 13, 13, '#c84040'); break;
case 'merry_top': fillN('#e05090', 0.05); for (let k = 0; k < 16; k++) { P(k, k, [250, 220, 60]); P(15 - k, k, [250, 220, 60]); P(7, k, [80, 180, 240]); P(k, 7, [80, 180, 240]); } break;
case 'merry_side': fillN('#e05090', 0.05); for (let x = 0; x < 16; x += 4) rect(x, 0, x + 1, 15, '#f5d742'); break;
case 'heart_block': case 'heart_front': case 'heart_top': {
fillN(name === 'heart_top' ? '#d84078' : '#f38baa', 0.06);
const hc = C(name === 'heart_front' ? '#ff1f5a' : '#e03068'), hr = [[3, 4, 5, 10, 11, 12], [2, 3, 4, 5, 6, 9, 10, 11, 12, 13], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [4, 5, 6, 7, 8, 9, 10, 11], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9], [7, 8]];
if (name !== 'heart_top') hr.forEach((xs, i) => xs.forEach(x => P(x, 4 + i, hc)));
else rect(4, 4, 11, 11, '#ff6fa0');
if (name === 'heart_front') { rect(0, 0, 15, 1, '#a02050'); rect(0, 14, 15, 15, '#a02050'); }
break;
}
case 'wolf_skin': fillN('#f2f4f8', 0.08); for (let k = 0; k < 8; k++) P(r() * 16 | 0, r() * 16 | 0, [214, 220, 232]); break;
case 'wolf_face': fillN('#f2f4f8', 0.06); rect(0, 0, 3, 4, '#d6dce8'); rect(12, 0, 15, 4, '#d6dce8'); rect(4, 5, 5, 6, '#4aa8e8'); rect(10, 5, 11, 6, '#4aa8e8'); rect(6, 9, 9, 13, '#ffffff'); rect(7, 9, 8, 10, '#202020'); break;
case 'leaves_silver': case 'leaves_gold': case 'leaves_diamond': { const lc = C({ leaves_silver: '#d8dee6', leaves_gold: '#f5d742', leaves_diamond: '#5decf5' }[name]);
for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) { if (r() < 0.16) P(x, y, [0, 0, 0], 0); else P(x, y, V(lc, 0.75 + r() * 0.45)); }
for (let k = 0; k < 5; k++) P(r() * 16 | 0, r() * 16 | 0, [255, 255, 255]); break; }
case 'portal': for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) { const dd = Math.hypot(x - 7.5, y - 7.5), a = Math.atan2(y - 7.5, x - 7.5), k = (dd * 0.9 + a * 1.6 + 20) % 3;
P(x, y, k < 1 ? [138, 64, 208] : k < 2 ? [192, 128, 255] : [240, 225, 255]); }
for (let k = 0; k < 16; k++) { P(k, 0, [245, 215, 66]); P(k, 15, [245, 215, 66]); P(0, k, [245, 215, 66]); P(15, k, [245, 215, 66]); } break;
case 'home_top': fillN('#40d0a0', 0.1); for (let y = 3; y <= 7; y++) rect(8 - (y - 3), y, 7 + (y - 3), y, '#ffffff'); rect(4, 8, 11, 13, '#ffffff'); rect(7, 10, 8, 13, '#2a8a6a'); break;
default: {
const w = E.WOOL.find(q => q[1] === name);
if (w) { const c = C(w[2]); for (let y = 0; y < 16; y++) for (let x = 0; x < 16; x++) P(x, y, V(c, ((x + y) % 4 === 0 ? 0.9 : 1) + (r() - 0.5) * 0.1)); }
else fillN('#ff00ff', 0);
}
}
ac.putImageData(img, (i % 16) * 16, (i >> 4) * 16);
}
E.TILES.forEach(drawTile);
// ---------------------------------------------------------------- item icons (data URLs, 32x32)
const iconCache = {};
function iconFor(id) {
if (iconCache[id]) return iconCache[id];
const c = document.createElement('canvas'); c.width = c.height = 32;
const x = c.getContext('2d'); x.imageSmoothingEnabled = false;
const tileXY = tt => [(tt % 16) * 16, (tt >> 4) * 16];
const flat = tt => { const [sx, sy] = tileXY(tt); x.drawImage(atlas, sx, sy, 16, 16, 0, 0, 32, 32); };
if (id < 100) {
const d = blk(id);
if (['cross', 'torch', 'ladder'].includes(d.shape)) flat(d.tex[0]);
else {
const top = d.tex[0], side = d.tex.length === 6 ? d.tex[2] : d.tex[2];
const draw = (tt, a, b, cc, dd, e, f, dark) => {
const [sx, sy] = tileXY(tt);
x.setTransform(a, b, cc, dd, e, f); x.drawImage(atlas, sx, sy, 16, 16, 0, 0, 16, 16);
if (dark) { x.fillStyle = 'rgba(0,0,0,' + dark + ')'; x.fillRect(0, 0, 16, 16); }
};
draw(top, 1, 0.5, -1, 0.5, 16, 0, 0);
draw(side, 1, 0.5, 0, 1, 0, 8, 0.25);
draw(d.tex.length === 6 ? d.tex[4] : side, 1, -0.5, 0, 1, 16, 16, 0.42);
x.setTransform(1, 0, 0, 1, 0, 0);
}
} else if (id === 115) {
const [ax, ay] = tileXY(T.door_top), [bx, by] = tileXY(T.door_bottom);
x.drawImage(atlas, ax, ay, 16, 16, 8, 0, 16, 16); x.drawImage(atlas, bx, by, 16, 16, 8, 16, 16, 16);
} else if (ITEMS[id] && ITEMS[id].tile) flat(T[ITEMS[id].tile]); // fairy tale keepsakes that look like their story block
else drawItem(x, id);
return (iconCache[id] = c.toDataURL());
}
function drawItem(x, id) {
const P = (px, py, col) => { x.fillStyle = col; x.fillRect(px * 2, py * 2, 2, 2); };
const line = (x0, y0, x1, y1, col, th) => {
const n = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0)) || 1;
for (let i = 0; i <= n; i++) { const px = Math.round(x0 + (x1 - x0) * i / n), py = Math.round(y0 + (y1 - y0) * i / n); P(px, py, col); if (th) P(px + 1, py, col); }
};
const blob = (cx, cy, rx, ry, col, edge) => { for (let py = 0; py < 16; py++) for (let px = 0; px < 16; px++) { const q = ((px - cx) / rx) ** 2 + ((py - cy) / ry) ** 2; if (q < 1) P(px, py, q > 0.7 && edge ? edge : col); } };
const it = ITEMS[id] || {};
// treasure add-on icons
const gem = (c, e) => { for (let py = 2; py <= 13; py++) for (let px = 2; px <= 13; px++) { const q = Math.abs(px - 7.5) * 1.1 + Math.abs(py - 8) * (py < 6 ? 2 : 0.9); if (q < 6.5) P(px, py, q > 5 ? e : c); } P(6, 5, '#fff'); P(5, 6, '#fff'); };
const fruitCol = { 151: ['#f5d742', '#b8961c'], 152: ['#b8d84a', '#7a9a2a'], 153: ['#f39c12', '#c0700a'], 155: ['#d01030', '#900818'], 156: ['#7a3aa8', '#4a1a70'] };
if (it.potion || id === 159) { // bottle
blob(8, 10, 5, 4.5, '#cfe8f0', '#7a9aa8'); for (let py = 3; py <= 6; py++) { P(7, py, '#7a9aa8'); P(8, py, '#cfe8f0'); } P(7, 2, '#8a6a40'); P(8, 2, '#8a6a40');
if (it.potion) { blob(8, 10.5, 4, 3.5, it.color, it.color); P(6, 9, '#ffffff'); }
return;
}
if (it.armor != null) {
const c = ['#e0e0e0', '#f5d742', '#5decf5'][it.tier], e = ['#9a9a9a', '#b8961c', '#1aa6b0'][it.tier];
const shapes = [ // helmet, chestplate, leggings, boots
[[3, 4, 12, 6], [3, 7, 4, 10], [11, 7, 12, 10]], [[2, 3, 5, 6], [10, 3, 13, 6], [4, 6, 11, 13]],
[[4, 3, 11, 5], [4, 6, 6, 13], [9, 6, 11, 13]], [[3, 8, 6, 12], [9, 8, 12, 12], [2, 12, 6, 13], [9, 12, 13, 13]]][it.armor];
for (const [x0, y0, x1, y1] of shapes) for (let py = y0; py <= y1; py++) for (let px = x0; px <= x1; px++) P(px, py, py === y1 || px === x0 ? e : c);
return;
}
if (it.kit === 'playground') { // a slide and a swing
line(2, 13, 6, 3, '#f5c020', true); line(6, 3, 6, 13, '#8a6234'); line(9, 4, 9, 13, '#8a6234'); line(14, 4, 14, 13, '#8a6234'); line(9, 4, 14, 4, '#8a6234');
line(11, 5, 11, 10, '#555'); line(12, 5, 12, 10, '#555'); line(10, 10, 13, 10, '#c84040'); line(1, 14, 15, 14, '#dccf9a'); return;
}
if (it.kit === 'heart') { // a pink factory with a heart and a chimney
for (let py = 6; py <= 14; py++) for (let px = 2; px <= 13; px++) P(px, py, '#f38baa');
line(10, 2, 10, 6, '#d84078', true); P(11, 1, '#ff6fa0');
for (const [x, y] of [[6, 8], [9, 8], [5, 9], [6, 9], [7, 9], [8, 9], [9, 9], [10, 9], [6, 10], [7, 10], [8, 10], [9, 10], [7, 11], [8, 11]]) P(x, y, '#ff1f5a');
line(7, 13, 8, 13, '#8a3a5a'); return;
}
if (it.kit) { // little castle in the kit's colours
const k = E.CASTLES[it.kit], wc = { fort: '#8a6234', stone: '#8a8a8a', royal: '#9a9aa8', palace: '#dccf96', ice: '#a8d8f0' }[it.kit];
for (let py = 6; py <= 14; py++) for (let px = 1; px <= 14; px++) P(px, py, (px === 7 || px === 8) && py > 10 ? '#3a2a1a' : wc);
for (const px of [1, 3, 5, 10, 12, 14]) P(px, 5, wc);
for (let py = 2; py <= 5; py++) P(7, py, '#5a4a3a');
const fl = E.blk(k.flag).color; P(8, 2, fl); P(9, 2, fl); P(8, 3, fl); P(9, 3, fl);
if (it.kit === 'royal') { P(4, 8, '#f5d742'); P(11, 8, '#f5d742'); }
return;
}
if (it.tkit) { // a fairy tale place kit: a little house in the tale's colour on an open story book
const T0 = E.TALES[E.TALE_IDX[it.tkit]];
for (let px = 1; px <= 14; px++) { P(px, 13, '#f4ecd8'); P(px, 14, px === 7 || px === 8 ? '#8a6a40' : '#e0d4b8'); }
for (let py = 7; py <= 12; py++) for (let px = 4; px <= 11; px++) P(px, py, (px === 7 || px === 8) && py > 9 ? '#3a2a1a' : T0.color);
for (let k = 0; k < 5; k++) for (let px = 3 + k; px <= 12 - k; px++) P(px, 6 - k, '#c02020');
P(13, 2, '#f5d742'); P(12, 1, '#fff'); P(2, 3, '#f5d742');
return;
}
if (it.keep) { // fairy tale keepsakes without a story block of their own
if (it.keep === 'redcap') { blob(8, 9, 6, 4.5, '#c02020', '#801010'); for (let px = 2; px <= 14; px++) P(px, 12, '#a01818'); P(6, 7, '#ff7070'); }
else if (it.keep === 'bremen') { blob(6, 10, 4.5, 4, '#b8865a', '#6b4a26'); blob(6, 10, 1.3, 1.3, '#3a2010'); line(9, 8, 14, 2, '#8a6234', true); P(14, 1, '#6b4a26'); P(13, 1, '#6b4a26'); }
else if (it.keep === 'rumpel') { for (let py = 4; py <= 12; py++) for (let px = 4; px <= 11; px++) P(px, py, py % 2 ? '#f5d742' : '#d8b030'); for (let px = 3; px <= 12; px++) { P(px, 3, '#8a6234'); P(px, 13, '#8a6234'); } line(11, 8, 15, 14, '#f5d742'); }
else if (it.keep === 'holle') { blob(8, 8, 5.5, 5.5, '#f5d742', '#b8961c'); blob(8, 8, 3, 3, '#e8c030'); P(6, 5, '#fff'); P(13, 2, '#e8f0ff'); P(2, 13, '#e8f0ff'); }
else if (it.keep === 'hansel') { blob(5.5, 6.5, 3.2, 3.2, '#a0602a', '#6b3a18'); blob(10.5, 6.5, 3.2, 3.2, '#a0602a', '#6b3a18'); for (let py = 7; py <= 14; py++) for (let px = 2 + (py - 7); px <= 13 - (py - 7); px++) P(px, py, '#a0602a');
line(4, 6, 7, 9, '#fafafa'); line(11, 6, 8, 9, '#fafafa'); P(8, 12, '#e04050'); }
else if (it.keep === 'wolf') { for (let py = 5; py <= 12; py++) { const w = Math.round((py - 4) * 0.7) + 2; for (let px = 8 - w; px <= 7 + w; px++) P(px, py, px === 8 - w ? '#b8961c' : '#f5d742'); } // a goat bell on its strap
for (let px = 3; px <= 12; px++) P(px, 13, '#b8961c'); blob(7.5, 14, 1.2, 1, '#6b4a26'); for (let px = 5; px <= 10; px++) P(px, 2, '#c02020'); P(5, 3, '#c02020'); P(10, 3, '#c02020'); P(7, 4, '#c02020'); P(8, 4, '#c02020'); P(6, 7, '#fff6c0'); }
else if (it.keep === 'snow') { blob(7.5, 6.5, 5, 5.5, '#c8b070', '#8a6a30'); blob(7.5, 6.5, 3.6, 4.2, '#dfe8f0', '#b8c8d8'); P(6, 4, '#ffffff'); P(5, 5, '#ffffff'); for (let py = 11; py <= 15; py++) { P(7, py, '#8a6a30'); P(8, py, '#c8b070'); } } // a little hand mirror
else if (it.keep === 'goose') { for (let k = 0; k <= 12; k++) { const px = 2 + k, py = 14 - k; P(px, py, '#b8961c'); if (k > 2) for (let w = 1; w <= Math.min(3, 13 - k); w++) { P(px - w, py - w, '#f5d742'); P(px + w, py + w, '#e8c030'); } } P(9, 4, '#fff6c0'); } // a golden feather
else if (it.keep === 'shoes') { line(2, 14, 13, 3, '#b8c0c8', true); for (const [px, py] of [[6, 8], [9, 5], [11, 6], [5, 11], [12, 2]]) blob(px, py, 1.6, 1.2, '#e8eef4', '#9aa4ae'); P(9, 4, '#ffffff'); } // a silver twig
return;
}
if (it.box != null) { // a gift box with a ribbon, and sparkles on the good ones
for (let py = 6; py <= 14; py++) for (let px = 2; px <= 13; px++) P(px, py, py === 14 || px === 2 ? '#00000060' : it.color);
for (let px = 1; px <= 14; px++) { P(px, 5, it.color); P(px, 6, it.color); }
for (let py = 5; py <= 14; py++) { P(7, py, '#d02030'); P(8, py, '#d02030'); }
for (let px = 1; px <= 14; px++) P(px, 9, '#d02030');
P(5, 3, '#d02030'); P(6, 4, '#d02030'); P(9, 4, '#d02030'); P(10, 3, '#d02030');
if (it.box >= 2) { P(1, 1, '#fff'); P(14, 2, '#fff'); P(13, 0, '#ffffaa'); }
if (it.box === 3) { P(0, 4, '#fff'); P(15, 7, '#ffccff'); P(3, 0, '#ffccff'); }
return;
}
if (it.pet) {
if (it.pet === 'babydino') { blob(8, 9, 5, 6, '#f0ead0', '#c8bc90'); for (const [sx, sy] of [[6, 6], [10, 9], [7, 12]]) blob(sx, sy, 1.2, 1, '#5a6b3a'); return; }
for (let py = 8; py <= 14; py++) for (let px = 2; px <= 13; px++) P(px, py, (px + py) % 3 === 0 ? '#8a6234' : '#b8945f');
for (let a = 0; a <= 12; a++) { const ang = Math.PI * a / 12; P(Math.round(8 + Math.cos(ang) * 6), Math.round(8 - Math.sin(ang) * 5), '#8a6234'); }
const c = it.pet === 'cat' ? '#e8964a' : '#c8a070'; blob(8, 7, 3, 2.5, c); P(7, 7, '#111'); P(9, 7, '#111');
if (it.pet === 'cat') { P(5, 4, c); P(11, 4, c); } else { P(5, 6, '#8a6038'); P(11, 6, '#8a6038'); }
return;
}
if (it.tool && id !== 143 && id !== 182) {
const mc = ['#a8844f', '#8a8a8a', '#e0e0e0', '#5decf5'][it.tier - 1], dk = ['#6b5130', '#555555', '#9a9a9a', '#1aa6b0'][it.tier - 1];
if (it.tool === 'sword') { line(5, 11, 13, 3, mc, true); P(13, 2, mc); line(3, 8, 8, 13, '#4a3220'); line(2, 14, 4, 12, '#6b5130', true); line(6, 11, 13, 4, dk); return; }
line(3, 13, 10, 6, '#6b5130', true);
if (it.tool === 'pick') { line(5, 3, 10, 3, mc, true); line(10, 3, 13, 6, mc, true); line(13, 6, 13, 11, mc, true); line(6, 4, 10, 4, dk); line(12, 7, 12, 10, dk); }
else if (it.tool === 'axe') { for (let py = 2; py <= 7; py++) for (let px = 8; px <= 13; px++) if (px - 8 + (7 - py) < 9) P(px, py, mc); line(8, 7, 13, 2, dk); }
else { blob(11.5, 4.5, 3, 3, mc, dk); }
return;
}
switch (id) {
case 100: line(3, 13, 12, 4, '#7a5a32', true); break;
case 101: blob(8, 8, 5, 4.5, '#2a2a2a', '#111'); P(6, 6, '#555'); P(9, 7, '#555'); break;
case 102: case 103: { const c = id === 102 ? '#d8d8d8' : '#f5d742', e = id === 102 ? '#9a9a9a' : '#b8961c'; for (let py = 6; py <= 10; py++) for (let px = 3 + (10 - py); px <= 13 - (10 - py) + 2; px++) P(px, py, py === 10 ? e : c); break; }
case 104: for (let py = 0; py < 16; py++) for (let px = 0; px < 16; px++) { const q = Math.abs(px - 7.5) + Math.abs(py - 7.5); if (q < 6) P(px, py, q > 4.5 ? '#1aa6b0' : '#5decf5'); } P(6, 5, '#fff'); break;
case 105: blob(8, 9.5, 5, 5, '#d42020', '#9a1010'); line(8, 2, 8, 4, '#6b4a26'); P(9, 3, '#3f8a28'); P(6, 7, '#ff8080'); break;
case 106: case 107: blob(8, 8.5, 6, 4.5, id === 106 ? '#f0a0a0' : '#b56a3a', id === 106 ? '#d07070' : '#7a4422'); line(4, 7, 11, 7, id === 106 ? '#ffe0e0' : '#d8a070'); break;
case 108: case 109: blob(8, 8.5, 6, 4.5, id === 108 ? '#c03030' : '#7a4422', id === 108 ? '#8a2020' : '#4a2a12'); P(6, 7, id === 108 ? '#fff' : '#a06030'); P(10, 9, id === 108 ? '#fff' : '#a06030'); break;
case 110: blob(8, 8.5, 6, 4.5, '#7a8a3a', '#4a5a2a'); P(6, 7, '#4a5a2a'); P(10, 9, '#4a5a2a'); break;
case 111: line(4, 12, 12, 4, '#e8e8e0', true); P(3, 12, '#e8e8e0'); P(4, 13, '#e8e8e0'); P(12, 3, '#e8e8e0'); P(13, 4, '#e8e8e0'); break;
case 112: line(3, 13, 12, 4, '#8a6a40'); P(12, 4, '#aaa'); P(13, 3, '#aaa'); P(11, 3, '#aaa'); P(13, 5, '#aaa'); P(2, 12, '#eee'); P(3, 14, '#eee'); P(2, 14, '#eee'); break;
case 113: for (let py = 8; py < 14; py++) for (let px = 8 - (py - 8); px < 8 + (py - 8); px++) P(px, py, Math.random() < 0.5 ? '#555' : '#888'); break;
case 114: blob(8, 8, 6, 5, '#9a5a2a', '#6b3a18'); break;
case 116: for (let px = 2; px < 14; px++) P(px, 8 + Math.round(Math.sin(px) * 1.5), '#eeeeee'); break;
case 140: case 141: blob(8, 9, 5.5, 4.5, id === 140 ? '#d05050' : '#8a4a22', id === 140 ? '#902a2a' : '#5a2a10'); line(11, 6, 14, 2, '#f0f0e0', true); P(14, 1, '#f0f0e0'); P(13, 1, '#f0f0e0'); break;
case 142: for (let py = 2; py <= 14; py++) { const w = Math.max(0, Math.round((py - 2) / 3)); for (let px = 8 - w; px <= 8 + w; px++) P(px, py, py > 11 ? '#c8b890' : '#f4f2e6'); } break;
case 143: line(5, 11, 13, 3, '#f4f2e6', true); P(13, 2, '#f4f2e6'); line(6, 11, 13, 4, '#c8b890'); line(3, 8, 8, 13, '#5a6b3a'); line(2, 14, 4, 12, '#6b5130', true); break;
case 146: for (let py = 6; py <= 10; py++) for (let px = 3 + (10 - py); px <= 13 - (10 - py) + 2; px++) P(px, py, py === 10 ? '#9aa4ae' : '#eef2f8'); break;
case 147: gem('#e0115f', '#8a0a3a'); break;
case 148: gem('#2ecc71', '#16804a'); break;
case 149: gem('#2f6fd8', '#183c80'); break;
case 150: gem('#a868d8', '#5a2a80'); break;
case 151: case 152: case 153: case 155: case 156: {
const [c, e] = fruitCol[id];
if (id === 155) { blob(5.5, 11, 3, 3, c, e); blob(10.5, 11, 3, 3, c, e); line(5, 8, 8, 3, '#3f8a28'); line(10, 8, 8, 3, '#3f8a28'); }
else if (id === 156) { for (const [gx, gy] of [[6, 6], [9, 6], [7.5, 8.5], [5, 9], [10, 9], [7.5, 11.5]]) blob(gx, gy, 1.9, 1.9, c, e); line(8, 2, 8, 4, '#3f8a28'); }
else if (id === 152) { blob(8, 10.5, 5, 4.5, c, e); blob(8, 6, 3, 3, c, e); line(8, 1, 8, 3, '#6b4a26'); }
else { blob(8, 9.5, 5, 5, c, e); line(8, 2, 8, 4, '#6b4a26'); P(9, 3, '#3f8a28'); P(6, 7, '#ffffff'); }
break;
}
case 154: for (let a = 0; a <= 10; a++) { const ang = Math.PI * (0.15 + a / 14); const px = Math.round(8 + Math.cos(ang) * 6), py = Math.round(4 + Math.sin(ang) * 8); P(px, py, '#f5d742'); P(px, py - 1, '#f5d742'); P(px + 1, py - 1, '#c8a820'); } P(13, 5, '#6b4a26'); break;
case 157: for (let py = 6; py <= 13; py++) for (let px = 2; px <= 13; px++) { const q = ((px - 7.5) / 6) ** 2 + ((py - 5) / 8) ** 2; if (q < 1 && py >= 6) P(px, py, q > 0.75 ? '#3f8a28' : q > 0.6 ? '#e8f0c0' : '#e8404a'); } P(6, 8, '#111'); P(9, 9, '#111'); P(7, 11, '#111'); break;
case 182: line(5, 11, 13, 3, '#eef2f8', true); P(13, 2, '#eef2f8'); line(6, 11, 13, 4, '#9aa4ae'); line(3, 8, 8, 13, '#2f6fd8'); line(2, 14, 4, 12, '#6b5130', true); break;
case 144: // airplane, seen from above
for (let py = 1; py <= 14; py++) { P(7, py, '#d23a32'); P(8, py, '#d23a32'); }
for (let px = 1; px <= 14; px++) { P(px, 6, '#e8e8e8'); P(px, 7, '#e8e8e8'); }
P(1, 6, '#d23a32'); P(14, 6, '#d23a32'); P(1, 7, '#d23a32'); P(14, 7, '#d23a32');
for (let px = 5; px <= 10; px++) P(px, 13, '#e8e8e8');
P(7, 4, '#8fd0f0'); P(8, 4, '#8fd0f0'); P(6, 0, '#333'); P(9, 0, '#333'); P(7, 0, '#9aa0a6'); P(8, 0, '#9aa0a6'); break;
case 145: // helicopter, side view
line(1, 2, 14, 2, '#2a2c30'); P(7, 3, '#9aa0a6');
blob(6, 7.5, 4.5, 3.5, '#f0c020', '#c89a10'); blob(4, 7, 2, 2, '#8fd0f0');
line(10, 7, 14, 6, '#f0c020', true); line(14, 4, 14, 7, '#2a2c30');
line(2, 13, 11, 13, '#333'); P(4, 12, '#333'); P(9, 12, '#333'); break;
case 224: case 225: case 226: { // jets, seen from above: pointy nose, swept wings
const jc = { 224: '#8a9098', 225: '#d23a32', 226: '#2a2c34' }[id], wc = id === 225 ? '#f0f0f0' : jc;
for (let py = 0; py <= 14; py++) { const w = py < 3 ? 0 : 1; for (let px = 7 - w; px <= 8 + w; px++) P(px, py, jc); }
for (let k = 0; k <= 6; k++) { P(6 - k, 6 + k, wc); P(9 + k, 6 + k, wc); P(6 - k, 7 + k, wc); P(9 + k, 7 + k, wc); }
line(5, 14, 10, 14, wc); P(7, 3, '#8fd0f0'); P(8, 3, '#8fd0f0'); P(7, 4, '#8fd0f0'); P(8, 4, '#8fd0f0'); break;
}
case 220: blob(8, 11, 6, 3.5, '#d0d4dc', '#8a909a'); blob(8, 9.5, 4.5, 1.6, '#a8642a'); for (const [x, y] of [[6, 9], [9, 9], [8, 10]]) P(x, y, '#7a4218'); break; // pet bowl
case 221: [[3, 4, 5, 10, 11, 12], [2, 3, 4, 5, 6, 9, 10, 11, 12, 13], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [4, 5, 6, 7, 8, 9, 10, 11], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9], [7, 8]]
.forEach((xs, i) => xs.forEach(x => P(x, 3 + i, '#ff2f6a'))); P(4, 4, '#ffb0c8'); P(3, 5, '#ffb0c8'); break; // a heart
case 117: for (let a = 0; a <= 12; a++) { const ang = Math.PI * (0.5 + a / 24); P(Math.round(13 + Math.cos(ang) * 10), Math.round(13 - Math.sin(ang) * 10), '#7a5a32'); }
line(3, 13, 13, 3, '#cccccc'); break;
default: blob(8, 8, 5, 5, '#ff00ff');
}
}
// ---------------------------------------------------------------- WebGL
const gl = cv.getContext('webgl', { antialias: false, alpha: false, powerPreference: 'high-performance' });
const glOK = !!gl;
let uintExt = null, prog, flat, atlasTex, quadIBO, maxQuads, dynVBO;
if (glOK) {
uintExt = gl.getExtension('OES_element_index_uint');
const sh = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) console.error(gl.getShaderInfoLog(s)); return s; };
const mk = (vs, fs) => { const p = gl.createProgram(); gl.attachShader(p, sh(gl.VERTEX_SHADER, vs)); gl.attachShader(p, sh(gl.FRAGMENT_SHADER, fs)); gl.linkProgram(p); return p; };
prog = mk(`attribute vec3 aP;attribute vec2 aT;attribute vec3 aL;
uniform mat4 uM;uniform vec3 uOff;uniform vec3 uCam;uniform float uDay;uniform vec2 uFog;uniform float uMin;
varying vec2 vT;varying vec3 vC;varying float vF;
void main(){vec3 p=aP+uOff;gl_Position=uM*vec4(p,1.0);vT=aT;
vec3 c=max(vec3(aL.x*uDay),vec3(aL.y)*vec3(1.0,0.85,0.6));vC=max(c,vec3(uMin))*aL.z;
vF=clamp((length(p-uCam)-uFog.x)/(uFog.y-uFog.x),0.0,1.0);}`,
`precision mediump float;uniform sampler2D uTex;uniform vec3 uFogC;uniform float uAlpha;uniform vec4 uTint;
varying vec2 vT;varying vec3 vC;varying float vF;
void main(){vec4 t=texture2D(uTex,vT);if(t.a<0.5)discard;vec3 c=mix(t.rgb*vC,uTint.rgb,uTint.a);
gl_FragColor=vec4(mix(c,uFogC,vF),uAlpha);}`);
prog.a = { p: gl.getAttribLocation(prog, 'aP'), t: gl.getAttribLocation(prog, 'aT'), l: gl.getAttribLocation(prog, 'aL') };
prog.u = {}; ['uM', 'uOff', 'uCam', 'uDay', 'uFog', 'uTex', 'uFogC', 'uAlpha', 'uTint', 'uMin'].forEach(n => { prog.u[n] = gl.getUniformLocation(prog, n); });
flat = mk('attribute vec3 aP;uniform mat4 uM;void main(){gl_Position=uM*vec4(aP,1.0);}',
'precision mediump float;uniform vec4 uC;void main(){gl_FragColor=uC;}');
flat.a = gl.getAttribLocation(flat, 'aP'); flat.uM = gl.getUniformLocation(flat, 'uM'); flat.uC = gl.getUniformLocation(flat, 'uC');
atlasTex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, atlasTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, atlas);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
maxQuads = uintExt ? 65536 : 16383;
const idx = uintExt ? new Uint32Array(maxQuads * 6) : new Uint16Array(maxQuads * 6);
for (let q = 0; q < maxQuads; q++) { const b = q * 4, o = q * 6; idx[o] = b; idx[o + 1] = b + 1; idx[o + 2] = b + 2; idx[o + 3] = b; idx[o + 4] = b + 2; idx[o + 5] = b + 3; }
quadIBO = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, quadIBO); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.STATIC_DRAW);
dynVBO = gl.createBuffer();
} else $('nogl').classList.remove('hidden');
const IDX_TYPE = () => uintExt ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT;
// ---------------------------------------------------------------- meshing
// vertex: x y z u v sky torch shade
const FACES = [
[1, 0, 0, [1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1], 4, 0.8],
[-1, 0, 0, [0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0], 5, 0.8],
[0, 1, 0, [0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0], 0, 1.0],
[0, -1, 0, [0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1], 1, 0.5],
[0, 0, 1, [0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1], 3, 0.65],
[0, 0, -1, [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0], 2, 0.65],
];
const faceTile = (def, f) => { const tx = def.tex; if (tx.length === 6) return tx[FACES[f][4]]; return f === 2 ? tx[0] : f === 3 ? tx[1] : tx[2]; };
const AO = [0.42, 0.6, 0.8, 1];
const PAD = CS + 2, PAD2 = PAD * PAD;
const pb = new Uint8Array(PAD2 * CH), ph = new Int16Array(PAD2);
let VB = new Float32Array(8 * 4 * 30000), WB = new Float32Array(8 * 4 * 8000);
let vn = 0, wn = 0;
function grow(water) {
if (water) { const n = new Float32Array(WB.length * 2); n.set(WB); WB = n; } else { const n = new Float32Array(VB.length * 2); n.set(VB); VB = n; }
}
// chunk vertices are stored relative to the chunk corner (CX0, CZ0) and placed by uOff at draw time: float32 world
// positions near x 1048576 (the dungeon) are only 1/8 block apart, which made walls wobble, crack and go black
function vert(water, x, y, z, u, v, s, tl, sh) {
x -= CX0; z -= CZ0;
if (water) { if (wn + 8 > WB.length) grow(true); WB[wn++] = x; WB[wn++] = y; WB[wn++] = z; WB[wn++] = u; WB[wn++] = v; WB[wn++] = s; WB[wn++] = tl; WB[wn++] = sh; }
else { if (vn + 8 > VB.length) grow(false); VB[vn++] = x; VB[vn++] = y; VB[vn++] = z; VB[vn++] = u; VB[vn++] = v; VB[vn++] = s; VB[vn++] = tl; VB[vn++] = sh; }
}
const tu = tt => (tt % 16) / 16, tv = tt => (tt >> 4) / 16, EPS = 0.0004, TS = 1 / 16 - EPS * 2;
let torchList = [];
function torchAt(x, y, z) {
let best = 0;
for (let i = 0; i < torchList.length; i += 3) {
const dx = torchList[i] - x, dy = torchList[i + 1] - y, dz = torchList[i + 2] - z;
const d2 = dx * dx + dy * dy + dz * dz; if (d2 > 64) continue;
const l = 1 - Math.sqrt(d2) / 8; if (l > best) best = l;
}
return best;
}
const G = (x, y, z) => y < 0 ? 16 : y >= CH ? 0 : pb[y * PAD2 + (z + 1) * PAD + x + 1];
const SKY = (x, y, z) => { if (y >= CH) return 1; const dd = ph[(z + 1) * PAD + x + 1] - y; return dd < 0 ? 1 : Math.max(0.04, 0.85 - dd * 0.14); };
// box with face culling at block edges, uv taken from the box position inside the tile
function emitBox(water, bx, by, bz, x0, y0, z0, x1, y1, z1, def, sky, tl, onlyFaces) {
const lim = [x0, y0, z0, x1, y1, z1];
for (let f = 0; f < 6; f++) {
if (onlyFaces && !(onlyFaces & (1 << f))) continue;
const F = FACES[f], nx = F[0], ny = F[1], nz = F[2];
const onEdge = (nx === 1 && x1 >= 1) || (nx === -1 && x0 <= 0) || (ny === 1 && y1 >= 1) || (ny === -1 && y0 <= 0) || (nz === 1 && z1 >= 1) || (nz === -1 && z0 <= 0);
if (onEdge && isOpaque[G(bx + nx, by + ny, bz + nz)]) continue;
const tt = faceTile(def, f), u0 = tu(tt) + EPS, v0 = tv(tt) + EPS;
for (let k = 0; k < 4; k++) {
const cx = F[3][k * 3] ? x1 : x0, cy = F[3][k * 3 + 1] ? y1 : y0, cz = F[3][k * 3 + 2] ? z1 : z0;
let u, v;
if (nx === 1) { u = 1 - cz; v = 1 - cy; } else if (nx === -1) { u = cz; v = 1 - cy; }
else if (nz === 1) { u = cx; v = 1 - cy; } else if (nz === -1) { u = 1 - cx; v = 1 - cy; }
else if (ny === 1) { u = cx; v = cz; } else { u = cx; v = 1 - cz; }
vert(water, CX0 + bx + cx, by + cy, CZ0 + bz + cz, u0 + u * TS, v0 + v * TS, sky, tl, F[5]);
}
}
}
let CX0 = 0, CZ0 = 0;
function buildMesh(c) {
const nb = [];
for (let dz = -1; dz <= 1; dz++) for (let dx = -1; dx <= 1; dx++) nb.push(world.chunks.get(E.key(c.cx + dx, c.cz + dz)));
for (let z = -1; z <= CS; z++) for (let x = -1; x <= CS; x++) {
const ncx = x < 0 ? -1 : x >= CS ? 1 : 0, ncz = z < 0 ? -1 : z >= CS ? 1 : 0, n = nb[(ncz + 1) * 3 + ncx + 1];
const lx = x - ncx * CS, lz = z - ncz * CS, pi = (z + 1) * PAD + x + 1;
ph[pi] = n.hm[lz * CS + lx];
for (let y = 0; y < CH; y++) pb[y * PAD2 + pi] = n.b[(y * CS + lz) * CS + lx];
}
CX0 = c.cx * CS; CZ0 = c.cz * CS;
torchList = [];
for (const n of nb) for (let i = 0; i < n.torches.length; i += 3) {
const tx = n.torches[i] + 0.5, tz = n.torches[i + 2] + 0.5;
if (tx > CX0 - 8 && tx < CX0 + CS + 8 && tz > CZ0 - 8 && tz < CZ0 + CS + 8) torchList.push(tx, n.torches[i + 1] + 0.5, tz);
}
vn = 0; wn = 0;
const mapPix = new Uint8ClampedArray(CS * CS * 4);
for (let z = 0; z < CS; z++) for (let x = 0; x < CS; x++) {
let topSeen = false;
for (let y = CH - 1; y >= 0; y--) {
const id = pb[y * PAD2 + (z + 1) * PAD + x + 1];
if (!id) continue;
const def = BLOCKS[id];
if (!topSeen && def.shape !== 'cross' && def.shape !== 'torch') {
topSeen = true;
const col = hexRgb(def.color || '#888'), f = 0.7 + y / CH * 0.6, mi = (z * CS + x) * 4;
mapPix[mi] = col[0] * f; mapPix[mi + 1] = col[1] * f; mapPix[mi + 2] = col[2] * f; mapPix[mi + 3] = 255;
}
const shape = def.shape;
if (shape === 'cube') {
for (let f = 0; f < 6; f++) {
const F = FACES[f], nx = F[0], ny = F[1], nz = F[2], n = G(x + nx, y + ny, z + nz);
if (isOpaque[n] || (n === id && def.cutout)) continue;
const tt = faceTile(def, f), u0 = tu(tt) + EPS, v0 = tv(tt) + EPS;
const lx = x + nx, ly = y + ny, lz = z + nz;
const aos = [0, 0, 0, 0], skys = [0, 0, 0, 0], tls = [0, 0, 0, 0];
for (let k = 0; k < 4; k++) {
const ccx = F[3][k * 3], ccy = F[3][k * 3 + 1], ccz = F[3][k * 3 + 2];
let ax, ay, az, bx2, by2, bz2;
if (nx) { ax = 0; ay = ccy ? 1 : -1; az = 0; bx2 = 0; by2 = 0; bz2 = ccz ? 1 : -1; }
else if (ny) { ax = ccx ? 1 : -1; ay = 0; az = 0; bx2 = 0; by2 = 0; bz2 = ccz ? 1 : -1; }
else { ax = ccx ? 1 : -1; ay = 0; az = 0; bx2 = 0; by2 = ccy ? 1 : -1; bz2 = 0; }
const o1 = isOpaque[G(lx + ax, ly + ay, lz + az)], o2 = isOpaque[G(lx + bx2, ly + by2, lz + bz2)];
const o3 = isOpaque[G(lx + ax + bx2, ly + ay + by2, lz + az + bz2)];
aos[k] = (o1 && o2) ? 0 : 3 - (o1 + o2 + o3);
let s = SKY(lx, ly, lz), cnt = 1;
if (!o1) { s += SKY(lx + ax, ly + ay, lz + az); cnt++; }
if (!o2) { s += SKY(lx + bx2, ly + by2, lz + bz2); cnt++; }
if (!o3 && !(o1 && o2)) { s += SKY(lx + ax + bx2, ly + ay + by2, lz + az + bz2); cnt++; }
skys[k] = s / cnt;
tls[k] = torchList.length ? torchAt(CX0 + x + ccx, y + ccy, CZ0 + z + ccz) : 0;
}
const flip = aos[0] + aos[2] < aos[1] + aos[3];
for (let kk = 0; kk < 4; kk++) {
const k = flip ? (kk + 1) % 4 : kk;
const ccx = F[3][k * 3], ccy = F[3][k * 3 + 1], ccz = F[3][k * 3 + 2];
const uu = (k === 0 || k === 3) ? 0 : 1, vv = (k === 0 || k === 1) ? 1 : 0;
vert(false, CX0 + x + ccx, y + ccy, CZ0 + z + ccz, u0 + uu * TS, v0 + vv * TS, skys[k], tls[k], F[5] * AO[aos[k]]);
}
}
} else if (shape === 'water') {
const above = G(x, y + 1, z), topH = above === 10 ? 1 : 0.875;
for (let f = 0; f < 6; f++) {
const F = FACES[f], n = G(x + F[0], y + F[1], z + F[2]);
if (n === 10 || isOpaque[n] || (f === 3 && n !== 0)) continue;
const tt = def.tex[0], u0 = tu(tt) + EPS, v0 = tv(tt) + EPS, sky = SKY(x + F[0], y + F[1], z + F[2]);
for (let k = 0; k < 4; k++) {
const ccy = F[3][k * 3 + 1] ? topH : 0, uu = (k === 0 || k === 3) ? 0 : 1, vv = (k === 0 || k === 1) ? 1 : 0;
vert(true, CX0 + x + F[3][k * 3], y + ccy, CZ0 + z + F[3][k * 3 + 2], u0 + uu * TS, v0 + vv * TS, sky, 0, F[5]);
}
}
} else {
const sky = SKY(x, y, z), tl = torchList.length ? torchAt(CX0 + x + 0.5, y + 0.5, CZ0 + z + 0.5) : 0;
if (shape === 'cross') {
const tt = def.tex[0], u0 = tu(tt) + EPS, v0 = tv(tt) + EPS, X = CX0 + x, Z = CZ0 + z;
const quads = [[0.15, 0.15, 0.85, 0.85], [0.85, 0.85, 0.15, 0.15], [0.15, 0.85, 0.85, 0.15], [0.85, 0.15, 0.15, 0.85]];
for (const q of quads) {
vert(false, X + q[0], y, Z + q[1], u0, v0 + TS, sky, tl, 0.9); vert(false, X + q[2], y, Z + q[3], u0 + TS, v0 + TS, sky, tl, 0.9);
vert(false, X + q[2], y + 1, Z + q[3], u0 + TS, v0, sky, tl, 0.9); vert(false, X + q[0], y + 1, Z + q[1], u0, v0, sky, tl, 0.9);
}
} else if (shape === 'torch') emitBox(false, x, y, z, 7 / 16, 0, 7 / 16, 9 / 16, 10 / 16, 9 / 16, def, 1, 1, 0);
else if (shape === 'slab' || shape === 'bed') emitBox(false, x, y, z, 0, 0, 0, 1, def.h, 1, def, sky, tl, 0);
else if (shape === 'cactus') emitBox(false, x, y, z, 1 / 16, 0, 1 / 16, 15 / 16, 1, 15 / 16, def, sky, tl, 0);
else if (shape === 'door') {
const thin = 3 / 16, alongX = (def.axis === 'x') !== def.open;
if (alongX) emitBox(false, x, y, z, 0, 0, 0, 1, 1, thin, def, sky, tl, 0);
else emitBox(false, x, y, z, 0, 0, 0, thin, 1, 1, def, sky, tl, 0);
} else if (shape === 'ladder') {
let any = false;
const th = 1 / 16;
if (isOpaque[G(x - 1, y, z)]) { emitBox(false, x, y, z, 0, 0, 0, th, 1, 1, def, sky, tl, 1); any = true; }
if (isOpaque[G(x + 1, y, z)]) { emitBox(false, x, y, z, 1 - th, 0, 0, 1, 1, 1, def, sky, tl, 2); any = true; }
if (isOpaque[G(x, y, z - 1)]) { emitBox(false, x, y, z, 0, 0, 0, 1, 1, th, def, sky, tl, 16); any = true; }
if (isOpaque[G(x, y, z + 1)]) { emitBox(false, x, y, z, 0, 0, 1 - th, 1, 1, 1, def, sky, tl, 32); any = true; }
if (!any) emitBox(false, x, y, z, 0, 0, 0, 1, 1, th, def, sky, tl, 0);
}
}
}
}
// upload
const old = chunkGL.get(E.key(c.cx, c.cz));
const m = old || { cx: c.cx, cz: c.cz, vbo: gl.createBuffer(), wvbo: gl.createBuffer(), n: 0, wn: 0 };
gl.bindBuffer(gl.ARRAY_BUFFER, m.vbo); gl.bufferData(gl.ARRAY_BUFFER, VB.subarray(0, vn), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, m.wvbo); gl.bufferData(gl.ARRAY_BUFFER, WB.subarray(0, wn), gl.STATIC_DRAW);
m.n = Math.min(maxQuads, vn / 32) * 6; m.wn = Math.min(maxQuads, wn / 32) * 6;
chunkGL.set(E.key(c.cx, c.cz), m);
c.dirty = false;
// map tile
const mc = document.createElement('canvas'); mc.width = mc.height = CS;
mc.getContext('2d').putImageData(new ImageData(mapPix, CS, CS), 0, 0);
mapTiles.set(E.key(c.cx, c.cz), mc);
}
// ---------------------------------------------------------------- mob / player models
const HUM = (faceT, headT, shirt, arms, pants, thin) => {
const a = thin ? 0.12 : 0.25, l = thin ? 0.12 : 0.25;
return [
{ b: [-0.25, 1.45, -0.25, 0.25, 1.95, 0.25], f: faceT, o: headT, head: true },
{ b: [-0.25, 0.7, -0.125, 0.25, 1.45, 0.125], f: shirt, o: shirt },
{ b: [-0.25 - a, 0.7, -a / 2, -0.25, 1.45, a / 2], f: arms, o: arms, py: 1.4, sw: 1, arm: true },
{ b: [0.25, 0.7, -a / 2, 0.25 + a, 1.45, a / 2], f: arms, o: arms, py: 1.4, sw: -1, arm: true },
{ b: [-0.25, 0, -l / 2, -0.25 + l, 0.7, l / 2], f: pants, o: pants, py: 0.7, sw: -1 },
{ b: [0.25 - l, 0, -l / 2, 0.25, 0.7, l / 2], f: pants, o: pants, py: 0.7, sw: 1 },
];
};
const QUAD = (bodyB, body, headB, faceT, headO, legH, lx, lz) => {
const legs = [];
[[-lx, lz, 1], [lx - 0.25, lz, -1], [-lx, -lz - 0.25, -1], [lx - 0.25, -lz - 0.25, 1]].forEach(([x0, z0, s]) => legs.push({ b: [x0, 0, z0, x0 + 0.25, legH, z0 + 0.25], f: body, o: body, py: legH, sw: s }));
return [{ b: bodyB, f: body, o: body }, { b: headB, f: faceT, o: headO, head: true }].concat(legs);
};
const MODELS = {
zombie: HUM(T.zombie_face, T.zombie_skin, T.zombie_shirt, T.zombie_skin, T.zombie_pants, false),
skeleton: HUM(T.skeleton_face, T.bone, T.bone, T.bone, T.bone, true),
player: HUM(T.player_face, T.player_hair, T.player_shirt, T.player_skin, T.player_pants, false),
creeper: [{ b: [-0.25, 1.2, -0.25, 0.25, 1.7, 0.25], f: T.creeper_face, o: T.creeper_skin, head: true },
{ b: [-0.25, 0.45, -0.125, 0.25, 1.2, 0.125], f: T.creeper_skin, o: T.creeper_skin },
{ b: [-0.25, 0, 0.125, 0, 0.45, 0.375], f: T.creeper_skin, o: T.creeper_skin, py: 0.45, sw: 1 },
{ b: [0, 0, 0.125, 0.25, 0.45, 0.375], f: T.creeper_skin, o: T.creeper_skin, py: 0.45, sw: -1 },
{ b: [-0.25, 0, -0.375, 0, 0.45, -0.125], f: T.creeper_skin, o: T.creeper_skin, py: 0.45, sw: -1 },
{ b: [0, 0, -0.375, 0.25, 0.45, -0.125], f: T.creeper_skin, o: T.creeper_skin, py: 0.45, sw: 1 }],
spider: (() => {
const m = [{ b: [-0.45, 0.25, -0.9, 0.45, 0.85, -0.1], f: T.spider_body, o: T.spider_body },
{ b: [-0.3, 0.3, -0.1, 0.3, 0.7, 0.3], f: T.spider_body, o: T.spider_body },
{ b: [-0.3, 0.25, 0.3, 0.3, 0.75, 0.75], f: T.spider_face, o: T.spider_body, head: true }];
for (let i = 0; i < 4; i++) { const z = 0.25 - i * 0.18; m.push({ b: [-1.0, 0.45, z - 0.05, -0.3, 0.55, z + 0.05], f: T.spider_body, o: T.spider_body, leg: (i % 2 ? 1 : -1) }); m.push({ b: [0.3, 0.45, z - 0.05, 1.0, 0.55, z + 0.05], f: T.spider_body, o: T.spider_body, leg: (i % 2 ? -1 : 1) }); }
return m;
})(),
pig: QUAD([-0.3, 0.35, -0.45, 0.3, 0.85, 0.45], T.pig_skin, [-0.25, 0.4, 0.45, 0.25, 0.9, 0.85], T.pig_face, T.pig_skin, 0.35, 0.3, 0.2),
cow: QUAD([-0.38, 0.6, -0.55, 0.38, 1.3, 0.55], T.cow_skin, [-0.25, 0.85, 0.55, 0.25, 1.35, 0.9], T.cow_face, T.cow_skin, 0.6, 0.38, 0.3),
sheep: QUAD([-0.38, 0.55, -0.5, 0.38, 1.15, 0.5], T.sheep_wool, [-0.2, 0.85, 0.5, 0.2, 1.25, 0.85], T.sheep_face, T.sheep_wool, 0.55, 0.38, 0.25),
cat: QUAD([-0.17, 0.22, -0.35, 0.17, 0.48, 0.3], T.cat_skin, [-0.16, 0.32, 0.28, 0.16, 0.62, 0.55], T.cat_face, T.cat_skin, 0.24, 0.17, 0.18)
.concat([{ b: [-0.04, 0.4, -0.7, 0.04, 0.48, -0.35], f: T.cat_skin, o: T.cat_skin }]),
dog: QUAD([-0.22, 0.38, -0.45, 0.22, 0.74, 0.35], T.dog_skin, [-0.18, 0.5, 0.33, 0.18, 0.86, 0.72], T.dog_face, T.dog_skin, 0.4, 0.22, 0.2)
.concat([{ b: [-0.04, 0.62, -0.7, 0.04, 0.7, -0.45], f: T.dog_skin, o: T.dog_skin }]),
wolf: QUAD([-0.24, 0.42, -0.5, 0.24, 0.8, 0.38], T.wolf_skin, [-0.2, 0.56, 0.36, 0.2, 0.94, 0.78], T.wolf_face, T.wolf_skin, 0.44, 0.24, 0.22)
.concat([{ b: [-0.06, 0.6, -0.85, 0.06, 0.74, -0.48], f: T.wolf_skin, o: T.wolf_skin }]), // white wolf: a bigger dog with a bushy tail
trex: (() => { const S = T.trex_skin; return [
{ b: [-0.55, 1.4, -1.0, 0.55, 2.4, 0.9], f: S, o: S },
{ b: [-0.45, 2.1, 0.8, 0.45, 2.9, 2.0], f: T.trex_face, o: S, head: true },
{ b: [-0.4, 1.85, 0.9, 0.4, 2.1, 1.9], f: S, o: S },
{ b: [-0.3, 1.6, -2.6, 0.3, 2.2, -1.0], f: S, o: S },
{ b: [-0.15, 1.75, -3.6, 0.15, 2.05, -2.6], f: S, o: S },
{ b: [-0.55, 0, -0.3, -0.15, 1.5, 0.2], f: S, o: S, py: 1.5, sw: 1 },
{ b: [0.15, 0, -0.3, 0.55, 1.5, 0.2], f: S, o: S, py: 1.5, sw: -1 },
{ b: [-0.45, 1.55, 0.85, -0.3, 1.7, 1.25], f: S, o: S },
{ b: [0.3, 1.55, 0.85, 0.45, 1.7, 1.25], f: S, o: S }]; })(),
raptor: (() => { const S = T.raptor_skin; return [
{ b: [-0.25, 0.7, -0.5, 0.25, 1.1, 0.4], f: S, o: S },
{ b: [-0.18, 1.0, 0.35, 0.18, 1.3, 0.85], f: T.raptor_face, o: S, head: true },
{ b: [-0.1, 0.8, -1.3, 0.1, 1.0, -0.5], f: S, o: S },
{ b: [-0.22, 0, -0.1, -0.07, 0.75, 0.08], f: S, o: S, py: 0.75, sw: 1 },
{ b: [0.07, 0, -0.1, 0.22, 0.75, 0.08], f: S, o: S, py: 0.75, sw: -1 }]; })(),
trike: (() => { const S = T.trike_skin, H = T.bone; const m = [
{ b: [-0.65, 0.6, -1.0, 0.65, 1.5, 0.9], f: S, o: S },
{ b: [-0.45, 0.6, 0.9, 0.45, 1.3, 1.6], f: T.trike_face, o: S, head: true },
{ b: [-0.75, 0.9, 0.82, 0.75, 1.9, 0.97], f: S, o: S },
{ b: [-0.35, 1.15, 1.6, -0.25, 1.25, 2.15], f: H, o: H },
{ b: [0.25, 1.15, 1.6, 0.35, 1.25, 2.15], f: H, o: H },
{ b: [-0.05, 0.85, 1.6, 0.05, 0.95, 1.9], f: H, o: H },
{ b: [-0.2, 0.8, -1.8, 0.2, 1.1, -1.0], f: S, o: S }];
[[-0.65, 0.5, 1], [0.35, 0.5, -1], [-0.65, -0.9, -1], [0.35, -0.9, 1]].forEach(([x, z, s]) => m.push({ b: [x, 0, z, x + 0.3, 0.65, z + 0.3], f: S, o: S, py: 0.65, sw: s }));
return m; })(),
brachio: (() => { const S = T.brachio_skin; const m = [
{ b: [-0.7, 1.6, -1.2, 0.7, 2.8, 1.0], f: S, o: S },
{ b: [-0.25, 2.4, 0.8, 0.25, 5.0, 1.3], f: S, o: S },
{ b: [-0.3, 4.8, 1.0, 0.3, 5.3, 1.8], f: T.brachio_face, o: S, head: true },
{ b: [-0.25, 1.9, -3.0, 0.25, 2.4, -1.2], f: S, o: S }];
[[-0.7, 0.5, 1], [0.25, 0.5, -1], [-0.7, -1.1, -1], [0.25, -1.1, 1]].forEach(([x, z, s]) => m.push({ b: [x, 0, z, x + 0.45, 1.65, z + 0.45], f: S, o: S, py: 1.65, sw: s }));
return m; })(),
};
const MB = new Float32Array(8 * 4 * 6 * 20);
function drawModel(boxes, x, y, z, yaw, walk, pitch, tint, armsForward, scale) {
const sky = world.skyAt(Math.floor(x), Math.floor(y + 1), Math.floor(z)), tl = world.torchLightAt(x, y + 1, z);
let n = 0;
const cy = Math.cos(yaw), sy = Math.sin(yaw), s = scale || 1;
for (const bx of boxes) {
let ang = 0, piv = 0;
if (bx.sw) { ang = Math.sin(walk) * 0.7 * bx.sw; piv = bx.py; }
if (bx.arm && armsForward) ang = -1.45 + Math.sin(walk) * 0.15 * bx.sw;
if (bx.head && pitch) { ang = -pitch; piv = bx.b[1]; }
const ca = Math.cos(ang), sa = Math.sin(ang), b = bx.b;
for (let f = 0; f < 6; f++) {
const F = FACES[f], tt = f === 4 ? bx.f : bx.o, u0 = tu(tt) + EPS, v0 = tv(tt) + EPS;
for (let k = 0; k < 4; k++) {
let lx = F[3][k * 3] ? b[3] : b[0], ly = F[3][k * 3 + 1] ? b[4] : b[1], lz = F[3][k * 3 + 2] ? b[5] : b[2];
if (bx.leg) { lz += Math.sin(walk + bx.leg) * 0.12 * (Math.abs(lx) > 0.5 ? 1 : 0); }
if (ang) { const yy = ly - piv, zz = lz; ly = piv + yy * ca - zz * sa; lz = yy * sa + zz * ca; }
lx *= s; ly *= s; lz *= s;
const wx = lx * cy + lz * sy, wz = -lx * sy + lz * cy;
const uu = (k === 0 || k === 3) ? 0 : 1, vv = (k === 0 || k === 1) ? 1 : 0;
MB[n++] = x - RO[0] + wx; MB[n++] = y + ly; MB[n++] = z - RO[2] + wz; MB[n++] = u0 + uu * TS; MB[n++] = v0 + vv * TS; MB[n++] = sky; MB[n++] = tl; MB[n++] = F[5];
}
}
}
gl.bindBuffer(gl.ARRAY_BUFFER, dynVBO); gl.bufferData(gl.ARRAY_BUFFER, MB.subarray(0, n), gl.DYNAMIC_DRAW);
bindAttribs();
gl.uniform4fv(prog.u.uTint, tint || [0, 0, 0, 0]);
gl.drawElements(gl.TRIANGLES, n / 32 * 6, IDX_TYPE(), 0);
}
// ---------------------------------------------------------------- vehicle models (nose towards +z, drawn with yaw + PI like players)
// spin: 'x' | 'y' | 'z' turns that box around its own centre (propeller, rotors)
function vehicleBoxes(kind, paint, pilot) {
const S = T['paint' + paint], W = T.plane_wing, M = T.metal, G = T.cockpit, R = T.rotor;
const bx = (b, f, o, spin) => ({ b, f, o: o == null ? f : o, spin });
let m, seat;
if (kind === 'jet' || kind === 'stunt' || kind === 'spy') { // jets: long pointy body, swept wings, two tail fins, no propeller
const B = kind === 'spy' ? T.wool_black : kind === 'stunt' ? T.paint0 : M, Wg = kind === 'stunt' ? T.wool_white : kind === 'spy' ? T.wool_black : W;
m = [bx([-0.45, 0.5, -2.6, 0.45, 1.2, 1.8], B), bx([-0.3, 0.6, 1.8, 0.3, 1.05, 2.6], B), bx([-0.12, 0.72, 2.6, 0.12, 0.92, 2.95], M),
bx([-0.36, 1.2, 0.2, 0.36, 1.6, 1.3], G),
bx([-1.0, 0.8, -0.8, 1.0, 0.92, 0.6], Wg), bx([-2.0, 0.8, -1.4, 2.0, 0.92, -0.6], Wg), bx([-2.6, 0.8, -1.8, 2.6, 0.92, -1.4], Wg),
bx([-2.6, 0.82, -1.8, -2.2, 0.94, -1.4], S), bx([2.2, 0.82, -1.8, 2.6, 0.94, -1.4], S), // owner's colour on the wing tips
bx([-0.42, 1.1, -2.6, -0.32, 1.9, -1.9], B), bx([0.32, 1.1, -2.6, 0.42, 1.9, -1.9], B), // twin tail fins
bx([-1.2, 0.85, -2.6, 1.2, 0.95, -2.1], Wg), bx([-0.3, 0.55, -2.75, 0.3, 1.0, -2.6], R, M), // tail wings, engine
bx([-0.6, 0, 0.1, -0.45, 0.5, 0.3], R, M), bx([0.45, 0, 0.1, 0.6, 0.5, 0.3], R, M), bx([-0.08, 0, 1.8, 0.08, 0.5, 2.0], R, M)];
seat = [0.3, 0.75];
} else if (kind === 'plane') {
m = [bx([-0.45, 0.5, -2.2, 0.45, 1.3, 1.6], S), bx([-0.35, 0.6, 1.6, 0.35, 1.2, 2.0], M),
bx([-0.95, 0.86, 2.02, 0.95, 0.94, 2.1], R, R, 'z'), bx([-0.38, 1.3, 0.0, 0.38, 1.8, 0.9], G),
bx([-2.7, 0.95, 0.1, 2.7, 1.1, 1.1], W), bx([-2.7, 0.96, 0.1, -2.2, 1.11, 1.1], S), bx([2.2, 0.96, 0.1, 2.7, 1.11, 1.1], S),
bx([-1.1, 1.1, -2.2, 1.1, 1.2, -1.6], W), bx([-0.06, 1.2, -2.2, 0.06, 2.0, -1.5], S),
bx([-0.85, 0, 0.6, -0.55, 0.5, 0.9], R, M), bx([0.55, 0, 0.6, 0.85, 0.5, 0.9], R, M), bx([-0.1, 0.25, -2.0, 0.1, 0.5, -1.8], R, M)];
seat = [0.15, 0.85];
} else {
m = [bx([-0.7, 0.4, -0.8, 0.7, 1.9, 1.0], S), bx([-0.65, 0.55, 1.0, 0.65, 1.8, 1.6], G),
bx([-0.15, 1.1, -3.4, 0.15, 1.4, -0.8], S), bx([-0.05, 1.1, -3.7, 0.05, 2.0, -3.3], S),
bx([0.08, 1.05, -3.75, 0.14, 2.05, -3.25], R, R, 'x'),
bx([-0.08, 1.9, -0.08, 0.08, 2.2, 0.08], M),
bx([-3.0, 2.2, -0.15, 3.0, 2.28, 0.15], R, R, 'y'), bx([-0.15, 2.2, -3.0, 0.15, 2.28, 3.0], R, R, 'y'),
bx([-0.8, 0, -0.9, -0.62, 0.1, 1.2], M), bx([0.62, 0, -0.9, 0.8, 0.1, 1.2], M),
bx([-0.72, 0.1, 0.4, -0.64, 0.4, 0.5], M), bx([0.64, 0.1, 0.4, 0.72, 0.4, 0.5], M)];
seat = [0.65, 1.05];
}
if (pilot) { const y = seat[0], z = seat[1];
m.push(bx([-0.22, y + 0.5, z - 0.22, 0.22, y + 0.94, z + 0.22], T.player_face, T.player_hair), bx([-0.25, y, z - 0.15, 0.25, y + 0.5, z + 0.15], T.player_shirt)); }
return m;
}
const VB2 = new Float32Array(8 * 4 * 6 * 24);
function drawVehicle(boxes, x, y, z, yaw, pitch, roll, spin) {
const sky = world.skyAt(Math.floor(x), Math.floor(y + 1), Math.floor(z)), tl = world.torchLightAt(x, y + 1, z);
const cy = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(pitch), sp = Math.sin(pitch), cr = Math.cos(roll), sr = Math.sin(roll);
const cs = Math.cos(spin), ss = Math.sin(spin), PY = 0.9; // tilt around the middle of the body
let n = 0;
for (const bx of boxes) {
const b = bx.b, mx = (b[0] + b[3]) / 2, my = (b[1] + b[4]) / 2, mz = (b[2] + b[5]) / 2;
for (let f = 0; f < 6; f++) {
const F = FACES[f], tt = f === 4 ? bx.f : bx.o, u0 = tu(tt) + EPS, v0 = tv(tt) + EPS;
for (let k = 0; k < 4; k++) {
let lx = F[3][k * 3] ? b[3] : b[0], ly = F[3][k * 3 + 1] ? b[4] : b[1], lz = F[3][k * 3 + 2] ? b[5] : b[2];
if (bx.spin === 'y') { const ax = lx - mx, az = lz - mz; lx = mx + ax * cs - az * ss; lz = mz + ax * ss + az * cs; }
else if (bx.spin === 'z') { const ax = lx - mx, ay = ly - my; lx = mx + ax * cs - ay * ss; ly = my + ax * ss + ay * cs; }
else if (bx.spin === 'x') { const ay = ly - my, az = lz - mz; ly = my + ay * cs - az * ss; lz = mz + ay * ss + az * cs; }
ly -= PY;
let ax = lx * cr - ly * sr, ay = lx * sr + ly * cr; // roll (around the nose axis)
const by = ay * cp + lz * sp, bz = -ay * sp + lz * cp; // pitch (nose up when > 0)
const wx = ax * cy + bz * sy, wz = -ax * sy + bz * cy; // yaw
const uu = (k === 0 || k === 3) ? 0 : 1, vv = (k === 0 || k === 1) ? 1 : 0;
VB2[n++] = x - RO[0] + wx; VB2[n++] = y + by + PY; VB2[n++] = z - RO[2] + wz; VB2[n++] = u0 + uu * TS; VB2[n++] = v0 + vv * TS; VB2[n++] = sky; VB2[n++] = tl; VB2[n++] = F[5];
}
}
}
gl.bindBuffer(gl.ARRAY_BUFFER, dynVBO); gl.bufferData(gl.ARRAY_BUFFER, VB2.subarray(0, n), gl.DYNAMIC_DRAW);
bindAttribs();
gl.uniform4fv(prog.u.uTint, [0, 0, 0, 0]);
gl.drawElements(gl.TRIANGLES, n / 32 * 6, IDX_TYPE(), 0);
}
function bindAttribs() {
gl.vertexAttribPointer(prog.a.p, 3, gl.FLOAT, false, 32, 0);
gl.vertexAttribPointer(prog.a.t, 2, gl.FLOAT, false, 32, 12);
gl.vertexAttribPointer(prog.a.l, 3, gl.FLOAT, false, 32, 20);
}
// ---------------------------------------------------------------- matrices
function perspective(fov, asp, n, f) { const t = 1 / Math.tan(fov / 2), nf = 1 / (n - f); return [t / asp, 0, 0, 0, 0, t, 0, 0, 0, 0, (f + n) * nf, -1, 0, 0, 2 * f * n * nf, 0]; }
function mul(a, b) { const o = new Array(16); for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) { let s = 0; for (let k = 0; k < 4; k++) s += a[k * 4 + r] * b[c * 4 + k]; o[c * 4 + r] = s; } return o; }
function viewMat(yaw, pitch, ex, ey, ez) {
const r = [Math.cos(yaw), 0, -Math.sin(yaw)];
const f = [-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)];
const b = [-f[0], -f[1], -f[2]];
const u = [b[1] * r[2] - b[2] * r[1], b[2] * r[0] - b[0] * r[2], b[0] * r[1] - b[1] * r[0]];
return [r[0], u[0], b[0], 0, r[1], u[1], b[1], 0, r[2], u[2], b[2], 0,
-(r[0] * ex + r[1] * ey + r[2] * ez), -(u[0] * ex + u[1] * ey + u[2] * ez), -(b[0] * ex + b[1] * ey + b[2] * ez), 1];
}
const fwd = () => [-Math.sin(pl.yaw) * Math.cos(pl.pitch), Math.sin(pl.pitch), -Math.cos(pl.yaw) * Math.cos(pl.pitch)];
// ---------------------------------------------------------------- game state
let world = null, sim = null, link = null, pl = null, session = null, state = 'menu';
const chunkGL = new Map(), mapTiles = new Map();
let inv = new Array(36).fill(null), sel = 0;
let mobs = new Map(), arrows = [], tnts = [], others = new Map(), myId = 1, simTime = 0.1;
let target = null, breakT = 0, breakKey = '', attackCool = 0, useCool = 0, hurtFlash = 0, shake = 0, toastT = 0;
let moveSend = 0, saveTimer = 0, stepT = 0, groanT = 5, lastJumpTap = 0;
let vehicles = new Map(), ride = null, vSend = 0, myName = 'You', inSafe = false, myPets = null, airfields = []; // myPets: { pets: [{ kind, name, lvl, xp, food }], slots, fed } from the server
const SPIRAL = []; for (let dz = -8; dz <= 8; dz++) for (let dx = -8; dx <= 8; dx++) SPIRAL.push([dx, dz, dx * dx + dz * dz]);
SPIRAL.sort((a, b) => a[2] - b[2]);
function toast(msg, secs) { $('toast').textContent = msg; toastT = secs || 3; }
function newPlayer(pos, mode) {
return { x: pos.x, y: pos.y, z: pos.z, vx: 0, vy: 0, vz: 0, w: 0.6, h: 1.8, yaw: 0, pitch: -0.2, onGround: false, fly: false,
hp: 20, food: 20, air: 10, fallY: null, spawn: null, fuel: 0, mode: mode || 'survival', dead: false,
fx: {}, armor: [null, null, null, null] }; // fx: potion effects (seconds left); armor: helmet, chestplate, leggings, boots item ids
}
const creative = () => pl && pl.mode === 'creative';
const FX_NAMES = { regen: 'REGENERATION', str: 'STRENGTH', speed: 'SPEED', jump: 'JUMP', shield: 'SHIELD', night: 'NIGHT VISION', water: 'WATER BREATHING' };
const armorPts = () => pl.armor.reduce((a, id) => a + (id ? ITEMS[id].pts : 0), 0);
const hasBoots = id => pl.armor[3] === id;
function drink(it) { // potions and the golden apple
const healer = H().cls === 'healer';
if (it.heal) { pl.hp = Math.min(maxHp(), pl.hp + it.heal); }
if (it.potion === 'heal') pl.hp = Math.min(maxHp(), pl.hp + (healer ? 16 : 8));
const fx = it.potion && it.potion !== 'heal' ? it.potion : it.fx, secs = it.secs * (healer && it.potion ? 2 : 1);
if (fx) { pl.fx[fx] = Math.max(pl.fx[fx] || 0, secs); toast(FX_NAMES[fx] + ' for ' + secs + ' seconds!'); }
if (it.potion) earn('potion');
else if (it.potion) toast('+4 hearts');
hurtFlash = 0; lastStats = '';
}
// ---------------------------------------------------------------- hero: XP, levels, class, points, achievements, loot boxes
// Kept with the player (saved in the single-player world, or on the family server with the bag).
const H = () => pl.hero || (pl.hero = { xp: 0, lvl: 1, cls: '', pts: { str: 0, spd: 0, hp: 0 }, free: 0, ach: {}, cnt: {}, fruit: {}, castles: {}, deepest: 0 });
const CLASSES = {
warrior: { name: 'WARRIOR', about: 'Hits 50% harder and has 2 extra hearts' },
archer: { name: 'ARCHER', about: 'Arrows do double damage, and half the time the arrow is free' },
healer: { name: 'HEALER', about: 'Always heals slowly; potions heal double and last twice as long' },
explorer: { name: 'EXPLORER', about: 'Runs 25% faster, falls of 8 blocks don\'t hurt, sees a little in the dark' },
};
const maxHp = () => { if (!pl) return 20; const h = H(); return 20 + h.pts.hp * 2 + (h.cls === 'warrior' ? 4 : 0); };
const xpNeed = lvl => 20 + lvl * 15;
const meleeBoost = () => (1 + H().pts.str * 0.1) * (H().cls === 'warrior' ? 1.5 : 1);
const speedBoost = () => (1 + Math.min(10, H().pts.spd) * 0.06) * (H().cls === 'explorer' ? 1.25 : 1);
function addXp(n) {
const h = H(); if (!n) return;
h.xp += n;
while (h.xp >= xpNeed(h.lvl)) {
h.xp -= xpNeed(h.lvl); h.lvl++; h.free++;
pl.hp = maxHp(); lastStats = '';
announce('LEVEL ' + h.lvl + '!', 'You got a point to spend. Tap HERO to make yourself stronger, faster or tougher.', '#55FF55');
if (h.lvl === 3) { const pet = 194 + Math.floor(Math.random() * 3); giveDrops([[pet, 1]]); announce('A PET IS WAITING FOR YOU!', 'You got a ' + E.itemName(pet) + '. Tap it to meet your new best friend.', '#FFAA00'); }
if (h.lvl === 5) earn('level5'); if (h.lvl === 10) earn('level10');
}
if (state === 'hero') renderHero();
}
// achievements: [title, how to get it, tier 0 bronze .. 3 legendary, the announcer's comment]
const ACH = {
first_blood: ['Monster Masher', 'Defeat your first monster', 0, 'One down. Several thousand to go.'],
zombie10: ['Zombie Zapper', 'Defeat 10 zombies', 1, 'The zombies have started a support group about you.'],
skeleton10: ['Bone Collector', 'Defeat 10 skeletons', 1, 'That is a lot of spare ribs.'],
spider5: ['Web Wrecker', 'Defeat 5 spiders', 0, 'Eight legs were not enough to run away.'],
kaboom: ['Kaboom Club', 'Get caught in an explosion', 0, 'Your eyebrows will grow back. Probably.'],
dino_snack: ['Dino Snack', 'Get bitten by a T-Rex', 0, 'The T-Rex says you taste like chicken.'],
trex_down: ['Bigger Teeth', 'Defeat a T-Rex', 2, 'Who is the top of the food chain now?'],
shiny: ['Shiny!', 'Dig up your first diamond', 0, 'Ooooh. Shiny.'],
jewel: ['Jewel Thief', 'Find a jewel', 1, 'Finders keepers.'],
castle: ['Knock Knock', 'Find a castle', 0, 'Nobody was home. Their treasure is now your treasure.'],
royal: ['Royal Visitor', 'Find a Royal Castle', 1, 'Please wipe your feet on the royal carpet.'],
all_castles: ['Castle Collector', 'Visit all five kinds of castle', 2, 'You have seen more castles than most kings.'],
kit: ['Home Sweet Castle', 'Build a castle from a kit', 2, 'Property values in this area just went up.'],
fly: ['Up Up and Away', 'Fly an airplane or helicopter', 1, 'Please keep your arms inside the vehicle.'],
potion: ['Bottoms Up', 'Drink a potion', 0, 'It tastes like purple. Or maybe green.'],
boots: ['Shiny Shoes', 'Wear Diamond Boots', 1, 'Gravity is no longer your problem.'],
full_diamond: ['Diamond Hero', 'Wear a full set of diamond armor', 2, 'You sparkle when you walk. It is a little distracting.'],
oops: ['Oopsie Daisy', 'Get defeated for the first time', 0, 'It happens to the best of heroes. Get back up!'],
gravity: ['Gravity Wins', 'Get hurt by a fall', 0, 'The ground was closer than it looked.'],
level5: ['Getting Stronger', 'Reach level 5', 1, 'The monsters have started to whisper your name.'],
level10: ['Hero of the Realm', 'Reach level 10', 2, 'Statues are being built in your honor. Small ones.'],
pet: ['Best Friends', 'Get a pet', 1, 'Every hero needs a sidekick.'],
pet_win: ['Good Pet!', 'Your pet defeats a monster', 0, 'Your pet would like a treat now, please.'],
dungeon: ['Going Down', 'Enter the dungeon', 0, 'Welcome, crawler. Mind the monsters.'],
safe: ['Phew!', 'Rest in a safe room', 0, 'Nothing can get you in here. Probably.'],
boss: ['Floor Boss Down', 'Defeat a floor boss', 2, 'The crowd goes wild! Well, the bats do.'],
floor3: ['Deeper and Deeper', 'Reach Floor 3', 1, 'It is getting darker. And smellier.'],
floor5: ['Crawler Champion', 'Reach Floor 5', 3, 'Legends will be told about this. Mostly by you.'],
box: ['Box Opener', 'Open a loot box', 0, 'What is inside? Prizes! Mostly.'],
legendary: ['Legendary!', 'Open a Legendary Loot Box', 2, 'The rarest box of all. Show off a little.'],
fruit: ['Fruit Salad', 'Eat 5 different kinds of fruit', 1, 'An apple a day keeps the zombies away.'],
};
// fairy tale kingdom add-on: one per tale quest, plus visiting and finishing them all
ACH.kingdom = ['Once Upon a Time', 'Visit the Fairy Tale Kingdom', 0, 'And they all lived happily ever after. Probably.'];
E.TALES.forEach(T => { ACH['tale_' + T.id] = [T.ach[0], 'Finish the quest at ' + T.place, 1, T.ach[1]]; });
ACH.all_tales = ['Storybook Legend', 'Finish all ten fairy tale quests', 3, 'Someone should write a book about you.'];
const TIER_NAMES = ['BRONZE', 'SILVER', 'GOLD', 'LEGENDARY'], TIER_COL = ['#d0884a', '#d8dee6', '#f5d742', '#d080ff'], TIER_XP = [10, 25, 60, 150];
// always: fairy tale achievements also count in Creative (the reading in ABC Books was the hard part)
function earn(id, always) {
const h = H(), a = ACH[id];
if (!a || h.ach[id] || !pl || (pl.mode === 'creative' && !always)) return;
h.ach[id] = Date.now();
announce('NEW ACHIEVEMENT: ' + a[0].toUpperCase() + '!', a[1] + '. ' + a[3] + '\nReward: ' + TIER_NAMES[a[2]] + ' Loot Box (tap it to open)', TIER_COL[a[2]]);
giveDrops([[190 + a[2], 1]]); addXp(TIER_XP[a[2]]);
}
const count = (k, n) => { const h = H(); h.cnt[k] = (h.cnt[k] || 0) + (n || 1); return h.cnt[k]; };
// the announcer: big banners at the top, one after another
const announceQ = []; let announceT = 0;
function announce(title, text, color, secs) { announceQ.push([title, text, color, secs]); if (announceQ.length === 1 && announceT <= 0) nextAnnounce(); }
function nextAnnounce() {
const a = announceQ[0], el = $('announce');
if (!a) { el.classList.add('hidden'); return; }
el.querySelector('b').textContent = a[0]; el.querySelector('b').style.color = a[2] || '#FFFF55';
el.querySelector('span').textContent = a[1]; el.style.borderColor = a[2] || '#FFFF55';
el.classList.remove('hidden'); announceT = a[3] || 4.5; if (!a[3]) sfx('fanfare'); // secs: a story stone, read out loud (no fanfare)
}
function tickAnnounce(dt) { if (announceT > 0) { announceT -= dt; if (announceT <= 0) { announceQ.shift(); nextAnnounce(); } } }
// loot boxes: random prizes, better boxes give better prizes
function openBox(tier) {
const R = (a, b) => a + Math.floor(Math.random() * (b - a + 1)), pick = a => a[Math.floor(Math.random() * a.length)];
const potion = () => 160 + R(0, 7), jewel = () => 147 + R(0, 3), fruit = () => pick([105, 152, 153, 154, 155, 156, 157]);
const pools = [
() => pick([[105, 3], [22, 8], [112, 8], [102, 3], [160, 1], [155, 3], [101, 5], [146, 2], [fruit(), 3]]),
() => pick([[103, 4], [102, 6], [104, R(1, 2)], [potion(), 1], [jewel(), 1], [146, 4], [151, 1], [fruit(), 4]]),
() => pick([[104, R(3, 5)], [jewel(), 2], [potion(), 2], [151, 1], [170 + R(0, 7), 1], [182, 1], [57, 1], [potion(), 1]]),
() => pick([[104, 8], [jewel(), 3], [178 + R(0, 3), 1], [183 + R(0, 4), 1], [194 + R(0, 2), 1], [162, 2], [165, 2], [53, 2], [151, 3]]),
];
const items = []; for (let i = 0; i < 2 + tier; i++) items.push(pools[tier]());
if (tier === 3 && Math.random() < 0.5) items.push([194 + R(0, 2), 1]);
if (tier >= 1 && Math.random() < 0.25) items.push(pools[tier - 1]());
giveDrops(items);
announce(TIER_NAMES[tier] + ' LOOT BOX!', 'You got: ' + items.map(([id, n]) => (n > 1 ? n + ' ' : '') + E.itemName(id)).join(', '), TIER_COL[tier]);
addXp([5, 15, 40, 100][tier]); earn('box'); if (tier === 3) earn('legendary');
}
function wearArmor(i) { // put the bag slot's armor on (swapping with what was worn)
const s = inv[i], it = s && ITEMS[s.id]; if (!it || it.armor == null) return false;
const old = pl.armor[it.armor]; pl.armor[it.armor] = s.id; inv[i] = old ? { id: old, n: 1 } : null;
sfx('door'); toast('Wearing ' + it.name + (s.id === 181 ? '\nNo more fall damage!' : '')); renderHotbar(); lastStats = '';
if (pl.armor[3] === 181) earn('boots');
if (pl.armor.every((a, k) => a === 178 + k)) earn('full_diamond');
return true;
}
function clientOnChange(x, y, z, old, id) {
const cx = Math.floor(x / CS), cz = Math.floor(z / CS), lx = x - cx * CS, lz = z - cz * CS;
const big = blk(old).light || blk(id).light;
for (let dz = -1; dz <= 1; dz++) for (let dx = -1; dx <= 1; dx++) {
if (!big && !((dx === 0 || (dx === -1 && lx === 0) || (dx === 1 && lx === CS - 1)) && (dz === 0 || (dz === -1 && lz === 0) || (dz === 1 && lz === CS - 1)))) continue;
const c = world.chunks.get(E.key(cx + dx, cz + dz)); if (c) c.dirty = true;
}
}
// ---------------------------------------------------------------- chunk loading
let lastUnload = 0;
function updateChunks(budget) {
const pcx = Math.floor(pl.x / CS), pcz = Math.floor(pl.z / CS), R = cfg.dist, t0 = performance.now();
let gens = 0;
for (const [dx, dz, d2] of SPIRAL) {
if (d2 > (R + 1.5) * (R + 1.5)) break;
if (!world.chunks.has(E.key(pcx + dx, pcz + dz))) { world.chunk(pcx + dx, pcz + dz, true); if (++gens >= 2 || performance.now() - t0 > budget) break; }
}
for (const [dx, dz, d2] of SPIRAL) {
if (d2 > (R + 0.5) * (R + 0.5)) break;
if (performance.now() - t0 > budget) break;
const c = world.chunks.get(E.key(pcx + dx, pcz + dz));
if (!c || !c.dirty) continue;
let ok = true;
for (let a = -1; a <= 1 && ok; a++) for (let b = -1; b <= 1; b++) if (!world.chunks.has(E.key(c.cx + a, c.cz + b))) { ok = false; break; }
if (ok) buildMesh(c);
}
const now = performance.now();
if (now - lastUnload > 2000) {
lastUnload = now;
for (const [k, m] of chunkGL) if (Math.abs(m.cx - pcx) > R + 2 || Math.abs(m.cz - pcz) > R + 2) { gl.deleteBuffer(m.vbo); gl.deleteBuffer(m.wvbo); chunkGL.delete(k); const c = world.chunks.get(k); if (c) c.dirty = true; }
for (const [k, c] of world.chunks) if (Math.abs(c.cx - pcx) > R + 4 || Math.abs(c.cz - pcz) > R + 4) world.chunks.delete(k);
}
}
function nearReady() {
const pcx = Math.floor(pl.x / CS), pcz = Math.floor(pl.z / CS);
for (let dz = -1; dz <= 1; dz++) for (let dx = -1; dx <= 1; dx++) if (!chunkGL.has(E.key(pcx + dx, pcz + dz))) return false;
return true;
}
// ---------------------------------------------------------------- inventory helpers
const maxDur = id => (ITEMS[id] && ITEMS[id].dur) || 0;
function addItem(id, n) {
const st = E.stackSize(id);
for (let i = 0; i < 36 && n > 0; i++) { const s = inv[i]; if (s && s.id === id && s.n < st) { const k = Math.min(n, st - s.n); s.n += k; n -= k; } }
for (let i = 0; i < 36 && n > 0; i++) if (!inv[i]) { const k = Math.min(n, st); inv[i] = { id, n: k }; if (maxDur(id)) inv[i].d = maxDur(id); n -= k; }
renderHotbar(); if (state === 'inv') renderInv();
return n;
}
const countItem = id => inv.reduce((a, s) => a + (s && s.id === id ? s.n : 0), 0);
function removeItem(id, n) {
for (let i = 35; i >= 0 && n > 0; i--) { const s = inv[i]; if (s && s.id === id) { const k = Math.min(n, s.n); s.n -= k; n -= k; if (!s.n) inv[i] = null; } }
renderHotbar();
}
function useHeld() { const s = inv[sel]; if (!s || creative()) return; s.n--; if (s.n <= 0) inv[sel] = null; renderHotbar(); }
function wearTool() {
const s = inv[sel]; if (!s || !maxDur(s.id) || creative()) return;
s.d = (s.d || maxDur(s.id)) - 1;
if (s.d <= 0) { inv[sel] = null; sfx('tool'); toast(E.itemName(s.id) + ' broke!'); }
renderHotbar();
}
function giveDrops(items) {
const names = [];
for (const [id, n] of items) { const left = addItem(id, n); if (left < n) names.push('+' + (n - left) + ' ' + E.itemName(id)); }
if (names.length) { sfx('pop'); toast(names.join('\n')); }
}
// ---------------------------------------------------------------- HUD
function slotHTML(s, extra) {
if (!s) return '<div class="slot ' + (extra || '') + '"></div>';
const md = maxDur(s.id), dur = md && s.d != null && s.d < md ? '<div class="dur" style="width:' + (80 * s.d / md) + '%;background:' + (s.d / md > 0.3 ? '#0c0' : '#e22') + '"></div>' : '';
return '<div class="slot ' + (extra || '') + '"><img src="' + iconFor(s.id) + '" alt="">' + (s.n > 1 ? '<span class="n">' + s.n + '</span>' : '') + dur + '</div>';
}
function renderHotbar() {
let h = '';
for (let i = 0; i < 9; i++) h += slotHTML(inv[i], i === sel ? 'sel' : '').replace('class="slot', 'data-i="' + i + '" class="slot');
$('hotbar').innerHTML = h;
}
$('hotbar').addEventListener('pointerdown', e => { const el = e.target.closest('.slot'); if (el) { sel = +el.dataset.i; renderHotbar(); showHeldName(); } e.stopPropagation(); });
function showHeldName() { const s = inv[sel]; if (s) toast(E.itemName(s.id)); }
let lastStats = '';
function renderStats() {
if (creative() || !pl) { if (lastStats !== 'c') { $('stats').style.visibility = 'hidden'; lastStats = 'c'; } return; }
const hp = Math.ceil(pl.hp), fd = Math.ceil(pl.food), air = pl.air < 10 ? Math.ceil(pl.air) : -1;
const ap = Math.ceil(armorPts() / 2);
const mh = maxHp() / 2;
const key = hp + ',' + fd + ',' + air + ',' + ap + ',' + mh; if (key === lastStats) return; lastStats = key;
$('armorbar').textContent = ap ? '◆'.repeat(ap) : '';
$('stats').style.visibility = 'visible';
let h = ''; for (let i = 0; i < mh; i++) h += hp >= (i + 1) * 2 ? '♥' : hp === i * 2 + 1 ? '♡' : '<span style="opacity:.3">♥</span>';
let f = ''; for (let i = 0; i < 10; i++) f += fd >= (i + 1) * 2 ? '●' : fd === i * 2 + 1 ? '◐' : '<span style="opacity:.3">●</span>';
$('hearts').innerHTML = h; $('food').innerHTML = f;
$('airbar').textContent = air >= 0 ? 'o'.repeat(air) : '';
}
// ---------------------------------------------------------------- inventory / crafting / chest UI
let picked = -1, openChest = null, chestSlots = [], station = '';
function nearBlock(id, r) {
const bx = Math.floor(pl.x), by = Math.floor(pl.y), bz = Math.floor(pl.z);
for (let y = -2; y <= 3; y++) for (let z = -r; z <= r; z++) for (let x = -r; x <= r; x++) if (world.peek(bx + x, by + y, bz + z) === id) return true;
return false;
}
function openInv(st, chestKey) {
station = st || ''; openChest = chestKey || null; picked = -1;
if (!openChest) chestSlots = [];
state = 'inv'; releasePointer();
$('inv').classList.remove('hidden');
renderInv();
}
function closeInv() {
if (openChest) link.send({ t: 'chestSet', k: openChest, slots: chestSlots });
openChest = null; $('inv').classList.add('hidden'); state = 'play'; renderHotbar();
}
function recipeOK(r) {
for (const [id, n] of r.inp) if (countItem(id) < n) return false;
if (r.st === 'table' && !(station === 'table' || nearBlock(19, 4))) return false;
if (r.st === 'furnace') { if (!(station === 'furnace' || nearBlock(20, 4))) return false; if (pl.fuel < 1 && !Object.keys(E.FUEL).some(k => countItem(+k) > 0)) return false; }
return true;
}
function craft(r) {
if (!recipeOK(r)) return;
if (r.st === 'furnace' && pl.fuel < 1) {
const fk = Object.keys(E.FUEL).map(Number).sort((a, b) => E.FUEL[b] - E.FUEL[a]).find(k => countItem(k) > 0 && !r.inp.some(q => q[0] === k && countItem(k) <= q[1]));
if (fk == null) { toast('Needs fuel (coal or wood)'); return; }
removeItem(fk, 1); pl.fuel += E.FUEL[fk];
}
if (r.st === 'furnace') pl.fuel -= 1;
for (const [id, n] of r.inp) removeItem(id, n);
const left = addItem(r.out, r.n);
if (left) toast('Bag is full!');
sfx('craft'); renderInv();
}
function renderInv() {
const cr = creative();
$('creativeBox').classList.toggle('hidden', !cr);
$('craftBox').classList.toggle('hidden', cr && !openChest ? true : !!openChest);
$('chestBox').classList.toggle('hidden', !openChest);
let g = '';
for (let i = 9; i < 36; i++) g += slotHTML(inv[i], picked === i ? 'pick' : '').replace('class="slot', 'data-s="' + i + '" class="slot');
$('invGrid').innerHTML = g;
let h = '';
for (let i = 0; i < 9; i++) h += slotHTML(inv[i], picked === i ? 'pick' : (i === sel ? 'sel' : '')).replace('class="slot', 'data-s="' + i + '" class="slot');
h += '<div class="slot" data-trash="1" title="Throw away" style="border-color:#FF5555;color:#FF5555">✖</div>';
$('invHot').innerHTML = h;
let a = '';
for (let i = 0; i < 4; i++) a += slotHTML(pl.armor[i] ? { id: pl.armor[i], n: 1 } : null).replace('class="slot', 'data-a="' + i + '" title="' + ['Helmet', 'Chestplate', 'Leggings', 'Boots'][i] + '" class="slot');
$('armorGrid').innerHTML = a;
$('armorInfo').textContent = armorPts() ? 'Monsters hurt you ' + Math.round(Math.min(0.8, armorPts() * 0.04) * 100) + '% less' + (hasBoots(181) ? ', no fall damage' : '') : 'Tap armor in your bag, then a slot here';
$('invHot').style.gridTemplateColumns = 'repeat(10,auto)';
if (openChest) {
let c = '';
for (let i = 0; i < 27; i++) c += slotHTML(chestSlots[i], '').replace('class="slot', 'data-c="' + i + '" class="slot');
$('chestGrid').innerHTML = c;
}
if (cr) {
if (!$('palette').childElementCount) $('palette').innerHTML = E.allCreative.map(id => slotHTML({ id, n: 1 }).replace('class="slot', 'data-p="' + id + '" class="slot')).join('');
} else if (!openChest) {
$('craftTitle').textContent = station === 'table' ? 'CRAFTING TABLE' : station === 'furnace' ? 'FURNACE' : 'CRAFTING';
const list = E.RECIPES.map((r, i) => ({ r, i, ok: recipeOK(r) })).sort((a, b) => (b.ok - a.ok));
$('recipes').innerHTML = list.map(({ r, i, ok }) => '<button class="rec' + (ok ? '' : ' no') + '" data-r="' + i + '"><img src="' + iconFor(r.out) + '" alt=""><span>' +
(r.n > 1 ? r.n + ' ' : '') + E.itemName(r.out) + '<br><span class="ing">' + r.inp.map(([id, n]) => n + ' ' + E.itemName(id)).join(' + ') +
(r.st ? ' · ' + (r.st === 'table' ? 'crafting table' : 'furnace + fuel') : '') + '</span></span></button>').join('');
}
}
$('inv').addEventListener('click', e => {
const s = e.target.closest('[data-s],[data-c],[data-p],[data-r],[data-trash],[data-a]');
if (!s) return;
if (s.dataset.a != null) { // armor slot: wear the picked piece, or take this one off
const ai = +s.dataset.a;
if (picked >= 0 && inv[picked] && ITEMS[inv[picked].id] && ITEMS[inv[picked].id].armor != null) { wearArmor(picked); picked = -1; }
else if (pl.armor[ai]) { const id = pl.armor[ai]; if (!addItem(id, 1)) { pl.armor[ai] = null; lastStats = ''; } else toast('Bag is full!'); }
renderInv(); return;
}
if (s.dataset.r != null) { craft(E.RECIPES[+s.dataset.r]); return; }
if (s.dataset.p != null) { const id = +s.dataset.p; inv[sel] = { id, n: E.stackSize(id) }; if (maxDur(id)) inv[sel].d = maxDur(id); $('itemName').textContent = E.itemName(id); renderInv(); renderHotbar(); return; }
if (s.dataset.trash) { if (picked >= 0) { inv[picked] = null; picked = -1; renderInv(); } else $('itemName').textContent = 'Pick an item, then tap here to throw it away'; return; }
if (s.dataset.c != null) { // chest -> bag
const i = +s.dataset.c, it = chestSlots[i]; if (!it) return;
const left = addItem(it.id, it.n);
chestSlots[i] = left ? Object.assign({}, it, { n: left }) : null;
renderInv(); return;
}
const i = +s.dataset.s;
if (inv[i]) $('itemName').textContent = E.itemName(inv[i].id);
if (openChest && inv[i]) { // bag -> chest
const it = inv[i], st = E.stackSize(it.id);
for (let k = 0; k < 27 && it.n > 0; k++) { const c = chestSlots[k]; if (c && c.id === it.id && c.n < st) { const m = Math.min(it.n, st - c.n); c.n += m; it.n -= m; } }
for (let k = 0; k < 27 && it.n > 0; k++) if (!chestSlots[k]) { chestSlots[k] = Object.assign({}, it); it.n = 0; }
if (it.n <= 0) inv[i] = null;
renderInv(); renderHotbar(); return;
}
if (picked < 0) { if (inv[i]) picked = i; }
else {
if (picked !== i) {
const a = inv[picked], b = inv[i];
if (b && a && a.id === b.id && b.n < E.stackSize(b.id)) { const m = Math.min(a.n, E.stackSize(b.id) - b.n); b.n += m; a.n -= m; if (!a.n) inv[picked] = null; }
else { inv[picked] = b; inv[i] = a; }
}
picked = -1;
}
renderInv(); renderHotbar();
});
$('invClose').onclick = closeInv;
// ---------------------------------------------------------------- pets and the HERO screen
function petTap(mo) {
const name = mo.ex ? mo.ex[0] : 'Your pet', owner = mo.ex ? mo.ex[1] : '';
toast((owner && owner.toLowerCase() !== myName.toLowerCase() && session.remote ? owner + "'s pet " : '') + name + ' loves you! ♥');
tone(880, 1320, 0.15, 'sine', 0.08); tone(1320, 990, 0.15, 'sine', 0.06, 0.15);
}
function openHero() { if (state !== 'play') return; state = 'hero'; releasePointer(); $('hero').classList.remove('hidden'); renderHero(); }
function closeHero() { state = 'play'; $('hero').classList.add('hidden'); }
function renderHero() {
const h = H(), need = xpNeed(h.lvl);
$('hLevel').textContent = (session.remote ? myName.toUpperCase() : 'HERO') + ' · LEVEL ' + h.lvl + (h.cls ? ' ' + CLASSES[h.cls].name : '');
$('hXp').style.width = Math.round(100 * h.xp / need) + '%'; $('hXpText').textContent = h.xp + ' / ' + need + ' XP';
$('hClass').innerHTML = Object.entries(CLASSES).map(([k, c]) => '<button class="btn small' + (h.cls === k ? ' on' : '') + '" data-cls="' + k + '">' + c.name + '</button>').join('');
$('hClassAbout').textContent = h.cls ? CLASSES[h.cls].about : 'Pick a class. You can change it any time.';
$('hFree').textContent = h.free ? h.free + ' point' + (h.free > 1 ? 's' : '') + ' to spend:' : 'Level up to get points.';
const st = [['str', 'STRENGTH', '+10% damage each'], ['spd', 'SPEED', '+6% speed each (up to 10)'], ['hp', 'HEALTH', '+1 heart each (up to 10)']];
$('hStats').innerHTML = st.map(([k, n, about]) => '<div class="row"><span style="min-width:8em;text-align:left">' + n + ' ' + h.pts[k] + '</span><button class="btn small" data-pt="' + k + '"' +
(h.free && !((k === 'spd' || k === 'hp') && h.pts[k] >= 10) ? '' : ' disabled style="opacity:.4"') + '>+</button><span class="sub" style="font-size:.8em">' + about + '</span></div>').join('');
const pets = myPets && myPets.pets.length ? myPets.pets : null, foodWord = f => f > 75 ? 'full' : f > 50 ? 'happy' : f > 20 ? 'HUNGRY' : 'VERY HUNGRY, feed it now!';
$('hPet').innerHTML = pets ? 'Room for ' + myPets.slots + ' of ' + E.MAX_PETS + ' pets.' + (myPets.slots < E.MAX_PETS ? ' Feed hungry pets ' + (E.FEEDS_PER_SLOT - (myPets.fed || 0)) + ' more times to earn room for another.' : '') +
pets.map(pt => '<br><b>' + pt.name + '</b> the ' + E.PET_KINDS[pt.kind] + ', level ' + pt.lvl + ', ' + foodWord(pt.food == null ? 100 : pt.food)).join('') +
'<br>Make Pet Food from raw meat or bones, then tap it to feed your hungriest pet.'
: 'No pet yet. You get one at level 3, find one in a loot box, or tame a white wolf in the snow (feed it 3 times).';
$('hPetRow').classList.toggle('hidden', !pets);
if (pets) { const pick = $('hPetPick'), was = pick.value; pick.replaceChildren(...pets.map((pt, i) => new Option(pt.name, i))); if (was && +was < pets.length) pick.value = was; }
$('hTalesTitle').textContent = 'FAIRY TALES ' + talesDone() + ' / ' + E.TALES.length + (kidName() ? '' : ' (pick your name in ABC Books)');
// 210 tales: the open quests first, then the finished ones, then the locked ones, so a kid's own tales are at the top.
// In the kingdom an open or finished tale has a Go button (fast travel to its gate: the kingdom is ~1,900 blocks wide).
const inK = E.inKingdom(pl.z);
if (inK) $('hTalesTitle').textContent += ': tap Go to travel there';
$('hTales').innerHTML = E.TALES.map((T, i) => {
const done = taleState(T).done, read = taleRead(i);
return [done ? 1 : read ? 0 : 2, i, '<div class="ach' + (done ? ' got' : '') + '"><b style="color:' + (done ? '#FFDD77' : read ? '#ddd' : '#777') + '">' + (done ? '★ ' : '☆ ') + T.title + '</b><br><span>' +
(done ? 'Done! You have the ' + T.keep : read ? 'Open: finish the quest at ' + T.place : 'Read it in ABC Books to open ' + T.place) + '</span>' +
(inK && read ? '<br><button class="btn small" data-go="' + i + '">Go to ' + T.place + '</button>' : '') + '</div>'];
}).sort((a, b) => a[0] - b[0] || a[1] - b[1]).map(r => r[2]).join('');
const got = Object.keys(h.ach).length;
$('hAchTitle').textContent = 'ACHIEVEMENTS ' + got + ' / ' + Object.keys(ACH).length;
$('hAch').innerHTML = Object.entries(ACH).map(([k, a]) => '<div class="ach' + (h.ach[k] ? ' got' : '') + '"><b style="color:' + (h.ach[k] ? TIER_COL[a[2]] : '#777') + '">' + (h.ach[k] ? '★ ' : '☆ ') + a[0] + '</b><br><span>' + a[1] + '</span></div>').join('');
}
$('hero').addEventListener('click', e => {
const b = e.target.closest('[data-cls],[data-pt],[data-go]'); if (!b) return;
if (b.dataset.go) { closeHero(); link.send({ t: 'travel', i: +b.dataset.go }); return; }
const h = H();
if (b.dataset.cls) { h.cls = b.dataset.cls; lastStats = ''; pl.hp = Math.min(pl.hp, maxHp()); toast('You are now a ' + CLASSES[h.cls].name + '!'); sfx('craft'); }
if (b.dataset.pt && h.free > 0) { h.pts[b.dataset.pt]++; h.free--; lastStats = ''; sfx('craft'); }
renderHero();
});
$('hPetSave').onclick = () => { const n = $('hPetName').value.trim(); if (n) { link.send({ t: 'petname', name: n, idx: +$('hPetPick').value || 0 }); $('hPetName').value = ''; } };
$('hClose').onclick = closeHero;
$('bHero').addEventListener('click', openHero);
// ---------------------------------------------------------------- map
let mapZoom = 3;
function drawMap() {
const c = $('mapCv'), x = c.getContext('2d');
x.imageSmoothingEnabled = false; x.fillStyle = '#000'; x.fillRect(0, 0, c.width, c.height);
const s = mapZoom, cx = c.width / 2, cy = c.height / 2;
for (const [k, t] of mapTiles) {
const [a, b] = k.split(',').map(Number);
const px = cx + (a * CS - pl.x) * s, py = cy + (b * CS - pl.z) * s;
if (px > -CS * s && py > -CS * s && px < c.width && py < c.height) x.drawImage(t, px, py, CS * s, CS * s);
}
const mark = (wx, wz, col, label) => { const px = cx + (wx - pl.x) * s, py = cy + (wz - pl.z) * s; x.fillStyle = col; x.fillRect(px - 4, py - 4, 8, 8); x.fillStyle = '#fff'; x.font = '14px monospace'; x.fillText(label, px + 6, py + 4); };
if (session && session.spawn) mark(session.spawn.x, session.spawn.z, '#55FFFF', 'spawn');
if (pl.spawn) mark(pl.spawn.x, pl.spawn.z, '#FF5555', 'bed');
for (const a of airfields) mark(a.x, a.z, '#55FFFF', 'jets'); // the airfields where jets wait to be found
if (session && session.kingdomGate) mark(session.kingdomGate.x, session.kingdomGate.z, '#C080FF', 'fairy tales');
if (E.inKingdom(pl.z)) { mark(E.PLAZA.x, E.PLAZA.z, '#40D0A0', 'way home'); E.TALES.forEach((T, i) => { const c = E.placeWorld(i, 10, 10); mark(c[0], c[1], taleRead(i) ? '#FFDD77' : '#888888', T.place); }); }
for (const o of others.values()) mark(o.x, o.z, '#FFFF55', o.name);
x.save(); x.translate(cx, cy); x.rotate(-pl.yaw);
x.fillStyle = '#fff'; x.beginPath(); x.moveTo(0, -9); x.lineTo(6, 7); x.lineTo(0, 3); x.lineTo(-6, 7); x.closePath(); x.fill(); x.restore();
x.fillStyle = '#FFFF55'; x.font = '15px monospace';
x.fillText('X ' + Math.floor(pl.x) + ' Y ' + Math.floor(pl.y) + ' Z ' + Math.floor(pl.z) + ' N is up', 10, 20);
}
function openMap() { state = 'map'; releasePointer(); $('mapPanel').classList.remove('hidden'); drawMap(); }
function closeMap() { state = 'play'; $('mapPanel').classList.add('hidden'); }
$('mapClose').onclick = closeMap;
$('mapIn').onclick = () => { mapZoom = Math.min(8, mapZoom + 1); drawMap(); };
$('mapOut').onclick = () => { mapZoom = Math.max(1, mapZoom - 1); drawMap(); };
// ---------------------------------------------------------------- input
const keys = {};
let stick = { id: null, x: 0, y: 0, ox: 0, oy: 0 }, look = { id: null, sx: 0, sy: 0, lx: 0, ly: 0, t0: 0, moved: false, hold: false };
let jumpHeld = false, downHeld = false, attackHeld = false, useHeld2 = false, locked = false;
const playing = () => state === 'play' && pl && !pl.dead;
addEventListener('keydown', e => {
if (e.target.tagName === 'INPUT') return;
keys[e.code] = true;
if (state === 'play') {
if (e.code === 'Space') { const now = performance.now(); if (creative() && now - lastJumpTap < 300) { pl.fly = !pl.fly; toast(pl.fly ? 'Flying' : 'Walking'); } lastJumpTap = now; e.preventDefault(); }
if (e.code === 'KeyF' && ride) leaveRide();
if (e.code === 'KeyE') openInv();
if (e.code === 'KeyM') openMap();
if (e.code === 'KeyH') openHero();
if (e.code === 'Escape' || e.code === 'KeyP') openPause();
if (/^Digit[1-9]$/.test(e.code)) { sel = +e.code.slice(5) - 1; renderHotbar(); showHeldName(); }
} else if (state === 'inv' && (e.code === 'KeyE' || e.code === 'Escape')) closeInv();
else if (state === 'map' && (e.code === 'KeyM' || e.code === 'Escape')) closeMap();
else if (state === 'hero' && (e.code === 'KeyH' || e.code === 'Escape')) closeHero();
else if (state === 'pause' && e.code === 'Escape') resume();
});
addEventListener('keyup', e => { keys[e.code] = false; });
function releasePointer() { if (document.pointerLockElement) document.exitPointerLock(); }
document.addEventListener('pointerlockchange', () => { locked = document.pointerLockElement === cv; if (!locked && state === 'play' && !isTouch) openPause(); });
cv.addEventListener('mousedown', e => {
if (isTouch || !playing()) return;
if (!locked) { cv.requestPointerLock(); return; }
if (e.button === 0) { attackHeld = true; doAttackPress(); }
if (e.button === 2) { useHeld2 = true; doUse(); useCool = 0.3; }
});
addEventListener('mouseup', e => { if (e.button === 0) { attackHeld = false; breakT = 0; } if (e.button === 2) useHeld2 = false; });
cv.addEventListener('contextmenu', e => e.preventDefault());
addEventListener('mousemove', e => { if (locked && playing()) { pl.yaw -= e.movementX * 0.0025; pl.pitch = clamp(pl.pitch - e.movementY * 0.0025, -1.55, 1.55); } });
addEventListener('wheel', e => { if (state === 'play') { sel = (sel + (e.deltaY > 0 ? 1 : 8)) % 9; renderHotbar(); } }, { passive: true });
// touch: left = move stick, right = look / tap / hold
const tz = $('touch');
tz.addEventListener('touchstart', e => {
e.preventDefault(); audio();
for (const t of e.changedTouches) {
if (!playing()) continue;
if (t.clientX < innerWidth * 0.4 && stick.id === null) {
stick = { id: t.identifier, ox: t.clientX, oy: t.clientY, x: 0, y: 0 };
const r = $('stickRing'); r.style.left = t.clientX + 'px'; r.style.top = t.clientY + 'px'; r.style.display = 'block'; $('stickKnob').style.transform = '';
} else if (look.id === null) {
look = { id: t.identifier, sx: t.clientX, sy: t.clientY, lx: t.clientX, ly: t.clientY, t0: performance.now(), moved: false, hold: false };
}
}
}, { passive: false });
tz.addEventListener('touchmove', e => {
e.preventDefault();
for (const t of e.changedTouches) {
if (t.identifier === stick.id) {
const R = Math.min(innerWidth, innerHeight) * 0.13;
let dx = (t.clientX - stick.ox) / R, dy = (t.clientY - stick.oy) / R; const l = Math.hypot(dx, dy); if (l > 1) { dx /= l; dy /= l; }
stick.x = dx; stick.y = dy; $('stickKnob').style.transform = 'translate(' + dx * R + 'px,' + dy * R + 'px)';
} else if (t.identifier === look.id && pl) {
const dx = t.clientX - look.lx, dy = t.clientY - look.ly; look.lx = t.clientX; look.ly = t.clientY;
if (Math.hypot(t.clientX - look.sx, t.clientY - look.sy) > 12) look.moved = true;
const sens = 4.2 / Math.max(innerWidth, innerHeight);
pl.yaw -= dx * sens * 1.4; pl.pitch = clamp(pl.pitch - dy * sens * 1.4, -1.55, 1.55);
}
}
}, { passive: false });
const touchEnd = e => {
for (const t of e.changedTouches) {
if (t.identifier === stick.id) { stick = { id: null, x: 0, y: 0 }; $('stickRing').style.display = 'none'; }
else if (t.identifier === look.id) {
if (!look.moved && !look.hold && performance.now() - look.t0 < 300 && playing()) {
if (target && target.mob) doAttackPress(); else doUse();
}
look = { id: null }; attackHeld = false; breakT = 0;
}
}
};
tz.addEventListener('touchend', touchEnd); tz.addEventListener('touchcancel', touchEnd);
const holdBtn = (el, on, off) => {
el.addEventListener('touchstart', e => { e.preventDefault(); el.classList.add('held'); on(); }, { passive: false });
el.addEventListener('touchend', e => { e.preventDefault(); el.classList.remove('held'); off(); });
el.addEventListener('touchcancel', () => { el.classList.remove('held'); off(); });
el.addEventListener('mousedown', on); el.addEventListener('mouseup', off);
};
holdBtn($('bJump'), () => {
jumpHeld = true; const now = performance.now();
if (creative() && now - lastJumpTap < 300) { pl.fly = !pl.fly; toast(pl.fly ? 'Flying' : 'Walking'); }
lastJumpTap = now;
}, () => { jumpHeld = false; });
holdBtn($('bDown'), () => { downHeld = true; }, () => { downHeld = false; });
$('bFly').addEventListener('click', () => { if (creative()) { pl.fly = !pl.fly; toast(pl.fly ? 'Flying' : 'Walking'); } });
$('bExit').addEventListener('click', () => { if (ride) leaveRide(); });
$('bInv').addEventListener('click', () => { if (state === 'play') openInv(); });
$('bMap').addEventListener('click', () => { if (state === 'play') openMap(); });
$('bPause').addEventListener('click', () => { if (state === 'play') openPause(); });
// ---------------------------------------------------------------- vehicles: getting in, flying, getting out
const angDiff = (a, b) => { let d = a - b; while (d > Math.PI) d -= 2 * Math.PI; while (d < -Math.PI) d += 2 * Math.PI; return d; };
function groundBelow(x, y, z) { // feet height of the first thing to stand on below (x, y, z)
const bx = Math.floor(x), bz = Math.floor(z);
for (let yy = Math.min(CH, Math.floor(y)); yy > 0; yy--) { const b = world.get(bx, yy - 1, bz); if (isSolid[b] || b === 10) return yy; }
return Math.floor(y);
}
let engine = null;
function engineSound(on, pitch) {
const a = on ? audio() : null;
if (!a) { if (engine) { try { engine.o.stop(); } catch (e) {} engine = null; } return; }
if (!engine) {
const o = a.createOscillator(), f = a.createBiquadFilter(), g = a.createGain();
o.type = 'sawtooth'; f.type = 'lowpass'; f.frequency.value = 500; g.gain.value = 0.035;
o.connect(f).connect(g).connect(a.destination); o.start(); engine = { o };
}
engine.o.frequency.setTargetAtTime(pitch, a.currentTime, 0.1);
}
function rideButtons() {
$('bExit').classList.toggle('hidden', !ride);
$('bJump').textContent = ride ? 'UP' : 'JUMP';
$('bDown').classList.toggle('hidden', !ride && !creative()); $('bFly').classList.toggle('hidden', !!ride || !creative());
}
function startRide(m) {
const d = E.VEHICLES[m.kind];
ride = { id: m.id, kind: m.kind, x: m.x, y: m.y, z: m.z, vx: 0, vy: 0, vz: 0, w: d.w, h: d.h, yaw: m.yaw, pitch: 0, roll: 0, speed: 0, fall: 0, spin: 0 };
pl.fly = false; pl.yaw = m.yaw; pl.pitch = 0;
rideButtons(); sfx('door'); earn('fly');
toast(E.VEHICLES[m.kind].plane ? 'Push forward to speed up, look up to take off!\nOUT to get out' : 'UP to fly up, move to fly around\nOUT to get out');
}
function leaveRide() {
if (!ride) return;
const r = ride, gy = groundBelow(r.x, r.y + 0.5, r.z);
link.send({ t: 'vleave', id: r.id, x: +r.x.toFixed(2), y: gy, z: +r.z.toFixed(2) });
// step out beside it, on the ground (falling out of the sky is no fun)
const sx = r.x + Math.cos(r.yaw) * 2.6, sz = r.z - Math.sin(r.yaw) * 2.6, sgy = groundBelow(sx, gy + 4, sz);
const free = !isSolid[world.get(Math.floor(sx), sgy, Math.floor(sz))] && !isSolid[world.get(Math.floor(sx), sgy + 1, Math.floor(sz))];
Object.assign(pl, free ? { x: sx, y: sgy, z: sz } : { x: r.x, y: gy + 2.2, z: r.z }, { vx: 0, vy: 0, vz: 0, fallY: null });
ride = null; engineSound(false); rideButtons(); sfx('door');
}
function updateRide(dt) {
const r = ride;
let mf = 0, ms = 0;
if (keys.KeyW || keys.ArrowUp) mf += 1; if (keys.KeyS || keys.ArrowDown) mf -= 1;
if (keys.KeyD || keys.ArrowRight) ms += 1; if (keys.KeyA || keys.ArrowLeft) ms -= 1;
if (stick.id !== null) { mf -= stick.y; ms += stick.x; }
const up = jumpHeld || keys.Space, down = downHeld || keys.ShiftLeft;
if (r.kind === 'heli') {
const sy = Math.sin(pl.yaw), cy = Math.cos(pl.yaw), sp = 12;
const tx = (-sy * mf + cy * ms) * sp, tz = (-cy * mf - sy * ms) * sp, ty = up ? 7 : down ? -7 : 0;
r.vx += (tx - r.vx) * Math.min(1, 2.5 * dt); r.vz += (tz - r.vz) * Math.min(1, 2.5 * dt); r.vy += (ty - r.vy) * Math.min(1, 4 * dt);
r.yaw += angDiff(pl.yaw, r.yaw) * Math.min(1, 4 * dt);
const fs = -r.vx * Math.sin(r.yaw) - r.vz * Math.cos(r.yaw), ss = r.vx * Math.cos(r.yaw) - r.vz * Math.sin(r.yaw);
r.pitch += (-fs * 0.025 - r.pitch) * Math.min(1, 5 * dt); r.roll += (ss * 0.03 - r.roll) * Math.min(1, 5 * dt);
r.spin += dt * 30;
engineSound(true, 70 + Math.abs(r.vy) * 4 + Math.hypot(r.vx, r.vz) * 2);
} else {
// arcade plane: stick forward = faster, back = slower; look (or UP/DOWN) to climb and dive; stick sideways or look to turn
if (mf > 0.2) r.speed += 9 * dt * mf; else if (mf < -0.2) r.speed += 14 * dt * mf;
r.speed = clamp(r.speed, 0, E.VEHICLES[r.kind].max || 20);
pl.yaw -= ms * (E.VEHICLES[r.kind].turn || 1) * 1.6 * dt;
if (up || down) pl.pitch = clamp(pl.pitch + (up ? 1 : -1) * 1.2 * dt, -1.55, 1.55);
const lift = clamp((r.speed - 6) / 6, 0, 1);
let tp = clamp(pl.pitch, -0.7, 0.7);
if (r.onGround && lift < 1) tp = Math.max(0, Math.min(tp, lift * 0.7));
const turn = clamp(angDiff(pl.yaw, r.yaw), -1.8 * dt, 1.8 * dt);
r.yaw += turn;
r.roll += (clamp(-turn / dt * 0.45, -0.7, 0.7) * lift - r.roll) * Math.min(1, 4 * dt);
r.pitch += (tp - r.pitch) * Math.min(1, 3 * dt);
r.fall = lift >= 1 ? 0 : Math.min(14, r.fall + 16 * dt * (1 - lift));
if (r.onGround) r.fall = Math.min(r.fall, 2);
const cp = Math.cos(r.pitch);
r.vx = -Math.sin(r.yaw) * cp * r.speed; r.vz = -Math.cos(r.yaw) * cp * r.speed;
r.vy = Math.sin(r.pitch) * r.speed * lift - r.fall;
r.spin += dt * (r.speed * 3 + 8);
engineSound(true, 60 + r.speed * 6);
}
if (r.inWater) { r.vy = Math.max(r.vy, 2); r.speed *= 0.97; }
const before = Math.hypot(r.vx, r.vz);
E.moveBody(world, r, dt, true);
if (r.hitWall && before > 6) { r.speed *= 0.3; sfx('hit', r.x, r.y, r.z); shake = 0.3; }
if (r.y > CH + 40) { r.y = CH + 40; r.vy = Math.min(r.vy, 0); }
if (r.y < 1) { r.y = groundBelow(r.x, CH, r.z); r.vy = 0; }
Object.assign(pl, { x: r.x, y: r.y + 0.3, z: r.z, vx: 0, vy: 0, vz: 0, fallY: null, air: 10 });
}
// ---------------------------------------------------------------- player update
function updatePlayer(dt) {
if (pl.dead) return;
for (const k in pl.fx) { pl.fx[k] -= dt; if (pl.fx[k] <= 0) { delete pl.fx[k]; toast(FX_NAMES[k] + ' wore off'); } }
if ((pl.fx.regen || H().cls === 'healer' || inSafe) && !creative()) pl.hp = Math.min(maxHp(), pl.hp + dt * (pl.fx.regen || inSafe ? 0.8 : 0.15));
if (ride) { updateRide(dt); return; }
let mf = 0, ms = 0;
if (keys.KeyW || keys.ArrowUp) mf += 1; if (keys.KeyS || keys.ArrowDown) mf -= 1;
if (keys.KeyD || keys.ArrowRight) ms += 1; if (keys.KeyA || keys.ArrowLeft) ms -= 1;
if (stick.id !== null) { mf -= stick.y; ms += stick.x; }
const ml = Math.hypot(mf, ms); if (ml > 1) { mf /= ml; ms /= ml; }
const sprint = (keys.ShiftLeft && !creative()) ? false : (ml > 0.95 && stick.id !== null) || keys.ControlLeft;
const jump = jumpHeld || keys.Space, down = downHeld || keys.ShiftLeft;
const sy = Math.sin(pl.yaw), cy = Math.cos(pl.yaw);
const dirx = -sy * mf + cy * ms, dirz = -cy * mf - sy * ms;
if (pl.fly) {
const sp = 10;
pl.vx = dirx * sp; pl.vz = dirz * sp; pl.vy = jump ? 8 : down ? -8 : 0;
E.moveBody(world, pl, dt, false);
if (pl.onGround && down) pl.fly = false;
pl.fallY = null;
} else {
const sp = (pl.inWater ? 2.2 : sprint ? 5.6 : 4.3) * (pl.fx.speed ? 1.6 : 1) * speedBoost();
const acc = pl.onGround ? 14 : pl.inWater ? 6 : 3;
pl.vx += (dirx * sp - pl.vx) * Math.min(1, acc * dt);
pl.vz += (dirz * sp - pl.vz) * Math.min(1, acc * dt);
if (pl.inWater) { pl.vy -= 9 * dt; pl.vy = Math.max(pl.vy, -2.5); if (jump) pl.vy = Math.min(pl.vy + 22 * dt, 3.2); }
else if (pl.onLadder) { pl.vy = jump || (ml > 0.1 && pl.hitWall) ? 2.6 : down ? -2.6 : Math.max(pl.vy - 28 * dt, -1.5); }
else { pl.vy -= 28 * dt; if (jump && pl.onGround) pl.vy = pl.fx.jump ? 12.5 : 8.4; }
// playground: a slide speeds you up the way you are going, a merry-go-round turns you, a trampoline bounces you
const under = pl.onGround ? blk(world.peek(Math.floor(pl.x), Math.floor(pl.y - 0.2), Math.floor(pl.z))) : null;
if (under && under.slide) {
const h = Math.hypot(pl.vx, pl.vz), sx = h > 0.5 ? pl.vx / h : -Math.sin(pl.yaw), sz = h > 0.5 ? pl.vz / h : -Math.cos(pl.yaw);
pl.vx += (sx * 9 - pl.vx) * Math.min(1, 3 * dt); pl.vz += (sz * 9 - pl.vz) * Math.min(1, 3 * dt);
}
if (under && under.spin) pl.yaw += 1.6 * dt;
if (under && under.bounce && jump) pl.vy = 14;
pl.vy = Math.max(pl.vy, -40);
const wasGround = pl.onGround;
E.moveBody(world, pl, dt, true);
const landOn = pl.onGround && !wasGround ? blk(world.peek(Math.floor(pl.x), Math.floor(pl.y - 0.2), Math.floor(pl.z))) : null;
if (pl.inWater || pl.onLadder) pl.fallY = null;
else if (!pl.onGround) { if (pl.fallY === null || pl.y > pl.fallY) pl.fallY = pl.y; }
else if (landOn && landOn.bounce) { // boing! the higher you fall, the higher you go (and it never hurts)
const fall = pl.fallY === null ? 0 : pl.fallY - pl.y; pl.fallY = null;
if (fall > 0.6) { pl.vy = Math.min(17, 7 + fall * 1.6); pl.onGround = false; sfx('pop'); }
}
else if (pl.fallY !== null) {
const fall = pl.fallY - pl.y; pl.fallY = null;
const safe = hasBoots(181) ? Infinity : pl.fx.jump ? 6.4 : H().cls === 'explorer' ? 8 : 3.4; // diamond boots: no fall damage
if (fall > safe && !creative()) { hurt(Math.floor(fall - safe + 0.4), 'You fell from a high place'); earn('gravity'); }
if (fall > 1) sfx('step');
}
if (pl.onGround && ml > 0.1) { stepT -= dt * (sprint ? 1.4 : 1); if (stepT <= 0) { stepT = 0.4; sfx('step'); } }
if (!wasGround && pl.onGround && pl.inWater) sfx('splash');
}
if (pl.y < -10) { hurt(100, 'You fell out of the world'); }
// survival needs
if (!creative()) {
pl.food = Math.max(0, pl.food - dt * (sprint ? 1 / 25 : 1 / 60) - (jump && pl.onGround ? 0.02 : 0));
if (pl.food >= 16 && pl.hp < maxHp()) { pl.hp = Math.min(maxHp(), pl.hp + dt / 3); pl.food -= dt / 14; }
if (pl.food <= 0 && pl.hp > 2) pl.hp -= dt / 4;
const head = world.peek(Math.floor(pl.x), Math.floor(pl.y + 1.62), Math.floor(pl.z));
if (head === 10 && !pl.fx.water) { pl.air -= dt; if (pl.air < 0) { pl.air = 0; pl.drown = (pl.drown || 0) + dt; if (pl.drown > 1) { pl.drown = 0; hurt(2, 'You drowned'); } } }
else pl.air = Math.min(10, pl.air + dt * 4);
if (pl.onGround && world.peek(Math.floor(pl.x), Math.floor(pl.y - 0.2), Math.floor(pl.z)) === 18) { pl.cactusT = (pl.cactusT || 0) - dt; if (pl.cactusT <= 0) { pl.cactusT = 0.6; hurt(1, 'You were pricked to death'); } }
}
}
function hurt(n, why, mob) {
if (creative() || pl.dead || n <= 0) return;
if (mob) { // armor and the shield potion only help against monsters, arrows and explosions
n *= 1 - Math.min(0.8, armorPts() * 0.04);
if (pl.fx.shield) n *= 0.5;
n = Math.max(0.5, n);
}
pl.hp -= n; hurtFlash = 0.5; sfx('hurt'); shake = 0.25;
if (pl.hp <= 0) die(why);
}
function die(why) {
leaveRide();
pl.hp = 0; pl.dead = true; sfx('die'); earn('oops');
$('deadWhy').textContent = why || ''; $('dead').classList.remove('hidden'); state = 'dead'; releasePointer();
link.send({ t: 'move', x: pl.x, y: pl.y, z: pl.z, yaw: pl.yaw, pitch: pl.pitch, dead: true });
}
$('dRespawn').onclick = () => {
const sp = pl.spawn || session.spawn;
Object.assign(pl, { x: sp.x, y: sp.y + 0.1, z: sp.z, vx: 0, vy: 0, vz: 0, hp: maxHp(), food: 20, air: 10, dead: false, fallY: null, fx: {} });
$('dead').classList.add('hidden'); state = 'play'; renderStats();
};
// ---------------------------------------------------------------- targeting, digging, placing
function findTarget() {
const eye = [pl.x, pl.y + 1.62, pl.z], f = fwd(), reach = creative() ? 6 : 5;
const h = E.raycast(world, eye[0], eye[1], eye[2], f[0], f[1], f[2], reach, false);
let best = h ? { block: h, d: h.d } : null;
for (const m of mobs.values()) {
const d = E.MOBS[E.MOB_TYPES[m.type]], hw = d.w / 2;
const t = E.rayBox(eye[0], eye[1], eye[2], f[0], f[1], f[2], m.rx - hw, m.ry, m.rz - hw, m.rx + hw, m.ry + d.h, m.rz + hw);
if (t >= 0 && t < 3.5 && (!best || t < best.d)) best = { mob: m, d: t };
}
for (const v of vehicles.values()) {
if (v.rider && v.rider !== myId) continue;
const d = E.VEHICLES[E.VEH_TYPES[v.kind]], hw = d.bw / 2;
const t = E.rayBox(eye[0], eye[1], eye[2], f[0], f[1], f[2], v.rx - hw, v.ry, v.rz - hw, v.rx + hw, v.ry + d.bh, v.rz + hw);
if (t >= 0 && t < 5 && (!best || t < best.d)) best = { veh: v, d: t };
}
target = best;
}
function breakTime(id) {
const d = blk(id); if (d.hard < 0) return Infinity; if (creative()) return 0;
const s = inv[sel], it = s && ITEMS[s.id];
const can = !d.lvl || (it && it.tool === 'pick' && it.tier >= d.lvl);
const speed = it && it.tool && it.tool === d.tool ? it.speed : 1;
return d.hard * (can ? 1.5 : 5) / speed;
}
function doAttackPress() {
if (target && target.mob && attackCool <= 0) {
const s = inv[sel], it = s && ITEMS[s.id], f = fwd(), l = Math.hypot(f[0], f[2]) || 1;
const mt = E.MOB_TYPES[target.mob.type], md = E.MOBS[mt], base = md.base || mt, undead = base === 'zombie' || base === 'skeleton';
if (md.pet) { petTap(target.mob); attackCool = 0.6; return; }
const dmg = (it && it.dmg ? it.dmg : 1) * (it && it.undead && undead ? it.undead : 1) * (pl.fx.str ? 2 : 1) * meleeBoost();
link.send({ t: 'hit', id: target.mob.id, dmg, kx: f[0] / l, kz: f[2] / l });
sfx('hit', target.mob.rx, target.mob.ry, target.mob.rz); attackCool = 0.45; if (it && it.tool) wearTool();
}
}
function breakBlock(b) {
const d = blk(b.id), s = inv[sel], it = s && ITEMS[s.id];
const can = !d.lvl || (it && it.tool === 'pick' && it.tier >= d.lvl);
if (notMine(b.x, b.z)) return;
setBlock(b.x, b.y, b.z, 0);
if (d.shape === 'door') { const oy = d.half ? b.y - 1 : b.y + 1; if (blk(world.peek(b.x, oy, b.z)).shape === 'door') setBlock(b.x, oy, b.z, 0); }
sfx('break', b.x, b.y, b.z);
if (!creative()) {
if (can) {
let drop = d.drop;
if (d.shape === 'door') drop = 115;
if (drop === -1) { // leaves: sometimes fruit or a stick
const r = Math.random();
drop = r < 0.04 ? 105 : r < 0.055 ? 152 : r < 0.07 ? 155 : r < 0.08 ? 156 : r < 0.13 ? 100 : 0;
}
if (drop === -2) drop = 147 + Math.floor(Math.random() * 4); // jewel ore: ruby, emerald, sapphire or amethyst
if (drop) giveDrops([[drop, 1]]);
const oreXp = { 12: 1, 13: 2, 14: 3, 15: 5, 55: 3, 56: 6 }[b.id];
if (oreXp) addXp(oreXp);
if (b.id === 15) earn('shiny'); if (b.id === 56) earn('jewel');
}
if (it && it.tool) wearTool();
}
}
function setBlock(x, y, z, id) { world.set(x, y, z, id); link.send({ t: 'block', x, y, z, id }); }
// kit castles belong to whoever built them: others can't change their blocks (the server checks this too)
let owned = [];
const castleOwnerAt = (x, z) => { for (const c of owned) if (x >= c.x0 && x < c.x0 + E.CW && z >= c.z0 && z < c.z0 + E.CW) return c; return null; };
function notMine(x, z) {
if (E.inKingdom(z)) { toast('This is the Fairy Tale Kingdom:\nlook, but no digging or building here'); return true; }
const c = castleOwnerAt(x, z);
if (!c || c.owner.toLowerCase() === myName.toLowerCase()) return false;
toast('This is ' + c.owner + "'s castle"); return true;
}
function doUse() {
if (!playing() || useCool > 0 || ride) return;
useCool = 0.22;
const s = inv[sel], it = s && ITEMS[s.id];
// a wild white wolf: feed it bones, raw meat or pet food (3 times and it is yours)
if (target && target.mob && it && E.TAME_FOOD.includes(s.id) && E.MOB_TYPES[target.mob.type] === 'wolf') {
link.send({ t: 'tame', id: target.mob.id, item: s.id, took: !creative() }); useHeld(); sfx('eat'); useCool = 0.6; return;
}
if (target && target.mob) { doAttackPress(); return; }
if (target && target.veh) {
const v = target.veh;
if (v.owner && v.owner.toLowerCase() !== myName.toLowerCase()) toast('This is ' + v.owner + "'s " + E.VEHICLES[E.VEH_TYPES[v.kind]].name.toLowerCase() + '.\nMake your own at a crafting table!');
else link.send({ t: 'vride', id: v.id });
useCool = 0.6; return;
}
// fairy tale portals, story stones, gates and quest blocks come first, whatever is in your hand
if (target && target.block && taleTap(target.block)) return;
// airplane / helicopter: set it down on the block you tap (always uses up the item, even in creative)
if (it && it.vehicle && target && target.block) {
const b = target.block;
let px = b.x + b.nx + 0.5, pz = b.z + b.nz + 0.5, py = b.ny === 1 ? b.y + blk(b.id).h : b.y + b.ny;
if (Math.hypot(px - pl.x, pz - pl.z) < 2.5) { // too close: put it down a few steps ahead instead
px = pl.x - Math.sin(pl.yaw) * 3.5; pz = pl.z - Math.cos(pl.yaw) * 3.5; py = groundBelow(px, pl.y + 3, pz);
}
const vd = E.VEHICLES[it.vehicle], hw = vd.w / 2 + 0.3;
for (let y = Math.floor(py); y <= Math.floor(py + vd.h + 0.5); y++) for (let z = Math.floor(pz - hw); z <= Math.floor(pz + hw); z++) for (let x = Math.floor(px - hw); x <= Math.floor(px + hw); x++)
if (isSolid[world.peek(x, y, z)]) { toast('Not enough room here.\nFind an open spot!'); return; }
link.send({ t: 'vplace', kind: it.vehicle, x: px, y: py, z: pz, yaw: pl.yaw });
s.n--; if (s.n <= 0) inv[sel] = null; renderHotbar();
sfx('place', px, py, pz); toast('Tap your ' + E.VEHICLES[it.vehicle].name.toLowerCase() + ' to get in!\nHold on it to pick it back up');
useCool = 0.6; return;
}
// loot box: tap to open
if (it && it.box != null) { s.n--; if (s.n <= 0) inv[sel] = null; renderHotbar(); openBox(it.box); useCool = 0.8; return; }
// pet basket / egg: call your pet (it stays yours; a different one swaps)
if (it && it.pet) { link.send({ t: 'pet', item: s.id }); inv[sel] = null; renderHotbar(); sfx('pop'); useCool = 1; return; }
// pet food: feeds your hungriest pet. A heart: heals you 3 hearts and cheers up all your pets.
if (it && it.petfood) { link.send({ t: 'feed', took: !creative() }); useHeld(); sfx('eat'); useCool = 0.6; return; }
if (it && it.heart) {
pl.hp = Math.min(maxHp(), pl.hp + it.heal); link.send({ t: 'feed', heart: 1 }); useHeld(); sfx('drink'); toast('+3 hearts'); useCool = 0.5; return;
}
// castle kit: the castle builds itself with its gate 4 steps in front of you (always uses up the kit)
if (it && (it.kit || it.tkit)) {
const f = fwd(), l = Math.hypot(f[0], f[2]) || 1, dx = f[0] / l, dz = f[2] / l, k = 13 / Math.max(Math.abs(dx), Math.abs(dz));
const cx = Math.floor(pl.x + dx * k), cz = Math.floor(pl.z + dz * k); // far enough that you are outside its walls
link.send({ t: 'kit', item: s.id, x: cx, z: cz });
inv[sel] = null; renderHotbar(); sfx('craft'); shake = 0.4; useCool = 1; return;
}
// bow
if (it && it.bow) {
const archer = H().cls === 'archer';
if (!creative() && countItem(112) < 1) { toast('You need arrows'); return; }
if (!creative() && !(archer && Math.random() < 0.5)) removeItem(112, 1);
const f = fwd();
link.send({ t: 'shoot', x: pl.x + f[0] * 0.5, y: pl.y + 1.5 + f[1] * 0.5, z: pl.z + f[2] * 0.5, vx: f[0] * 32, vy: f[1] * 32, vz: f[2] * 32,
dmg: 6 * (archer ? 2 : 1) * (1 + H().pts.str * 0.05) });
sfx('bow'); wearTool(); useCool = 0.6; return;
}
const b = target && target.block;
if (it && it.keep) { storyStone(E.TALE_IDX[it.keep], false); useCool = 0.8; return; } // a keepsake: hear its story again
if (b) {
const id = b.id, d = blk(id);
if (id === 19) { openInv('table'); return; }
if (id === 20) { openInv('furnace'); return; }
if (E.isChest(id)) { const k = b.x + ',' + b.y + ',' + b.z; openChestAt(k); return; }
if (id === 61 || id === 62) { link.send({ t: 'stairs', x: b.x, y: b.y, z: b.z }); useCool = 1.5; return; }
if (d.shape === 'door') {
const ny = d.open ? id - 4 : id + 4, oy = d.half ? b.y - 1 : b.y + 1, oid = world.peek(b.x, oy, b.z);
setBlock(b.x, b.y, b.z, ny);
if (blk(oid).shape === 'door') setBlock(b.x, oy, b.z, blk(oid).open ? oid - 4 : oid + 4);
sfx('door', b.x, b.y, b.z); return;
}
if (id === 31) { pl.spawn = { x: b.x + 0.5, y: b.y + 1, z: b.z + 0.5 }; sleepStart(b); link.send({ t: 'sleep' }); return; }
if (id === 94) { // swing: wheee, up and forward
const f = fwd(), l = Math.hypot(f[0], f[2]) || 1; pl.vy = 9; pl.vx = f[0] / l * 6; pl.vz = f[2] / l * 6; pl.onGround = false;
sfx('pop'); toast('Wheee!'); useCool = 0.8; return;
}
if (id === 97) { // heart machine: one fruit or flower in, a heart and two heart blocks out
const inp = [105, 152, 153, 154, 155, 156, 157, 36, 37, 73].find(i => countItem(i) > 0);
if (!inp) { toast('The Heart Machine needs fruit or flowers.\nPut one in and it makes a heart!'); useCool = 0.8; return; }
removeItem(inp, 1); addItem(221, 1); addItem(96, 2); renderHotbar();
sfx('craft'); shake = 0.15; toast('Pop! A heart and two heart blocks.\nTap a heart to heal you and your pets.'); useCool = 0.5; return;
}
if (id === 32) { link.send({ t: 'ignite', x: b.x, y: b.y, z: b.z }); sfx('hiss', b.x, b.y, b.z); return; }
}
// potions (the empty bottle comes back) and the golden apple
if (it && (it.potion || it.fx)) {
if (it.fx) pl.food = Math.min(20, pl.food + it.food);
drink(it); s.n--; if (s.n <= 0) inv[sel] = null; if (it.potion) addItem(159, 1);
renderHotbar(); sfx(it.potion ? 'drink' : 'eat'); return;
}
// armor: tap to wear it
if (it && it.armor != null) { wearArmor(sel); return; }
// eat
if (it && it.food) {
if (creative() || pl.food >= 20) { toast('You are not hungry'); return; }
pl.food = Math.min(20, pl.food + it.food); useHeld(); sfx('eat');
if ([105, 152, 153, 154, 155, 156, 157].includes(s.id)) { const h = H(); h.fruit[s.id] = 1; if (Object.keys(h.fruit).length >= 5) earn('fruit'); }
return;
}
if (!s || !b) return;
// place
let place = s.id < 100 ? s.id : (it && it.places) || 0;
if (!place) return;
let px = b.x + b.nx, py = b.y + b.ny, pz = b.z + b.nz;
if (b.id === 38 || b.id === 36 || b.id === 37) { px = b.x; py = b.y; pz = b.z; }
const cur = world.peek(px, py, pz);
if (cur && cur !== 10 && cur !== 38) return;
if (py < 1 || py >= CH - 1) return;
if (notMine(px, pz)) return;
if (place === 23) {
const f = fwd(); place = Math.abs(f[0]) > Math.abs(f[2]) ? 25 : 23;
const above = world.peek(px, py + 1, pz);
if (above && above !== 38) return;
setBlock(px, py, pz, place); setBlock(px, py + 1, pz, place + 1); useHeld(); sfx('place', px, py, pz); return;
}
if (isSolid[place]) {
const hw = pl.w / 2;
if (px + 1 > pl.x - hw && px < pl.x + hw && pz + 1 > pl.z - hw && pz < pl.z + hw && py + 1 > pl.y && py < pl.y + pl.h) return;
for (const o of others.values()) if (Math.abs(o.x - (px + 0.5)) < 0.8 && Math.abs(o.z - (pz + 0.5)) < 0.8 && py + 1 > o.y && py < o.y + 1.8) return;
}
if ((blk(place).shape === 'cross') && !isSolid[world.peek(px, py - 1, pz)]) return;
setBlock(px, py, pz, place); useHeld(); sfx('place', px, py, pz);
}
function openChestAt(k) { openChest = k; chestSlots = []; link.send({ t: 'chest', k }); }
function interact(dt) {
attackCool -= dt; useCool -= dt;
if (ride) { target = null; breakT = 0; return; }
findTarget();
const holding = attackHeld || (look.id != null && look.hold);
if (look.id != null && !look.hold && !look.moved && performance.now() - look.t0 > 300) look.hold = true;
if (holding && target && target.veh) { // hold on your own vehicle to put it back in the bag
const v = target.veh;
if (v.owner && v.owner.toLowerCase() !== myName.toLowerCase()) { if (breakT === 0) toast('Only ' + v.owner + ' can pick that up'); breakT = 0.001; return; }
if (breakKey !== 'v' + v.id) { breakKey = 'v' + v.id; breakT = 0; }
breakT += dt;
if (breakT >= 1) { link.send({ t: 'vpickup', id: v.id }); vehicles.delete(v.id); breakT = 0; breakKey = ''; }
return;
}
if (look.id != null && look.hold && target && target.mob) { doAttackPress(); return; }
if (holding && target && target.block && creative()) {
if (attackCool <= 0 && blk(target.block.id).hard >= 0) { breakBlock(target.block); attackCool = 0.25; }
} else if (holding && target && target.block) {
const b = target.block, k = b.x + ',' + b.y + ',' + b.z;
if (k !== breakKey) { breakKey = k; breakT = 0; if (E.inKingdom(b.z)) notMine(b.x, b.z); }
const tt = E.inKingdom(b.z) ? Infinity : breakTime(b.id);
if (tt === Infinity) return;
breakT += dt;
if (Math.floor(breakT / 0.25) !== Math.floor((breakT - dt) / 0.25)) sfx('dig', b.x, b.y, b.z);
if (breakT >= tt) { breakBlock(b); breakT = 0; breakKey = ''; }
} else if (holding && target && target.mob) doAttackPress();
else { breakT = 0; breakKey = ''; }
if (useHeld2 && useCool <= 0) doUse();
}
// ---------------------------------------------------------------- fairy tale kingdom: unlocks from ABC Books, story stones, quests
// ABC Books runs on the same site (games.503mail.com/abcbooks/), so its localStorage 'abcbooks' can be read here:
// progress[kid].grimm1884[lesson n].stars. A tale counts as read when every part of it has stars.
let abcLessons = null; // [{n, tale}] from ABC Books' own book file; until it loads (or if it can't), TALES[i].parts is used
fetch('/abcbooks/books/grimm1884.json').then(r => r.ok ? r.json() : null).then(b => { if (b && Array.isArray(b.lessons)) abcLessons = b.lessons.map(L => ({ n: L.n, tale: L.tale })); }).catch(() => {});
const taleTest = {}; // testing only: BCdebug().taleTest[i] = true / false
let abcCache = null, abcAt = -1e9;
function abcState() {
const now = performance.now();
if (now - abcAt > 2000) { abcAt = now; try { abcCache = JSON.parse(localStorage.getItem('abcbooks') || 'null') || {}; } catch (e) { abcCache = {}; } }
return abcCache;
}
// whose reading counts: the name signed in to Play Together, or in single player this tablet's name or the kid picked in ABC Books
const kidName = () => session && session.remote ? myName : (cfg.name || abcState().kid || '');
// ABC Books also reports finished tales to the BlockCraft server (that covers abcbooks.fyi and other tablets): sent on join,
// pushed while playing (msg 'tales'), and fetched for single player
let serverTales = [];
function fetchTales() {
const nm = kidName(); if (!nm) return;
fetch(BASE + 'api/tales?name=' + encodeURIComponent(nm)).then(r => r.ok ? r.json() : null).then(j => { if (j && Array.isArray(j.tales)) serverTales = j.tales; }).catch(() => {});
}
function taleRead(i) {
if (taleTest[i] != null) return taleTest[i];
if (serverTales.includes(E.TALES[i].id)) return true;
const s = abcState(), nm = kidName().toLowerCase();
if (!nm || !s.progress) return false;
const k = Object.keys(s.progress).find(q => q.toLowerCase() === nm); if (!k) return false;
const p = (s.progress[k] || {}).grimm1884 || {}, T = E.TALES[i];
const ns = abcLessons ? abcLessons.filter(L => L.tale === T.abc).map(L => L.n) : Array.from({ length: T.parts[1] }, (_, j) => T.parts[0] + j);
return ns.length > 0 && ns.every(n => p[n] && p[n].stars);
}
E.setGateOpen((x, z) => { const pk = E.placeAt(x, z); return !!pk && taleRead(pk.i); });
// spoken lines: tales/<key>.mp3, one after another (the same words are on the screen)
let taleAudio = null;
function sayTale(keys) {
if (taleAudio) { taleAudio.onended = taleAudio.onerror = null; taleAudio.pause(); taleAudio = null; }
if (!cfg.sound) return;
const q = keys.slice();
const next = () => {
const k = q.shift(); if (!k) { taleAudio = null; return; }
const a = new Audio(BASE + 'tales/' + k + '.mp3'); let gone = false;
const go = () => { if (!gone && taleAudio === a) { gone = true; next(); } };
taleAudio = a; a.onended = go; a.onerror = go; a.play().catch(go);
};
next();
}
function showStory(title, text, color, secs) { // a story banner replaces any story banner still waiting
for (let k = announceQ.length - 1; k >= 1; k--) if (announceQ[k][3]) announceQ.splice(k, 1);
if (announceQ.length && announceT > 0) { announceQ.splice(1, 0, [title, text, color, secs]); announceT = 0.01; }
else announce(title, text, color, secs);
}
const taleState = T => { const h = H(); h.tales = h.tales || {}; return h.tales[T.id] || (h.tales[T.id] = { s: 0, got: [] }); };
const talesDone = () => E.TALES.filter(T => ((H().tales || {})[T.id] || {}).done).length;
// story stone (or a keepsake tapped in your hand): the story, then what to do next
function storyStone(i, home) {
const T = E.TALES[i], st = taleState(T), read = taleRead(i), mine = home && home.owner.toLowerCase() === myName.toLowerCase();
let status, clip = null;
if (home) status = 'This is ' + (mine || !session.remote ? 'your own ' : home.owner + "'s ") + T.place + '. The quest is in the Fairy Tale Kingdom.';
else if (home === false) status = st.done ? 'You earned this by finishing the quest at ' + T.place + '.' : '';
else if (!read) { status = E.TALE_LINES.locked; clip = 'locked'; }
else if (st.done) { status = E.TALE_LINES.done; clip = 'done'; }
else if (st.s === 0 && !st.got.length) { status = T.quest; clip = T.id + '-quest'; }
else { status = 'Next: ' + T.steps[st.s].hint; clip = T.id + '-h' + st.s; }
showStory(T.title.toUpperCase(), T.sum.slice(T.title.length + 2) + (status ? '\n\n' + status : ''), '#FFDD77', 18);
sayTale([T.id + '-sum'].concat(clip ? [clip] : []));
}
// tapping a block: the portals, story stones and gates, and the quest steps. true = handled.
function taleTap(b) {
const id = b.id;
if (id === 82 || id === 83) { link.send({ t: 'stairs', x: b.x, y: b.y, z: b.z }); useCool = 1.5; return true; }
const pk = E.inKingdom(b.z) ? E.placeAt(b.x, b.z) : null;
let i = pk ? pk.i : -1, home = null;
if (!pk) { const c = castleOwnerAt(b.x, b.z); if (c && String(c.type).startsWith('tale:')) { home = c; i = E.TALE_IDX[c.type.slice(5)]; } }
if (i == null || i < 0) return false;
const T = E.TALES[i];
if (id === 63) { storyStone(i, home); useCool = 0.8; return true; }
if (home) return false; // your own kit copy: its chest, bed, table and doors work like any other
if (id === 64) {
if (taleRead(i)) toast('The gate is open for you. Walk right in!');
else { toast(T.place + ' is locked.\nRead ' + T.title + ' in ABC Books to open it.', 5); sayTale(['locked']); }
return true;
}
const dy = b.y - E.KY, k = T.steps.findIndex(S => S.at ? S.at[0] === pk.lx && S.at[1] === dy && S.at[2] === pk.lz : S.id === id);
if (k < 0) return false;
useCool = 0.6;
if (!taleRead(i)) { toast('Read ' + T.title + ' in ABC Books first!', 4); sayTale(['locked']); return true; }
const st = taleState(T);
if (st.done) { toast('You finished this quest already. Well done!'); return true; }
if (k !== st.s) {
toast((k < st.s ? 'You did that already. Next: ' : 'Not yet! First: ') + T.steps[st.s].hint, 5);
sayTale([T.id + '-h' + st.s]); return true;
}
const S = T.steps[k], clips = [];
if (S.n) {
const spot = b.x + ',' + b.y + ',' + b.z;
if (st.got.includes(spot)) { toast('You found that one already. ' + S.hint, 4); return true; }
st.got.push(spot); const j = st.got.length - 1;
toast(S.say[j], 6); clips.push(T.id + '-s' + k + '-' + j);
if (st.got.length < S.n) { sfx('pop'); sayTale(clips); return true; }
st.got = [];
} else { toast(S.say, 6); clips.push(T.id + '-s' + k); }
st.s++;
[659, 784, 988].forEach((f, n) => tone(f, f, 0.14, 'triangle', 0.06, n * 0.09));
if (st.s >= T.steps.length) { // quest complete: the keepsake, the kit and the achievement
st.done = Date.now(); clips.push(T.id + '-win');
giveDrops([[T.keepId, 1], [T.kitId, 1]]);
announce('QUEST COMPLETE: ' + T.title.toUpperCase() + '!', T.win, '#FFDD77');
earn('tale_' + T.id, true); if (talesDone() >= E.TALES.length) earn('all_tales', true);
if (state === 'hero') renderHero();
}
sayTale(clips);
return true;
}
// ---------------------------------------------------------------- networking
function onMsg(m) {
switch (m.t) {
case 'welcome': { // a typed name + code only replaces the saved sign-in once the server has said yes
if (typed) { cfg.name = typed.name; cfg.code = typed.code; typed = null; }
cfg.signedIn = true; autoJoin = false; retries = 0; const saved = saveCfg(); updateMultiBtn(); startRemote(m);
if (!saved) toast('Could not save the sign-in: this device is out of storage');
break;
}
case 'error': // a wrong typed try leaves the saved sign-in alone; only a saved code the server refuses signs out
$('status').textContent = lastErr = m.text; autoJoin = false;
if (!typed) { cfg.signedIn = false; saveCfg(); updateMultiBtn(); }
typed = null; showMpForm(); if (link && link.ws) link.ws.close(); break;
case 'play': playNews(m); break;
case 'break': startBreak(m.until, m.name); break;
case 'busy': { // name is playing on another tablet: stay signed in, try again in a bit (frees up when that tablet leaves)
const auto = cfg.signedIn && !typed; typed = null; autoJoin = false;
$('status').textContent = lastErr = m.text + (auto ? ' Trying again...' : ' Pick your own name.'); if (link && link.ws) link.ws.close();
if (!auto) { showMpForm(); break; }
if (retries < 6) { retries++; rejoinLater(10000); }
break;
}
case 'blocks': if (link && link.local) break; // single player shares the sim's world: already changed
for (let i = 0; i < m.l.length; i += 4) world.set(m.l[i], m.l[i + 1], m.l[i + 2], m.l[i + 3]); break;
case 'snap': {
simTime = m.time;
const seen = new Set();
for (const a of m.mobs) {
seen.add(a[0]); let mo = mobs.get(a[0]);
if (!mo) { mo = { id: a[0], rx: a[2], ry: a[3], rz: a[4], ryaw: a[5], walk: 0 }; mobs.set(a[0], mo); }
Object.assign(mo, { type: a[1], x: a[2], y: a[3], z: a[4], yaw: a[5], fl: a[6], ex: a.length > 7 ? a.slice(7) : null }); // ex: boss [hp%, floor] or pet [name, owner, level]
}
for (const k of [...mobs.keys()]) if (!seen.has(k)) mobs.delete(k);
arrows = m.arrows; tnts = m.tnts;
const ps = new Set();
for (const p of m.players) {
if (p[0] === myId) continue; ps.add(p[0]);
let o = others.get(p[0]);
if (!o) { o = { id: p[0], rx: p[2], ry: p[3], rz: p[4], walk: 0 }; others.set(p[0], o); }
Object.assign(o, { name: p[1], x: p[2], y: p[3], z: p[4], yaw: p[5], pitch: p[6], dead: p[7] });
}
for (const k of [...others.keys()]) if (!ps.has(k)) others.delete(k);
const vs = new Set();
for (const a of m.vehicles || []) {
vs.add(a[0]); let v = vehicles.get(a[0]);
if (!v) { v = { id: a[0], rx: a[2], ry: a[3], rz: a[4], ryaw: a[5], spin: 0 }; vehicles.set(a[0], v); }
Object.assign(v, { kind: a[1], x: a[2], y: a[3], z: a[4], yaw: a[5], pitch: a[6], roll: a[7], rider: a[8], owner: a[9] || '' });
}
for (const k of [...vehicles.keys()]) if (!vs.has(k)) vehicles.delete(k);
if (ride && (!vehicles.has(ride.id) || vehicles.get(ride.id).rider !== myId)) { ride = null; engineSound(false); rideButtons(); }
break;
}
case 'vride': if (pl && !pl.dead && state === 'play') startRide(m); break;
case 'owned': {
const mine = l => (l || []).filter(c => c.owner.toLowerCase() === myName.toLowerCase()).length;
if (mine(m.list) > mine(owned)) earn('kit');
owned = m.list || []; break;
}
case 'kill': { // a monster you (or your pet) defeated: XP and achievements
const d = E.MOBS[m.type], base = d.base || m.type;
if (d.boss) {
addXp(100 + 50 * (m.floor || 1)); earn('boss');
giveDrops([[m.floor >= 3 ? 193 : 192, 1]]);
announce(d.name + ' IS DEFEATED!', (m.helped ? 'You helped beat it! ' : '') + 'The stairs to Floor ' + ((m.floor || 1) + 1) + ' are open in the middle of the room. Reward: a ' + (m.floor >= 3 ? 'Legendary' : 'Gold') + ' Loot Box.', '#FF5555');
break;
}
addXp({ zombie: 5, skeleton: 6, spider: 5, creeper: 7, raptor: 6, trike: 10, trex: 30, brachio: 12 }[base] || 2);
earn('first_blood');
if (m.pet) earn('pet_win');
const n = count('kill_' + base);
if (base === 'zombie' && n >= 10) earn('zombie10'); if (base === 'skeleton' && n >= 10) earn('skeleton10');
if (base === 'spider' && n >= 5) earn('spider5'); if (base === 'trex') earn('trex_down');
break;
}
case 'tp': { // went down or up a stairwell
leaveRide();
Object.assign(pl, { x: m.x, y: m.y, z: m.z, vx: 0, vy: 0, vz: 0, fallY: null }); if (m.yaw != null) pl.yaw = m.yaw;
state = 'loading'; $('loading').classList.remove('hidden');
$('loadText').textContent = m.floor ? 'FLOOR ' + m.floor : m.kingdom === 1 ? 'ONCE UPON A TIME...' : m.kingdom === 2 ? 'BACK HOME' : m.kingdom === 3 ? 'OFF TO ' + E.TALES[m.place].place.toUpperCase() + '...' : 'BACK TO THE SURFACE';
if (m.kingdom === 1) { earn('kingdom', true); if (!session.remote) fetchTales(); showStory('THE FAIRY TALE KINGDOM', E.TALE_LINES.welcome, '#FFDD77', 10); sayTale(['welcome']); }
if (m.kingdom === 3) toast('You are at ' + E.TALES[m.place].place + '.\nThe gate is in front of you, the story stone next to it.', 5);
if (m.floor) {
earn('dungeon'); if (m.floor >= 3) earn('floor3'); if (m.floor >= 5) earn('floor5');
const h = H(); if (m.floor > h.deepest) { h.deepest = m.floor; addXp(25 * m.floor); }
announce('FLOOR ' + m.floor, 'Start in the safe room (blue floor): no monsters, and you heal. Find the boss room to open the stairs down. The green stairwell takes you back up.', '#AA55FF');
}
break;
}
case 'petinfo': {
myPets = m.pets; const ps = (myPets && myPets.pets) || [];
if (m.got != null && ps[m.got]) { earn('pet'); announce('A NEW PET!', ps[m.got].name + ' the ' + E.PET_KINDS[ps[m.got].kind] + ' follows you now. Keep it fed with Pet Food!', '#FFAA00'); }
if (m.up != null && ps[m.up]) announce(ps[m.up].name.toUpperCase() + ' LEVELED UP!', 'Your pet is now level ' + ps[m.up].lvl + ' and hits harder.', '#FFAA00');
if (m.fed) toast('Yum! ' + m.fed + (m.fed.includes(' and ') ? ' are' : ' is') + ' happy.', 4);
if (m.room) announce('ROOM FOR ONE MORE PET!', m.room, '#FFAA00');
if (state === 'hero') renderHero();
break;
}
case 'petwarn': // level 1 hungry, 2 very hungry, 3 died of hunger
if (m.level === 1) toast(m.name + ' is hungry!\nTap Pet Food to feed your pets.', 6);
else if (m.level === 2) announce(m.name.toUpperCase() + ' IS VERY HUNGRY!', 'Feed ' + m.name + ' Pet Food right now, or ' + m.name + ' will die.', '#FF5555');
else announce(m.name.toUpperCase() + ' DIED', m.name + ' was too hungry. Remember to feed your pets!', '#AAAAAA');
break;
case 'nosleep': sleepEnd(); toast(m.text); break;
case 'wakeup': if (sleeping) setTimeout(sleepEnd, 1500); break;
case 'hurt': if (pl && !pl.dead && !creative()) { pl.vx += m.kx * 5; pl.vz += m.kz * 5; pl.vy = Math.max(pl.vy, 4); hurt(m.amt, 'You were slain by a monster', true);
if (m.src === 'trex' || m.src === 'dlord') earn('dino_snack'); if (m.src === 'boom') earn('kaboom'); } break;
case 'drop': giveDrops(m.items); break;
case 'tales': serverTales = m.tales || []; toast('ABC Books: new fairy tale places are open for you!', 4); break;
case 'chest': if (m.k === openChest) { chestSlots = m.slots.slice(); openInv('', m.k); } break;
case 'msg': toast(m.text); break;
case 'time': simTime = m.time; break;
case 'boom': sfx('boom', m.x, m.y, m.z); if (pl && Math.hypot(m.x - pl.x, m.z - pl.z) < 16) shake = 0.6; break;
case 'sfx': sfx(m.s, m.x, m.y, m.z); break;
}
}
function localLink() {
return { send: m => sim.handle(1, m), tick: dt => sim.tick(dt), local: true };
}
function remoteLink(name, code) {
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + BASE + 'ws');
const l = { ws, send: m => { if (ws.readyState === 1) ws.send(JSON.stringify(m)); }, tick: () => {}, local: false };
ws.onopen = () => { $('status').textContent = 'Connected, joining...'; ws.send(JSON.stringify({ t: 'join', name, code, dev: cfg.dev, typed: !!typed })); };
ws.onmessage = e => { try { onMsg(JSON.parse(e.data)); } catch (err) { console.error(err); } };
ws.onerror = () => { $('status').textContent = 'Could not reach the game server.'; };
ws.onclose = () => {
const playing = session && session.remote && state !== 'menu';
if (playing) { saveGame(); quitToMenu(true); autoJoin = cfg.signedIn; }
else if (!autoJoin || !link || link.ws !== ws) return; // a try that failed keeps going below; a closed-on-purpose one stops here
// stay signed in: keep reconnecting by itself, however long the Wi-Fi is out (server restarts, Wi-Fi blips)
if (autoJoin) {
tries++; $('menu').classList.add('hidden'); $('mpMenu').classList.remove('hidden'); hideMpForm();
$('status').textContent = 'Lost the connection, trying again... (' + tries + ')';
rejoinLater(tries < 6 ? 3000 : 10000);
} else {
if (lastErr) { $('menu').classList.add('hidden'); $('mpMenu').classList.remove('hidden'); showMpForm(); }
$('status').textContent = lastErr || 'Disconnected. Tap JOIN to try again.';
}
};
lastErr = '';
return l;
}
let retries = 0, lastErr = '', tries = 0, autoJoin = false, typed = null, rejoinTimer = 0;
function rejoinLater(ms) { // only while the "joining as ..." screen is up: BACK or SWITCH PLAYER stops it
clearTimeout(rejoinTimer);
rejoinTimer = setTimeout(() => {
if (state !== 'menu' || $('mpMenu').classList.contains('hidden') || $('mpSwitch').classList.contains('hidden')) return;
autoJoin = true; typed = null; link = remoteLink(cfg.name, cfg.code);
}, ms);
}
// ---------------------------------------------------------------- sessions, saving
const invSave = () => inv.map(s => s ? [s.id, s.n, s.d || 0] : 0);
const invLoad = a => { inv = new Array(36).fill(null); (a || []).forEach((s, i) => { if (s && i < 36) inv[i] = { id: s[0], n: s[1] }; if (s && s[2]) inv[i].d = s[2]; }); };
const playerData = () => ({ x: pl.x, y: ride ? groundBelow(pl.x, pl.y, pl.z) : pl.y, z: pl.z, yaw: pl.yaw, pitch: pl.pitch, hp: pl.hp, food: pl.food, inv: invSave(), sel, spawn: pl.spawn, fuel: pl.fuel, mode: pl.mode, armor: pl.armor, hero: H() });
function listWorlds() { try { return JSON.parse(localStorage.getItem('blockcraft_worlds') || '[]'); } catch (e) { return []; } }
function saveWorldList(l) { try { localStorage.setItem('blockcraft_worlds', JSON.stringify(l)); } catch (e) {} }
function saveGame() {
if (!session || !pl) return;
if (session.remote) { link.send({ t: 'save', data: playerData() }); return; }
const data = { seed: world.seed, time: sim.time, edits: world.encodeEdits(), chests: sim.chests, vehicles: sim.saveVehicles(), owned: sim.owned, dungeon: sim.dungeon, pets: sim.petData, kingdom: sim.kingdom, spawn: session.spawn, player: playerData() };
try { localStorage.setItem('blockcraft_w_' + session.id, JSON.stringify(data)); }
catch (e) { toast('Could not save: this device is out of storage'); }
const l = listWorlds(), w = l.find(q => q.id === session.id); if (w) { w.played = Date.now(); saveWorldList(l); }
}
function resetSessionState() {
for (const m of chunkGL.values()) { gl.deleteBuffer(m.vbo); gl.deleteBuffer(m.wvbo); }
chunkGL.clear(); mapTiles.clear(); mobs.clear(); others.clear(); vehicles.clear(); arrows = []; tnts = [];
ride = null; engineSound(false); owned = []; myPets = null; airfields = []; inSafe = false; announceQ.length = 0; announceT = 0; $('announce').classList.add('hidden');
target = null; breakT = 0; picked = -1; openChest = null;
}
function beginPlay() {
$('menu').classList.add('hidden'); $('spMenu').classList.add('hidden'); $('mpMenu').classList.add('hidden');
$('loading').classList.remove('hidden'); $('loadText').textContent = 'BUILDING WORLD...';
state = 'loading'; lastStats = ''; renderHotbar();
}
function enterWorld() {
$('loading').classList.add('hidden'); $('bar').classList.remove('hidden'); $('topbtns').classList.remove('hidden');
for (const id of ['bJump', 'bDown', 'bFly']) $(id).classList.remove('hidden');
rideButtons();
state = 'play'; renderHotbar(); renderStats();
toast(session.remote ? 'Welcome, ' + session.name + '!' : session.name);
if (!(myPets && myPets.gift)) link.send({ t: 'petgift' }); // once per name: 6 Pet Food (the server keeps track)
}
function startLocal(w) {
let data = null;
try { data = JSON.parse(localStorage.getItem('blockcraft_w_' + w.id) || 'null'); } catch (e) {}
resetSessionState();
sim = new E.Sim({ seed: w.seed, difficulty: w.diff, time: data ? data.time : 0.02, chests: data ? data.chests : {}, vehicles: data ? data.vehicles : [], owned: data && data.owned || [], dungeon: data && data.dungeon, pets: data && data.pets || {}, kingdom: data && data.kingdom,
send: (m, to) => { if (to == null || to === 1) onMsg(m); } });
world = sim.world;
if (data && data.edits) world.decodeEdits(data.edits);
const simChange = world.onChange; world.onChange = (...a) => { simChange(...a); clientOnChange(...a); };
link = localLink(); myId = 1; myName = 'You'; owned = sim.owned;
const spawn = (data && data.spawn) || sim.spawnPoint();
session = { id: w.id, name: w.name, remote: false, spawn };
sim.ensureEntrance(spawn); sim.ensureKingdomGate(spawn); session.kingdomGate = sim.kingdom.gate; sim.ensureAirfields(spawn); airfields = sim.dungeon.air || []; myPets = sim.petsOf('you'); serverTales = []; fetchTales();
pl = newPlayer(spawn, w.mode);
if (data && data.player) { const p = data.player; Object.assign(pl, { x: p.x, y: p.y, z: p.z, yaw: p.yaw, pitch: p.pitch, hp: p.hp, food: p.food, spawn: p.spawn, fuel: p.fuel || 0 }); if (p.armor) pl.armor = p.armor.slice(0, 4); if (p.hero) pl.hero = p.hero; invLoad(p.inv); sel = p.sel || 0; }
else { inv = new Array(36).fill(null); sel = 0; if (w.mode === 'creative') [1, 4, 5, 6, 11, 22, 115, 21, 19].forEach((id, i) => { inv[i] = { id, n: E.stackSize(id) }; }); }
sim.addPlayer(1, 'You', pl);
beginPlay();
}
function startRemote(m) {
resetSessionState();
sim = null;
world = new E.World(m.seed);
world.decodeEdits(m.edits || {});
world.onChange = clientOnChange;
myId = m.id; myName = m.name; simTime = m.time; owned = m.owned || []; myPets = m.pet || null; airfields = m.air || []; serverTales = m.tales || [];
session = { remote: true, name: m.name, spawn: m.spawn, kingdomGate: m.kingdom || null };
pl = newPlayer(m.spawn, cfg.mpMode);
if (m.you) { const p = m.you; Object.assign(pl, { x: p.x, y: p.y, z: p.z, yaw: p.yaw || 0, pitch: p.pitch || 0, hp: p.hp || 20, food: p.food || 20, spawn: p.spawn || null, fuel: p.fuel || 0 }); if (p.armor) pl.armor = p.armor.slice(0, 4); if (p.hero) pl.hero = p.hero; invLoad(p.inv); sel = p.sel || 0; }
else { inv = new Array(36).fill(null); sel = 0; }
pl.mode = cfg.mpMode;
if (pl.mode === 'creative' && !inv.some(Boolean)) [1, 4, 5, 6, 11, 22, 115, 21, 19].forEach((id, i) => { inv[i] = { id, n: E.stackSize(id) }; });
beginPlay();
}
function quitToMenu(skipSave) {
if (!skipSave) { leaveRide(); saveGame(); }
if (link && link.ws) { const ws = link.ws; session = null; ws.close(); }
session = null; state = 'menu'; releasePointer();
sleeping = false; clearInterval(sleepHeal);
for (const id of ['bar', 'topbtns', 'bJump', 'bDown', 'bFly', 'bExit', 'pause', 'dead', 'inv', 'mapPanel', 'loading', 'hero', 'sleepPanel']) $(id).classList.add('hidden');
$('menu').classList.remove('hidden'); $('coords').textContent = '';
resetSessionState(); pl = null; world = null; sim = null;
}
// ---------------------------------------------------------------- menus
function pickRow(rowId, val) { for (const b of $(rowId).children) b.classList.toggle('on', b.dataset.v === val); }
const rowVal = rowId => { const b = [...$(rowId).children].find(q => q.classList.contains('on')); return b ? b.dataset.v : null; };
for (const r of ['nwMode', 'nwDiff', 'mpMode']) $(r).addEventListener('click', e => { if (e.target.dataset.v) pickRow(r, e.target.dataset.v); });
$('optSound').checked = cfg.sound;
$('optSound').onchange = () => { cfg.sound = $('optSound').checked; saveCfg(); };
function showWorlds() {
const l = listWorlds().sort((a, b) => (b.played || 0) - (a.played || 0));
$('worldList').innerHTML = l.length ? l.map(w => '<div class="world"><div class="wn">' + w.name.replace(/</g, '<') + '<small>' + (w.mode === 'creative' ? 'Creative' : 'Survival · ' + w.diff) +
' · seed ' + w.seed + '</small></div><button class="btn small" data-play="' + w.id + '">PLAY</button><button class="btn small red" data-del="' + w.id + '">DELETE</button></div>').join('')
: '<div class="sub">No worlds yet. Make one below!</div>';
}
function goSingle() { $('menu').classList.add('hidden'); $('spMenu').classList.remove('hidden'); showWorlds(); }
$('mSingle').onclick = () => {
audio(); if (!glOK) return;
const go = goSingle;
if (!(cfg.signedIn && cfg.name)) { askWho(go); return; } // single player counts toward the kid's play time too
playApi({ name: cfg.name, code: cfg.code }).then(j => { if (j.breakUntil) startBreak(j.breakUntil, j.name); else go(); });
};
$('spBack').onclick = () => { $('spMenu').classList.add('hidden'); $('menu').classList.remove('hidden'); };
$('worldList').addEventListener('click', e => {
const p = e.target.dataset.play, d = e.target.dataset.del;
if (p) { const w = listWorlds().find(q => q.id === p); if (w) startLocal(w); }
if (d) {
if (e.target.dataset.sure) { saveWorldList(listWorlds().filter(q => q.id !== d)); try { localStorage.removeItem('blockcraft_w_' + d); } catch (er) {} showWorlds(); }
else { e.target.dataset.sure = '1'; e.target.textContent = 'SURE?'; }
}
});
$('nwGo').onclick = () => {
const name = $('nwName').value.trim() || 'My World';
const st = $('nwSeed').value.trim();
const seed = st ? (/^-?\d+$/.test(st) ? parseInt(st, 10) : hashStr(st) | 0) : (Math.random() * 2147483647) | 0;
const w = { id: 'w' + Date.now().toString(36), name, seed, mode: rowVal('nwMode'), diff: rowVal('nwDiff'), played: Date.now() };
const l = listWorlds(); l.push(w); saveWorldList(l);
startLocal(w);
};
const KIDS = ['Lavon', 'Layla', 'Lilly', 'Luca', 'Dietrich', 'Seyna'];
$('mpNames').innerHTML = KIDS.map(n => '<button class="btn small" data-n="' + n + '">' + n.toUpperCase() + '</button>').join('');
$('mpNames').addEventListener('click', e => { if (e.target.dataset.n) { $('mpName').value = e.target.dataset.n; for (const b of $('mpNames').children) b.classList.toggle('on', b === e.target); } });
if (cfg.signedIn === undefined && cfg.name && cfg.code) cfg.signedIn = true; // joined before this option existed
function updateMultiBtn() { $('mMulti').textContent = cfg.signedIn && cfg.name ? 'PLAY TOGETHER AS ' + cfg.name.toUpperCase() : 'PLAY TOGETHER'; }
function showMpForm() { for (const el of $('mpMenu').querySelectorAll('.row, #mpGo')) el.classList.remove('hidden'); $('mpSwitch').classList.add('hidden'); }
function hideMpForm() {
for (const el of $('mpMenu').querySelectorAll('.row, #mpGo')) el.classList.add('hidden');
$('mpSwitch').classList.remove('hidden'); $('mpSwitch').textContent = 'NOT ' + cfg.name.toUpperCase() + '?';
}
updateMultiBtn();
// ---------------------------------------------------------------- who is playing + play time
// The Amazon Kids browser forgets this tablet's saved sign-in whenever it closes, so every game starts by picking
// a name: at home the kids just tap theirs (the server knows the house's address), away from home it needs the code.
// The server counts each name's play time: 30 minutes, then the PLUG ME IN screen for a 1 hour break.
let breakUntil = 0, breakTimer = 0, warnedAt = 0;
async function playApi(body, what) {
try {
const r = await fetch(BASE + 'api/' + (what || 'play'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
return Object.assign({ ok: r.ok }, await r.json());
} catch (e) { return { ok: false, offline: true }; } // no server: single player still works, just untimed
}
async function askWho(then) {
$('menu').classList.add('hidden'); $('mpMenu').classList.add('hidden'); $('whoPanel').classList.remove('hidden');
$('whoStatus').textContent = 'Looking...'; $('whoNames').replaceChildren();
const w = await playApi({}, 'who'), names = w.home && w.names.length ? w.names : KIDS;
$('whoCodeRow').classList.toggle('hidden', !!w.home); $('whoCode').value = '';
$('whoStatus').textContent = w.home ? 'Tap your name.' : 'Tap your name and type the family code first.';
for (const n of names) {
const b = document.createElement('button'); b.className = 'btn'; b.textContent = n.toUpperCase();
b.onclick = async () => {
const code = w.home ? '' : $('whoCode').value.trim();
$('whoStatus').textContent = 'Checking...';
const j = await playApi({ name: n, code });
if (j.offline) { // no game server: single player still works (untimed), Play Together needs the server
cfg.name = n; saveCfg(); $('whoPanel').classList.add('hidden'); if (then === goSingle) then(); else { $('menu').classList.remove('hidden'); toast('Could not reach the game server.'); } return;
}
if (!j.ok) { $('whoStatus').textContent = j.error || 'Something went wrong.'; return; }
cfg.name = j.name; cfg.code = code; cfg.signedIn = true; saveCfg(); updateMultiBtn();
$('whoPanel').classList.add('hidden');
if (j.breakUntil) startBreak(j.breakUntil, j.name); else then();
};
$('whoNames').append(b);
}
}
$('whoBack').onclick = () => { $('whoPanel').classList.add('hidden'); $('menu').classList.remove('hidden'); };
function playNews(j) { // minutes left from the server: say so at 5 and 1 minutes
if (j.breakUntil) { startBreak(j.breakUntil, cfg.name); return; }
if (j.left == null || !session) return;
if (j.left > 300) warnedAt = 0;
else if (j.left > 60 && warnedAt !== 5) { warnedAt = 5; toast('5 more minutes, then a break. Find a good place to stop!', 6); }
else if (j.left <= 60 && warnedAt !== 1) { warnedAt = 1; toast('1 more minute, then a break!', 6); }
}
function startBreak(until, name) {
breakUntil = until; autoJoin = false; clearTimeout(rejoinTimer);
if (session) quitToMenu(false); // saves first (single player world, or the player over the connection)
for (const id of ['menu', 'spMenu', 'mpMenu', 'whoPanel']) $(id).classList.add('hidden');
$('breakWho').textContent = 'Time for a break' + (name ? ', ' + name : '') + '! Put the tablet on the charger.';
$('breakPanel').classList.remove('hidden');
clearInterval(breakTimer); breakTimer = setInterval(showBreakLeft, 1000); showBreakLeft();
}
function showBreakLeft() {
const min = Math.ceil((breakUntil - Date.now()) / 60000);
if (min <= 0) { clearInterval(breakTimer); $('breakPanel').classList.add('hidden'); $('menu').classList.remove('hidden'); return; }
$('breakLeft').textContent = 'You can play again in ' + min + (min === 1 ? ' minute.' : ' minutes.');
}
// single player: tell the server every 30 seconds while a kid is really playing (screen on, in a world)
setInterval(() => {
if (session && !session.remote && state !== 'menu' && !document.hidden && cfg.signedIn && cfg.name)
playApi({ name: cfg.name, code: cfg.code, ping: true }).then(j => { if (j.ok) playNews(j); });
}, 30000);
if (cfg.signedIn && cfg.name) playApi({ name: cfg.name, code: cfg.code }).then(j => { if (j.breakUntil) startBreak(j.breakUntil, j.name); });
$('mMulti').onclick = () => {
audio(); if (!glOK) return;
if (!(cfg.signedIn && cfg.name)) { askWho(() => $('mMulti').click()); return; }
$('menu').classList.add('hidden'); $('mpMenu').classList.remove('hidden');
$('mpName').value = cfg.name || ''; $('mpCode').value = cfg.code || ''; pickRow('mpMode', cfg.mpMode || 'survival'); $('status').textContent = '';
for (const b of $('mpNames').children) b.classList.toggle('on', b.dataset.n === cfg.name);
if (cfg.signedIn && cfg.name) { // already signed in on this tablet: go straight in
hideMpForm();
$('status').textContent = 'Joining as ' + cfg.name + '...'; retries = 0; tries = 0; autoJoin = true; typed = null;
link = remoteLink(cfg.name, cfg.code);
} else showMpForm();
};
$('mpSwitch').onclick = () => { // opens WHO IS PLAYING: the saved sign-in stays until another name really gets in
clearTimeout(rejoinTimer); autoJoin = false; typed = null;
if (link && link.ws) link.ws.close();
askWho(() => $('mMulti').click());
};
for (const id of ['mpName', 'mpCode']) $(id).addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); $(id).blur(); $('mpGo').click(); } });
$('mpBack').onclick = () => { clearTimeout(rejoinTimer); autoJoin = false; typed = null; $('mpMenu').classList.add('hidden'); $('menu').classList.remove('hidden'); };
$('mpGo').onclick = () => {
const name = $('mpName').value.trim();
if (!name) { $('status').textContent = 'Pick your name first'; return; }
if (link && link.ws && link.ws.readyState <= 1) link.ws.close(); // JOIN tapped twice: only the last try counts
typed = { name, code: $('mpCode').value.trim() }; cfg.mpMode = rowVal('mpMode'); saveCfg(); autoJoin = false;
$('status').textContent = 'Connecting...';
link = remoteLink(name, typed.code);
};
function openPause() {
if (state !== 'play') return;
state = 'pause'; releasePointer(); $('pause').classList.remove('hidden');
pickRow('pDist', String(cfg.dist)); $('pSound').checked = cfg.sound; $('pCoords').checked = cfg.coords;
$('pMode').textContent = creative() ? 'CREATIVE' : 'SURVIVAL';
saveGame();
}
function resume() { $('pause').classList.add('hidden'); state = 'play'; }
// sleeping in a bed: the screen goes dark, you heal, WAKE UP gets you up. At night, everyone in bed = morning (the server says wakeup).
let sleeping = false, sleepHeal = 0;
function sleepStart(b) {
if (state !== 'play') return;
sleeping = true; state = 'sleep'; releasePointer();
Object.assign(pl, { x: b.x + 0.5, z: b.z + 0.5, vx: 0, vz: 0 });
$('sleepPanel').classList.remove('hidden');
clearInterval(sleepHeal); sleepHeal = setInterval(() => { if (pl && pl.hp < maxHp()) { pl.hp = Math.min(maxHp(), pl.hp + 1); lastStats = ''; } }, 2000);
}
function sleepEnd() {
clearInterval(sleepHeal);
if (!sleeping) return;
sleeping = false; $('sleepPanel').classList.add('hidden');
if (state === 'sleep') state = 'play';
if (link) link.send({ t: 'wake' });
}
$('sleepWake').onclick = sleepEnd;
$('pResume').onclick = resume;
$('pDist').addEventListener('click', e => { if (e.target.dataset.v) { cfg.dist = +e.target.dataset.v; saveCfg(); pickRow('pDist', e.target.dataset.v); } });
$('pSound').onchange = () => { cfg.sound = $('pSound').checked; saveCfg(); };
$('pCoords').onchange = () => { cfg.coords = $('pCoords').checked; saveCfg(); if (!cfg.coords) $('coords').textContent = ''; };
$('pMode').onclick = () => {
pl.mode = creative() ? 'survival' : 'creative'; pl.fly = false;
if (session.remote) { cfg.mpMode = pl.mode; saveCfg(); }
else { const l = listWorlds(), w = l.find(q => q.id === session.id); if (w) { w.mode = pl.mode; saveWorldList(l); } }
$('pMode').textContent = creative() ? 'CREATIVE' : 'SURVIVAL';
rideButtons();
$('palette').innerHTML = ''; lastStats = '';
};
$('pQuit').onclick = () => quitToMenu(false);
document.addEventListener('visibilitychange', () => { if (document.hidden && session) { saveGame(); if (state === 'play') openPause(); } });
addEventListener('beforeunload', () => { if (session) saveGame(); });
// ---------------------------------------------------------------- rendering
function resize() {
const scale = isTouch ? Math.min(devicePixelRatio || 1, 1.25) : Math.min(devicePixelRatio || 1, 2);
cv.width = Math.round(innerWidth * scale); cv.height = Math.round(innerHeight * scale);
hud.width = innerWidth; hud.height = innerHeight;
}
addEventListener('resize', resize); resize();
const lerpC = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
let lastMVP = null;
const RO = [0, 0, 0]; // render origin near the camera: the GPU only sees positions relative to it (see vert)
function render(dt) {
const dl = E.dayLight(simTime);
const eye = [pl.x, pl.y + 1.62, pl.z];
if (ride) { // camera behind and above, pulled in if a wall is in the way
const f0 = fwd(), cx = ride.x, cy = ride.y + 1.6, cz = ride.z;
let d = E.VEHICLES[ride.kind].plane ? 8 : 7;
const h = E.raycast(world, cx, cy, cz, -f0[0], -f0[1], -f0[2], d, false);
if (h) d = Math.max(1.2, h.d - 0.4);
eye[0] = cx - f0[0] * d; eye[1] = cy - f0[1] * d + 0.8; eye[2] = cz - f0[2] * d;
}
if (shake > 0) { eye[0] += (Math.random() - 0.5) * shake * 0.3; eye[1] += (Math.random() - 0.5) * shake * 0.3; shake -= dt; }
const under = world.peek(Math.floor(eye[0]), Math.floor(eye[1]), Math.floor(eye[2])) === 10;
let sky = lerpC([0.03, 0.04, 0.12], [0.56, 0.74, 0.95], clamp((dl - 0.12) / 0.88, 0, 1));
const fogEnd = cfg.dist * CS, fogStart = fogEnd * 0.5;
let fog = [fogStart, fogEnd];
if (under) { sky = [0.08, 0.16, 0.45]; fog = [0, 12]; }
else if (E.inDungeon(pl.x)) { sky = [0.02, 0.015, 0.04]; fog = [10, 34]; } // the dungeon: dark, short sight
gl.viewport(0, 0, cv.width, cv.height);
gl.clearColor(sky[0], sky[1], sky[2], 1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const proj = perspective(70 * Math.PI / 180, cv.width / cv.height, 0.05, fogEnd + 32);
RO[0] = Math.floor(eye[0] / CS) * CS; RO[2] = Math.floor(eye[2] / CS) * CS;
const rel = [eye[0] - RO[0], eye[1], eye[2] - RO[2]];
const mvp = mul(proj, viewMat(pl.yaw, pl.pitch, rel[0], rel[1], rel[2])); // for the GPU (origin RO)
const mvpW = mul(proj, viewMat(pl.yaw, pl.pitch, eye[0], eye[1], eye[2])); lastMVP = mvpW; // world coords, for HUD labels
// sun and moon
gl.useProgram(flat); gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE);
gl.enableVertexAttribArray(flat.a);
const ang = simTime * Math.PI * 2;
for (const [s, col] of [[1, [1, 0.97, 0.75, 1]], [-1, [0.85, 0.88, 0.95, 1]]]) {
const dx = Math.cos(ang) * s, dy = Math.sin(ang) * s;
if (dy < -0.15) continue;
const cx = rel[0] + dx * 80, cy = rel[1] + dy * 80, cz = rel[2] + 10, r = s > 0 ? 7 : 5;
const ux = -dy * r, uy = dx * r;
const q = new Float32Array([cx - ux, cy - uy, cz - r, cx + ux, cy + uy, cz - r, cx + ux, cy + uy, cz + r, cx - ux, cy - uy, cz - r, cx + ux, cy + uy, cz + r, cx - ux, cy - uy, cz + r]);
gl.bindBuffer(gl.ARRAY_BUFFER, dynVBO); gl.bufferData(gl.ARRAY_BUFFER, q, gl.DYNAMIC_DRAW);
gl.vertexAttribPointer(flat.a, 3, gl.FLOAT, false, 0, 0);
gl.uniformMatrix4fv(flat.uM, false, mvp); gl.uniform4fv(flat.uC, col);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
gl.disableVertexAttribArray(flat.a);
// world
gl.useProgram(prog); gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE);
gl.enableVertexAttribArray(prog.a.p); gl.enableVertexAttribArray(prog.a.t); gl.enableVertexAttribArray(prog.a.l);
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, atlasTex);
gl.uniform1i(prog.u.uTex, 0); gl.uniformMatrix4fv(prog.u.uM, false, mvp); gl.uniform3fv(prog.u.uCam, rel);
gl.uniform1f(prog.u.uDay, 0.28 + dl * 0.72); gl.uniform2fv(prog.u.uFog, fog); gl.uniform3fv(prog.u.uFogC, sky);
gl.uniform1f(prog.u.uMin, pl.fx.night > 0 ? 0.75 : E.inDungeon(pl.x) ? (H().cls === 'explorer' ? 0.4 : 0.28) : H().cls === 'explorer' ? 0.2 : 0.04); // night vision potion: dark places look lit
gl.uniform1f(prog.u.uAlpha, 1); gl.uniform4fv(prog.u.uTint, [0, 0, 0, 0]);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, quadIBO);
const f = fwd(), visible = [];
for (const m of chunkGL.values()) {
const rx = m.cx * CS + 8 - eye[0], rz = m.cz * CS + 8 - eye[2];
if (rx * f[0] + rz * f[2] < -14 * Math.SQRT2 - 8 && Math.abs(f[1]) < 0.8) continue;
if (Math.hypot(rx, rz) > fogEnd + 24) continue;
visible.push(m);
if (!m.n) continue;
gl.uniform3f(prog.u.uOff, m.cx * CS - RO[0], 0, m.cz * CS - RO[2]);
gl.bindBuffer(gl.ARRAY_BUFFER, m.vbo); bindAttribs();
gl.drawElements(gl.TRIANGLES, m.n, IDX_TYPE(), 0);
}
gl.uniform3f(prog.u.uOff, 0, 0, 0); // models below are already relative to RO
// mobs, players, arrows, tnt
const k = Math.min(1, dt * 12);
for (const mo of mobs.values()) {
const d0 = Math.hypot(mo.x - mo.rx, mo.z - mo.rz);
mo.rx += (mo.x - mo.rx) * k; mo.ry += (mo.y - mo.ry) * k; mo.rz += (mo.z - mo.rz) * k;
let dy = mo.yaw - mo.ryaw; while (dy > Math.PI) dy -= 2 * Math.PI; while (dy < -Math.PI) dy += 2 * Math.PI; mo.ryaw += dy * k;
if (mo.fl & 8) mo.walk += dt * 9; else mo.walk *= 0.9;
const type = E.MOB_TYPES[mo.type], md = E.MOBS[type], base = md.base || type;
const tint = mo.fl & 1 ? [1, 0, 0, 0.45] : mo.fl & 2 ? [1, 1, 1, 0.65] : mo.fl & 4 ? [1, 0.5, 0, 0.3] : md.boss ? [0.4, 0, 0.6, 0.18] : null;
drawModel(MODELS[base], mo.rx, mo.ry, mo.rz, mo.ryaw, mo.walk, 0, tint, base === 'zombie', (md.scale || 1) * (base === 'creeper' && mo.fl & 2 ? 1.08 : 1));
if (type === 'zombie' && d0 >= 0) { groanT -= dt * 0.15; }
}
if (groanT <= 0) { groanT = 6 + Math.random() * 8; const z = [...mobs.values()].find(q => E.MOB_TYPES[q.type] === 'zombie'); if (z) sfx('groan', z.rx, z.ry, z.rz); }
const riders = new Set();
for (const v of vehicles.values()) {
if (v.rider) riders.add(v.rider);
if (ride && v.id === ride.id) continue;
v.rx += (v.x - v.rx) * k; v.ry += (v.y - v.ry) * k; v.rz += (v.z - v.rz) * k; v.ryaw += angDiff(v.yaw, v.ryaw) * k;
v.rp = (v.rp || 0) + (v.pitch - (v.rp || 0)) * k; v.rr = (v.rr || 0) + (v.roll - (v.rr || 0)) * k;
v.spin += dt * (v.rider ? 30 : 0);
drawVehicle(vehicleBoxes(E.VEH_TYPES[v.kind], paintFor(v.owner), !!v.rider), v.rx, v.ry, v.rz, v.ryaw + Math.PI, v.rp, v.rr, v.spin);
}
if (ride) drawVehicle(vehicleBoxes(ride.kind, paintFor(myName), true), ride.x, ride.y, ride.z, ride.yaw + Math.PI, ride.pitch, ride.roll, ride.spin);
for (const o of others.values()) {
const d0 = Math.hypot(o.x - o.rx, o.z - o.rz);
o.rx += (o.x - o.rx) * k; o.ry += (o.y - o.ry) * k; o.rz += (o.z - o.rz) * k;
o.walk += d0 > 0.02 ? dt * 9 : 0;
if (!o.dead && !riders.has(o.id)) drawModel(MODELS.player, o.rx, o.ry, o.rz, o.yaw + Math.PI, o.walk, o.pitch, null, false);
}
for (const a of arrows) {
const yaw = Math.atan2(a[4], a[6]);
drawModel([{ b: [-0.04, -0.04, -0.3, 0.04, 0.04, 0.3], f: T.arrow_tex, o: T.arrow_tex }], a[1], a[2], a[3], yaw, 0, 0, null);
}
for (const tn of tnts) {
const def = blk(32);
drawModel([{ b: [-0.49, 0, -0.49, 0.49, 0.98, 0.49], f: def.tex[2], o: def.tex[2] }], tn[1], tn[2], tn[3], 0, 0, 0, tn[4] ? [1, 1, 1, 0.6] : null);
}
// water
gl.uniform4fv(prog.u.uTint, [0, 0, 0, 0]);
gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false); gl.disable(gl.CULL_FACE);
gl.uniform1f(prog.u.uAlpha, 0.72);
for (const m of visible) { if (!m.wn) continue; gl.uniform3f(prog.u.uOff, m.cx * CS - RO[0], 0, m.cz * CS - RO[2]); gl.bindBuffer(gl.ARRAY_BUFFER, m.wvbo); bindAttribs(); gl.drawElements(gl.TRIANGLES, m.wn, IDX_TYPE(), 0); }
gl.depthMask(true); gl.disable(gl.BLEND); gl.uniform3f(prog.u.uOff, 0, 0, 0);
gl.disableVertexAttribArray(prog.a.p); gl.disableVertexAttribArray(prog.a.t); gl.disableVertexAttribArray(prog.a.l);
// block outline
if (target && target.block) {
const b = target.block, d = blk(b.id), e = 0.003, bx = b.x - RO[0], bz = b.z - RO[2];
const x0 = bx - e, y0 = b.y - e, z0 = bz - e, x1 = bx + 1 + e, y1 = b.y + (d.h < 1 ? d.h : 1) + e, z1 = bz + 1 + e;
const L = new Float32Array([x0, y0, z0, x1, y0, z0, x1, y0, z0, x1, y0, z1, x1, y0, z1, x0, y0, z1, x0, y0, z1, x0, y0, z0,
x0, y1, z0, x1, y1, z0, x1, y1, z0, x1, y1, z1, x1, y1, z1, x0, y1, z1, x0, y1, z1, x0, y1, z0,
x0, y0, z0, x0, y1, z0, x1, y0, z0, x1, y1, z0, x1, y0, z1, x1, y1, z1, x0, y0, z1, x0, y1, z1]);
gl.useProgram(flat); gl.enableVertexAttribArray(flat.a);
gl.bindBuffer(gl.ARRAY_BUFFER, dynVBO); gl.bufferData(gl.ARRAY_BUFFER, L, gl.DYNAMIC_DRAW);
gl.vertexAttribPointer(flat.a, 3, gl.FLOAT, false, 0, 0);
gl.uniformMatrix4fv(flat.uM, false, mvp); gl.uniform4fv(flat.uC, [0, 0, 0, 0.8]);
gl.drawArrays(gl.LINES, 0, 24); gl.disableVertexAttribArray(flat.a);
}
drawHUD(under, mvp);
}
function project(mvp, x, y, z) {
const cx = mvp[0] * x + mvp[4] * y + mvp[8] * z + mvp[12], cy = mvp[1] * x + mvp[5] * y + mvp[9] * z + mvp[13], cw = mvp[3] * x + mvp[7] * y + mvp[11] * z + mvp[15];
if (cw <= 0.1) return null;
return [(cx / cw * 0.5 + 0.5) * hud.width, (1 - (cy / cw * 0.5 + 0.5)) * hud.height];
}
function drawHUD(under, mvp) {
const W = hud.width, H = hud.height;
hx.clearRect(0, 0, W, H);
if (under) { hx.fillStyle = 'rgba(20,50,160,.25)'; hx.fillRect(0, 0, W, H); }
const cx = W / 2, cy = H / 2;
hx.strokeStyle = 'rgba(255,255,255,.85)'; hx.lineWidth = 2;
if (!ride) { hx.beginPath(); hx.moveTo(cx - 9, cy); hx.lineTo(cx + 9, cy); hx.moveTo(cx, cy - 9); hx.lineTo(cx, cy + 9); hx.stroke(); }
// potion effects still running, top left
let fy = ride ? 80 : 30;
hx.font = 'bold 15px "Lucida Console",monospace'; hx.textAlign = 'left';
for (const k in pl.fx) { hx.fillStyle = '#000'; hx.fillText(FX_NAMES[k] + ' ' + Math.ceil(pl.fx[k]), 13, fy + 1); hx.fillStyle = '#FF77FF'; hx.fillText(FX_NAMES[k] + ' ' + Math.ceil(pl.fx[k]), 12, fy); fy += 20; }
if (ride) { // flying: speed and height instead of the crosshair
const sp = E.VEHICLES[ride.kind].plane ? ride.speed : Math.hypot(ride.vx, ride.vz);
hx.font = 'bold 18px "Lucida Console",monospace'; hx.textAlign = 'left'; hx.fillStyle = '#FFFF55';
hx.fillText('SPEED ' + Math.round(sp * 3.6) + ' HEIGHT ' + Math.max(0, Math.floor(ride.y - E.SEA)), 12, 30);
if (E.VEHICLES[ride.kind].plane && ride.speed < 12) { hx.fillStyle = '#fff'; hx.fillText(ride.onGround ? 'Go faster to take off' : 'Too slow!', 12, 54); }
}
else if (breakT > 0 && target && target.veh) { hx.strokeStyle = '#55FF55'; hx.lineWidth = 4; hx.beginPath(); hx.arc(cx, cy, 18, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * Math.min(1, breakT)); hx.stroke(); }
else if (breakT > 0 && target && target.block) {
const tt = breakTime(target.block.id);
if (tt > 0 && tt < Infinity) { hx.strokeStyle = '#FFFF55'; hx.lineWidth = 4; hx.beginPath(); hx.arc(cx, cy, 18, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * Math.min(1, breakT / tt)); hx.stroke(); }
}
hx.font = '14px "Lucida Console",monospace'; hx.textAlign = 'center';
for (const o of others.values()) {
if (o.dead) continue;
const p = project(mvp, o.rx, o.ry + 2.2, o.rz); if (!p) continue;
const w = hx.measureText(o.name).width + 8;
hx.fillStyle = 'rgba(0,0,0,.5)'; hx.fillRect(p[0] - w / 2, p[1] - 14, w, 18);
hx.fillStyle = '#fff'; hx.fillText(o.name, p[0], p[1]);
}
// pet name tags, and the health bar of a floor boss you are near
let boss = null;
for (const mo of mobs.values()) {
const md = E.MOBS[E.MOB_TYPES[mo.type]];
if (md.boss && mo.ex && Math.hypot(mo.rx - pl.x, mo.rz - pl.z) < 40) boss = { md, hp: mo.ex[0] };
if (md.pet && mo.ex && Math.hypot(mo.rx - pl.x, mo.rz - pl.z) < 24) {
const p = project(mvp, mo.rx, mo.ry + md.h + 0.5, mo.rz); if (!p) continue;
const label = mo.ex[0] + ' (lv ' + mo.ex[2] + ')', w = hx.measureText(label).width + 8;
hx.fillStyle = 'rgba(0,0,0,.5)'; hx.fillRect(p[0] - w / 2, p[1] - 14, w, 18);
hx.fillStyle = PAINTS[paintFor(mo.ex[1])]; hx.fillText(label, p[0], p[1]);
}
}
if (boss) {
const bw = Math.min(W * 0.6, 420), bx = (W - bw) / 2, by = H - Math.min(150, H * 0.24); // above the hotbar, clear of the announcer
hx.fillStyle = 'rgba(0,0,0,.6)'; hx.fillRect(bx - 4, by - 22, bw + 8, 38);
hx.fillStyle = '#FF5555'; hx.font = 'bold 15px "Lucida Console",monospace'; hx.fillText(boss.md.name, W / 2, by - 6);
hx.fillStyle = '#400'; hx.fillRect(bx, by, bw, 10); hx.fillStyle = '#e02020'; hx.fillRect(bx, by, bw * boss.hp / 100, 10);
hx.font = '14px "Lucida Console",monospace';
}
if (E.inDungeon(pl.x)) {
hx.font = 'bold 16px "Lucida Console",monospace'; hx.textAlign = 'right';
hx.fillStyle = inSafe ? '#55FFFF' : '#AA77FF';
hx.fillText('FLOOR ' + E.floorAt(pl.x) + (inSafe ? ' SAFE ROOM' : ''), W - 12, 72);
hx.textAlign = 'center'; hx.font = '14px "Lucida Console",monospace';
}
for (const c of owned) { // "Layla's Royal Castle" over kit castles nearby
const mx = c.x0 + 10.5, mz = c.z0 + 10.5; if (Math.hypot(mx - pl.x, mz - pl.z) > 48) continue;
const p = project(mvp, mx, c.base + 13, mz); if (!p) continue;
const label = (session.remote ? c.owner + "'s " : 'Your ') + E.ownedName(c.type), w = hx.measureText(label).width + 8;
hx.fillStyle = 'rgba(0,0,0,.5)'; hx.fillRect(p[0] - w / 2, p[1] - 14, w, 18);
hx.fillStyle = PAINTS[paintFor(c.owner)]; hx.fillText(label, p[0], p[1]);
}
if (E.inKingdom(pl.z)) E.TALES.forEach((T, i) => { // the name of each fairy tale place, and whether it is open for you
const c = E.placeWorld(i, 10, 10); if (Math.hypot(c[0] - pl.x, c[1] - pl.z) > 64) return;
const p = project(mvp, c[0] + 0.5, E.KY + (T.id === 'rapunzel' ? 26 : 13), c[1] + 0.5); if (!p) return;
const done = taleState(T).done, read = taleRead(i), label = T.place + (done ? ' ★' : read ? '' : ' (locked)'), w = hx.measureText(label).width + 8;
hx.fillStyle = 'rgba(0,0,0,.55)'; hx.fillRect(p[0] - w / 2, p[1] - 14, w, 18);
hx.fillStyle = done ? '#FFDD77' : read ? '#ffffff' : '#aaaaaa'; hx.fillText(label, p[0], p[1]);
});
if (session) for (const v of vehicles.values()) { // "Layla's Airplane" (or a jet nobody has found yet) over parked vehicles nearby
if (v.rider || Math.hypot(v.rx - pl.x, v.rz - pl.z) > 24) continue;
const p = project(mvp, v.rx, v.ry + 2.6, v.rz); if (!p) continue;
const vn = E.VEHICLES[E.VEH_TYPES[v.kind]].name, label = v.owner ? v.owner + "'s " + vn : vn + ': climb in to keep it!', w = hx.measureText(label).width + 8;
hx.fillStyle = 'rgba(0,0,0,.5)'; hx.fillRect(p[0] - w / 2, p[1] - 14, w, 18);
hx.fillStyle = PAINTS[paintFor(v.owner)]; hx.fillText(label, p[0], p[1]);
}
hx.textAlign = 'left';
$('hurt').style.opacity = hurtFlash > 0 ? Math.min(1, hurtFlash * 2) : 0;
}
// walking into a castle says which kind it is (once per castle per visit)
let castleT = 0, inCastle = '';
function castleCheck(dt) {
castleT -= dt; if (castleT > 0) return; castleT = 0.5;
const x = Math.floor(pl.x), z = Math.floor(pl.z), mine = castleOwnerAt(x, z);
let k = '', msg = '';
if (mine) { k = 'k' + mine.x0 + ',' + mine.z0; msg = (mine.owner.toLowerCase() === myName.toLowerCase() ? 'Your ' : mine.owner + "'s ") + E.ownedName(mine.type); }
else {
const c = E.castleAt(Math.floor(x / E.REG), Math.floor(z / E.REG), world.seed);
if (c && x >= c.x0 && x < c.x0 + E.CW && z >= c.z0 && z < c.z0 + E.CW) {
k = c.x0 + ',' + c.z0; msg = 'You found a ' + E.CASTLES[c.type].name + '!\nLook for the treasure chest in the keep';
const h = H(); h.castles[c.type] = 1; earn('castle'); if (c.type === 'royal') earn('royal'); if (Object.keys(h.castles).length >= 5) earn('all_castles');
}
}
if (E.inKingdom(pl.z)) { // in the fairy tale kingdom: say which place you walked into, or whether its gate is open for you
const pk = E.placeAt(x, z);
if (pk) { const T = E.TALES[pk.i]; k = 'tale' + pk.i; msg = T.place + (taleState(T).done ? ' ★' : '\nTap the story stone by the gate to hear the story'); }
else for (let i = 0; i < E.TALES.length; i++) {
const g = E.placeWorld(i, 10, 0), T = E.TALES[i];
if (Math.hypot(g[0] + 0.5 - pl.x, g[1] + 0.5 - pl.z) < 3.2) { k = 'gate' + i; msg = T.place + (taleRead(i) ? ': the gate is open for you!' : ' is locked.\nRead ' + T.title + ' in ABC Books to open it.'); }
}
}
inSafe = E.inSafeRoom(pl.x, pl.z, world.seed);
if (inSafe) earn('safe');
if (k && k !== inCastle) { toast(msg); sfx('craft'); }
inCastle = k;
}
// ---------------------------------------------------------------- main loop
let last = performance.now();
function frame(now) {
requestAnimationFrame(frame);
const dt = Math.min(0.05, (now - last) / 1000); last = now;
if (!pl || !world) return;
if (state === 'loading') {
updateChunks(40);
if (nearReady()) {
const top = world.topY(Math.floor(pl.x), Math.floor(pl.z));
if (pl.y < top + 1 && isSolid[world.get(Math.floor(pl.x), Math.floor(pl.y + 0.5), Math.floor(pl.z))]) pl.y = top + 1;
enterWorld();
}
return;
}
const active = state === 'play' || state === 'inv' || state === 'map' || state === 'hero' || state === 'dead' || (state === 'pause' && session && session.remote);
if (active) {
if (state === 'play') { updatePlayer(dt); interact(dt); castleCheck(dt); }
tickAnnounce(dt);
if (link.local) { simTime = sim.time; sim.players.get(1) && Object.assign(sim.players.get(1), { x: pl.x, y: pl.y, z: pl.z, yaw: pl.yaw, pitch: pl.pitch, dead: pl.dead }); }
link.tick(dt);
moveSend -= dt;
vSend -= dt;
if (ride && vSend <= 0) { vSend = 0.1; const r2 = v => +v.toFixed(2); link.send({ t: 'vmove', id: ride.id, x: r2(ride.x), y: r2(ride.y), z: r2(ride.z), yaw: r2(ride.yaw), pitch: r2(ride.pitch), roll: r2(ride.roll) }); }
if (moveSend <= 0 && !link.local) { moveSend = 0.1; link.send({ t: 'move', x: +pl.x.toFixed(2), y: +pl.y.toFixed(2), z: +pl.z.toFixed(2), yaw: +pl.yaw.toFixed(2), pitch: +pl.pitch.toFixed(2), dead: pl.dead }); }
saveTimer -= dt; if (saveTimer <= 0) { saveTimer = session.remote ? 10 : 30; saveGame(); }
}
hurtFlash = Math.max(0, hurtFlash - dt);
if (toastT > 0) { toastT -= dt; if (toastT <= 0) $('toast').textContent = ''; }
updateChunks(isTouch ? 6 : 10);
render(dt);
renderStats();
fpsN++; if (now - fpsT > 1000) { fps = Math.round(fpsN * 1000 / (now - fpsT)); fpsN = 0; fpsT = now; }
if (cfg.coords && state === 'play') $('coords').textContent = 'X ' + Math.floor(pl.x) + ' Y ' + Math.floor(pl.y) + ' Z ' + Math.floor(pl.z) + ' ' + (dl2txt(E.dayLight(simTime))) + ' ' + fps + ' fps';
}
let fps = 0, fpsN = 0, fpsT = 0;
const dl2txt = d => d > 0.6 ? 'day' : d > 0.3 ? 'dusk' : 'night';
requestAnimationFrame(frame);
window.BCdebug = () => ({ pl, world, sim, mobs, chunkGL, state, target, inv, addItem, openInv, closeInv, doUse,
dig: () => target && target.block && breakBlock(target.block), select: i => { sel = i; renderHotbar(); }, others, vehicles, ride: () => ride, leaveRide, owned: () => owned, giveDrops,
taleTest, taleRead, taleTap, kidName, tales: () => H().tales, look: (x, y, z) => { // turn to face block (x, y, z)
const dx = x + 0.5 - pl.x, dy = y + 0.5 - (pl.y + 1.62), dz = z + 0.5 - pl.z; pl.yaw = Math.atan2(-dx, -dz); pl.pitch = Math.atan2(dy, Math.hypot(dx, dz)); } });
})();
EOF
index.html: adds the WEARING row to the bag, the armor diamonds next to the hearts, and a line about treasure on the start screen.
cat > /root/blockcraft/index.html <<'EOF'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<meta name="theme-color" content="#000000">
<title>BlockCraft</title>
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32.png">
<link rel="icon" type="image/png" sizes="192x192" href="icon-192.png">
<link rel="icon" type="image/png" sizes="512x512" href="icon-512.png">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<meta property="og:title" content="BlockCraft">
<meta property="og:image" content="https://games.503mail.com/blockcraft/icon-512.png">
<style>
html,body{margin:0;height:100%;background:#000;overflow:hidden;font-family:"Lucida Console","Courier New",monospace;color:#fff;
-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
canvas{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none}
#hud{pointer-events:none;z-index:2}
button{font:inherit;cursor:pointer}
.hidden{display:none!important}
/* overlays */
.panel{position:fixed;inset:0;z-index:10;background:rgba(0,0,0,.82);display:flex;flex-direction:column;align-items:center;
justify-content:center;gap:2vmin;padding:16px;box-sizing:border-box;font-size:clamp(13px,2.6vmin,20px);text-align:center;overflow:auto}
.panel h1{margin:0;color:#FFFF55;letter-spacing:.25em;font-size:2em;text-shadow:3px 3px #555}
.panel h2{margin:0;color:#55FFFF;letter-spacing:.2em;font-size:1.2em}
.panel .sub{color:#AAAAAA}
.btn{background:#0000AA;color:#fff;border:3px solid #55FFFF;padding:.5em 1.2em;min-width:11em;letter-spacing:.1em}
.btn:active,.btn.on{background:#5555FF;border-color:#FFFF55;color:#FFFF55}
.btn.red{border-color:#FF5555}
.btn.small{min-width:0;padding:.3em .8em}
.row{display:flex;gap:.8em;flex-wrap:wrap;justify-content:center;align-items:center}
input[type=text],input[type=password]{font:inherit;background:#000;color:#FFFF55;border:3px solid #55FFFF;padding:.35em .6em;width:12em}
.worlds{display:flex;flex-direction:column;gap:.6em;width:min(560px,100%)}
.world{display:flex;gap:.6em;align-items:center;background:#111a;border:2px solid #555;padding:.5em}
.world .wn{flex:1;text-align:left}
.world .wn small{color:#AAAAAA;display:block}
.help{color:#AAAAAA;font-size:.85em;line-height:1.6;max-width:44em}
.help kbd{color:#FFFF55}
a{color:#55FFFF}
#status{color:#FF5555;min-height:1.2em}
/* HUD */
#bar{position:fixed;left:50%;bottom:1vmin;transform:translateX(-50%);z-index:4;display:flex;flex-direction:column;align-items:center;gap:.4vmin;pointer-events:none}
#stats{display:flex;gap:4vmin;font-size:clamp(12px,3vmin,22px);text-shadow:1px 1px #000;pointer-events:none}
#hearts{color:#FF5555;letter-spacing:-.1em}#food{color:#d9a066;letter-spacing:-.1em}
#airbar{color:#55FFFF}
#armorbar{color:#5decf5;letter-spacing:-.1em}
#hotbar{display:flex;gap:.5vmin;background:rgba(0,0,0,.45);padding:.6vmin;border:2px solid #555;pointer-events:auto}
.slot{position:relative;width:min(8.5vmin,58px);height:min(8.5vmin,58px);border:2px solid #777;background:rgba(40,40,40,.65);
box-sizing:border-box;display:flex;align-items:center;justify-content:center}
.slot img{width:78%;height:78%;image-rendering:pixelated;pointer-events:none}
.slot .n{position:absolute;right:2px;bottom:0;font-size:clamp(10px,2.2vmin,15px);text-shadow:1px 1px #000;pointer-events:none}
.slot .dur{position:absolute;left:10%;right:10%;bottom:6%;height:3px;background:#0a0;pointer-events:none}
.slot.sel{border-color:#FFFF55;background:rgba(90,90,40,.7)}
.slot.pick{border-color:#55FF55;background:rgba(40,110,40,.8)}
#toast{position:fixed;left:50%;top:9vmin;transform:translateX(-50%);width:max-content;max-width:min(680px,92vw);z-index:5;color:#fff;text-shadow:2px 2px #000;font-size:clamp(13px,2.8vmin,20px);
text-align:center;pointer-events:none;white-space:pre-line}
#coords{position:fixed;left:1vmin;top:1vmin;z-index:4;font-size:12px;text-shadow:1px 1px #000;pointer-events:none}
#hurt{position:fixed;inset:0;z-index:3;background:radial-gradient(transparent 40%,rgba(255,0,0,.55));opacity:0;pointer-events:none;transition:opacity .25s}
/* touch controls */
#touch{position:fixed;inset:0;z-index:1;touch-action:none;display:none}
body.touch #touch{display:block}
.tb{display:none;position:fixed;z-index:4;touch-action:none;background:rgba(0,0,120,.45);color:#FFFF55;border:3px solid rgba(85,255,255,.8);
border-radius:1.5vmin;font:bold clamp(12px,3vmin,22px) "Lucida Console","Courier New",monospace}
body.touch .tb{display:block}
.tb.held{background:rgba(85,85,255,.75)}
#bJump{right:3vmin;bottom:15vmin;width:15vmin;height:15vmin;border-radius:50%}
#bDown{right:20vmin;bottom:5vmin;width:12vmin;height:12vmin;border-radius:50%}
#bFly{right:20vmin;bottom:19vmin;width:12vmin;height:9vmin}
#bExit{position:fixed;z-index:4;left:50%;top:1.5vmin;transform:translateX(-50%);background:rgba(160,0,0,.6);color:#FFFF55;
border:3px solid #FF5555;border-radius:1.2vmin;font:bold clamp(14px,3.2vmin,24px) "Lucida Console","Courier New",monospace;padding:1vmin 3vmin;touch-action:manipulation}
#topbtns{position:fixed;right:1.5vmin;top:1.5vmin;z-index:4;display:flex;gap:1.2vmin}
#topbtns button{background:rgba(0,0,120,.55);color:#FFFF55;border:3px solid rgba(85,255,255,.8);border-radius:1.2vmin;
font:bold clamp(12px,2.8vmin,20px) "Lucida Console","Courier New",monospace;padding:1vmin 1.6vmin;touch-action:manipulation}
#stickRing{position:fixed;z-index:3;width:26vmin;height:26vmin;margin:-13vmin 0 0 -13vmin;border-radius:50%;border:3px solid rgba(85,255,255,.6);
background:rgba(0,0,80,.25);pointer-events:none;display:none}
#stickKnob{position:absolute;left:50%;top:50%;width:10vmin;height:10vmin;margin:-5vmin 0 0 -5vmin;border-radius:50%;background:rgba(255,255,85,.75)}
/* inventory */
#inv{justify-content:flex-start}
#invWrap{display:flex;gap:3vmin;flex-wrap:wrap;justify-content:center;align-items:flex-start;max-width:100%}
.grid{display:grid;grid-template-columns:repeat(9,auto);gap:.5vmin;justify-content:center}
.box{background:rgba(30,30,60,.9);border:3px solid #555;padding:1.2vmin}
.box h3{margin:0 0 1vmin;color:#55FFFF;font-size:1em;letter-spacing:.15em}
#recipes{display:flex;flex-direction:column;gap:.6vmin;max-height:62vh;overflow:auto;min-width:min(330px,90vw)}
.rec{display:flex;align-items:center;gap:.6em;background:#0000AA;border:2px solid #55FFFF;padding:.3em .5em;text-align:left;color:#fff}
.rec img{width:2em;height:2em;image-rendering:pixelated}
.rec .ing{color:#AAAAAA;font-size:.8em}
.rec.no{background:#222;border-color:#444;color:#888}
.rec.no img{opacity:.45}
#palette{display:grid;grid-template-columns:repeat(9,auto);gap:.5vmin;max-height:58vh;overflow:auto}
#itemName{min-height:1.3em;color:#FFFF55}
/* announcer banner, HERO screen */
#announce{position:fixed;left:50%;top:13vmin;transform:translateX(-50%);z-index:6;width:min(560px,90vw);background:rgba(10,0,30,.88);
border:3px solid #FFFF55;padding:1.2vmin 2vmin;text-align:center;pointer-events:none;font-size:clamp(12px,2.6vmin,18px);white-space:pre-line}
#announce b{display:block;font-size:1.25em;letter-spacing:.08em;margin-bottom:.4em}
#hero{justify-content:flex-start}
.xpbar{width:min(420px,80vw);height:14px;border:2px solid #55FFFF;background:#111}
.xpbar div{height:100%;background:#55FF55;width:0}
#hAch,#hTales{display:grid;grid-template-columns:repeat(auto-fill,minmax(13em,1fr));gap:.6vmin;max-width:min(900px,92vw);text-align:left;font-size:.85em}
.ach{background:#111a;border:2px solid #333;padding:.4em;color:#777}
.ach.got{border-color:#555;color:#ddd}
/* map */
#mapCv{position:static;width:min(92vw,92vh*1.5);height:min(72vh,92vw/1.5);border:3px solid #55FFFF;background:#000;image-rendering:pixelated}
</style>
</head>
<body>
<canvas id="gl"></canvas>
<canvas id="hud"></canvas>
<div id="touch"></div>
<div id="stickRing"><div id="stickKnob"></div></div>
<div id="hurt"></div>
<div id="coords"></div>
<div id="toast"></div>
<div id="bar" class="hidden">
<div id="stats"><span id="armorbar"></span><span id="hearts"></span><span id="airbar"></span><span id="food"></span></div>
<div id="hotbar"></div>
</div>
<button id="bJump" class="tb hidden" aria-label="Jump">JUMP</button>
<button id="bDown" class="tb hidden" aria-label="Fly down">▼</button>
<button id="bFly" class="tb hidden" aria-label="Fly">FLY</button>
<button id="bExit" class="hidden" aria-label="Get out">OUT</button>
<div id="topbtns" class="hidden">
<button id="bHero" aria-label="Hero">HERO</button>
<button id="bInv" aria-label="Inventory">BAG</button>
<button id="bMap" aria-label="Map">MAP</button>
<button id="bPause" aria-label="Pause">II</button>
</div>
<div id="menu" class="panel">
<h1>BLOCKCRAFT</h1>
<div class="sub">BUILD · MINE · SURVIVE</div>
<button class="btn" id="mSingle">SINGLE PLAYER</button>
<button class="btn" id="mMulti">PLAY TOGETHER</button>
<div class="row"><label><input type="checkbox" id="optSound" checked> Sound</label></div>
<div id="nogl" class="hidden" style="color:#FF5555">This browser can't draw 3D (WebGL is off), so the game can't run here.</div>
<div class="help">
<b>Tablet:</b> left thumb moves, drag on the right to look. <b>Tap</b> to place or use, <b>hold</b> to dig or hit.<br>
<b>Keyboard:</b> <kbd>WASD</kbd> move · mouse look · <kbd>left click</kbd> dig/hit · <kbd>right click</kbd> place/use ·
<kbd>space</kbd> jump (double tap = fly in Creative) · <kbd>E</kbd> bag · <kbd>M</kbd> map · <kbd>1</kbd>–<kbd>9</kbd> pick<br>
<b>Airplanes & helicopters:</b> earn one in Survival (iron + diamonds at a crafting table), set it down, tap it to get in.
It is yours only. <kbd>F</kbd> or <b>OUT</b> gets out.<br>
<b>Treasure:</b> explore Wooden Forts, Stone and Royal Castles, Desert Palaces and Ice Castles for treasure chests.
Tap potions to drink them, tap armor to wear it, and earn castle kits to build a castle of your own.<br>
<b>Dungeon:</b> the glowing stairwell next to the start leads down to dungeon floors with bosses. <b>HERO</b> (<kbd>H</kbd>) shows your level,
class, points, pet and achievements. Tap loot boxes to open them.<br>
<b>Fairy Tale Kingdom:</b> the Story Book arch on the other side of the start leads to a place for every fairy tale in ABC Books.
Read a whole tale in ABC Books and its gate opens for you. Tap the story stone to hear the story, finish the quest, and earn its
keepsake and a kit that builds the place at home.
</div>
<a href="/">Other games</a>
</div>
<div id="spMenu" class="panel hidden">
<h2>SINGLE PLAYER</h2>
<div class="worlds" id="worldList"></div>
<div class="box" style="display:flex;flex-direction:column;gap:1.2vmin;align-items:center">
<h3>NEW WORLD</h3>
<div class="row"><input type="text" id="nwName" maxlength="20" placeholder="World name"><input type="text" id="nwSeed" maxlength="12" placeholder="Seed (optional)"></div>
<div class="row" id="nwMode"><button class="btn small on" data-v="survival">SURVIVAL</button><button class="btn small" data-v="creative">CREATIVE</button></div>
<div class="row" id="nwDiff"><button class="btn small" data-v="peaceful">PEACEFUL</button><button class="btn small on" data-v="easy">EASY</button><button class="btn small" data-v="normal">NORMAL</button></div>
<button class="btn" id="nwGo">CREATE</button>
</div>
<button class="btn small" id="spBack">BACK</button>
</div>
<div id="mpMenu" class="panel hidden">
<h2>PLAY TOGETHER</h2>
<div class="sub">Everyone joins the same family world.</div>
<div class="row" id="mpNames"></div>
<div class="row"><input type="text" id="mpName" maxlength="16" placeholder="Your name"></div>
<div class="row"><input type="password" id="mpCode" maxlength="32" placeholder="Family code"></div>
<div class="row" id="mpMode"><button class="btn small on" data-v="survival">SURVIVAL</button><button class="btn small" data-v="creative">CREATIVE</button></div>
<button class="btn" id="mpGo">JOIN</button>
<div id="status"></div>
<button class="btn small hidden" id="mpSwitch">SWITCH PLAYER</button>
<button class="btn small" id="mpBack">BACK</button>
</div>
<div id="sleepPanel" class="panel hidden" style="background:rgba(0,0,30,.9)">
<h1>Zzz...</h1>
<h2>SLEEPING</h2>
<div class="sub">Sleeping heals you. At night, when everyone is in bed, it turns morning.</div>
<button class="btn" id="sleepWake">WAKE UP</button>
</div>
<div id="whoPanel" class="panel hidden">
<h2>WHO IS PLAYING?</h2>
<div class="row" id="whoNames"></div>
<div class="row hidden" id="whoCodeRow"><input type="password" id="whoCode" maxlength="32" placeholder="Family code"></div>
<div id="whoStatus" style="color:#FF5555;min-height:1.2em"></div>
<button class="btn small" id="whoBack">BACK</button>
</div>
<div id="breakPanel" class="panel hidden" role="alertdialog" aria-labelledby="breakH" aria-describedby="breakWho breakLeft" style="z-index:20;background:#000a30">
<h1 id="breakH">PLUG ME IN!</h1>
<div style="font-size:5em;line-height:1" aria-hidden="true">🔌🔋</div>
<h2 id="breakWho">Time for a break!</h2>
<div class="sub" id="breakLeft" style="font-size:1.2em"></div>
</div>
<div id="loading" class="panel hidden"><h2 id="loadText">BUILDING WORLD...</h2></div>
<div id="pause" class="panel hidden">
<h2>PAUSED</h2>
<button class="btn" id="pResume">BACK TO GAME</button>
<div class="row">View: <span class="row" id="pDist"><button class="btn small" data-v="2">NEAR</button><button class="btn small" data-v="3">MEDIUM</button><button class="btn small" data-v="5">FAR</button></span></div>
<div class="row"><label><input type="checkbox" id="pSound"> Sound</label><label><input type="checkbox" id="pCoords"> Show position</label></div>
<div class="row" id="pModeRow">Mode: <button class="btn small" id="pMode"></button></div>
<button class="btn red" id="pQuit">SAVE & QUIT</button>
</div>
<div id="dead" class="panel hidden">
<h1 style="color:#FF5555">YOU DIED!</h1>
<div class="sub" id="deadWhy"></div>
<button class="btn" id="dRespawn">RESPAWN</button>
</div>
<div id="inv" class="panel hidden">
<div id="itemName"></div>
<div id="invWrap">
<div class="box" id="chestBox"><h3>CHEST</h3><div class="grid" id="chestGrid"></div></div>
<div class="box" id="creativeBox"><h3>ALL BLOCKS & ITEMS</h3><div id="palette"></div></div>
<div class="box" id="armorBox"><h3>WEARING</h3><div class="grid" id="armorGrid" style="grid-template-columns:repeat(4,auto)"></div><div class="sub" id="armorInfo" style="font-size:.8em;margin-top:.6vmin"></div></div>
<div class="box"><h3>BAG</h3><div class="grid" id="invGrid"></div><div style="height:1vmin"></div><div class="grid" id="invHot"></div></div>
<div class="box" id="craftBox"><h3 id="craftTitle">CRAFTING</h3><div id="recipes"></div></div>
</div>
<button class="btn small" id="invClose">CLOSE</button>
</div>
<div id="announce" class="hidden" role="status" aria-live="polite"><b></b><span></span></div>
<div id="hero" class="panel hidden">
<h2 id="hLevel">HERO</h2>
<div class="xpbar"><div id="hXp"></div></div><div class="sub" id="hXpText"></div>
<div class="box" style="display:flex;flex-direction:column;gap:1vmin;align-items:center">
<h3>CLASS</h3><div class="row" id="hClass"></div><div class="sub" id="hClassAbout"></div>
<h3>POINTS</h3><div class="sub" id="hFree"></div><div id="hStats" style="display:flex;flex-direction:column;gap:.6vmin"></div>
<h3>PET</h3><div id="hPet"></div>
<div class="row hidden" id="hPetRow"><select id="hPetPick" aria-label="Which pet"></select><input type="text" id="hPetName" maxlength="16" placeholder="New pet name"><button class="btn small" id="hPetSave">NAME</button></div>
</div>
<div class="box"><h3 id="hTalesTitle">FAIRY TALES</h3><div id="hTales" class="tales"></div></div>
<div class="box"><h3 id="hAchTitle">ACHIEVEMENTS</h3><div id="hAch"></div></div>
<button class="btn small" id="hClose">CLOSE</button>
</div>
<div id="mapPanel" class="panel hidden">
<canvas id="mapCv" width="900" height="600"></canvas>
<div class="row"><button class="btn small" id="mapOut">−</button><button class="btn small" id="mapIn">+</button><button class="btn small" id="mapClose">CLOSE</button></div>
</div>
<script src="engine.js"></script>
<script src="game.js"></script>
</body>
</html>
EOF
server.js: lets the kit message through, sends and saves the list of kit castles.
cat > /root/blockcraft/server.js <<'EOF'
'use strict';
// BlockCraft multiplayer server (CT 127). Serves the game page at /blockcraft/ and runs the shared
// world over a WebSocket at /blockcraft/ws. The world simulation is the same engine.js the page uses.
const http = require('http'), fs = require('fs'), path = require('path');
const WebSocket = require('ws');
const ROOT = __dirname;
const PUB = fs.existsSync(path.join(ROOT, 'public')) ? path.join(ROOT, 'public') : path.join(ROOT, '..', 'public');
const BC = require(path.join(PUB, 'engine.js'));
const DATA = path.join(ROOT, 'data'), WORLD_FILE = path.join(DATA, 'world.json'), CFG_FILE = path.join(ROOT, 'config.json');
const cfg = Object.assign({ port: 8080, code: '', difficulty: 'normal', names: [], families: [], pw: {}, invites: [], pending: [] },
fs.existsSync(CFG_FILE) ? JSON.parse(fs.readFileSync(CFG_FILE, 'utf8')) : {});
fs.mkdirSync(DATA, { recursive: true });
// ---------------------------------------------------------------- families + codes
// cfg.names = every player (Build Designer and the other games read it too). Players listed in
// cfg.families[] (cousins, friends) use their family's code; everyone else uses cfg.code; admin uses adminCode.
const lc = s => String(s).toLowerCase();
function familyOf(nm) { return cfg.families.find(f => f.players.some(p => lc(p) === lc(nm))) || null; }
function codeFor(nm) {
if (lc(nm) === 'admin' && cfg.adminCode) return cfg.adminCode;
const f = familyOf(nm); return f ? f.code : cfg.code;
}
// Players who signed up with an invite have their own password: cfg.pw[lowercase name] = 'scrypt$salt$hash'
// (Build Designer checks the same hash). Everyone else signs in with their family's code.
const crypto = require('crypto');
function hashPw(p) { const salt = crypto.randomBytes(16); return 'scrypt$' + salt.toString('base64') + '$' + crypto.scryptSync(String(p), salt, 32).toString('base64'); }
function checkPw(p, h) {
const [k, s, x] = String(h).split('$'); if (k !== 'scrypt' || !s || !x) return false;
const want = Buffer.from(x, 'base64'), got = crypto.scryptSync(String(p), Buffer.from(s, 'base64'), want.length);
return got.length === want.length && crypto.timingSafeEqual(got, want);
}
function checkLogin(nm, code) {
if (lc(nm) === 'admin' && cfg.adminCode) return sameText(code, cfg.adminCode);
if (cfg.pw[lc(nm)]) return checkPw(code, cfg.pw[lc(nm)]);
const need = codeFor(nm); return !need || sameText(code, need);
}
function sameText(a, b) {
const x = Buffer.from(String(a)), y = Buffer.from(String(b));
return x.length === y.length && require('crypto').timingSafeEqual(x, y);
}
function saveCfg() {
try { fs.copyFileSync(CFG_FILE, CFG_FILE + '.bak'); } catch (e) {}
const tmp = CFG_FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { mode: 0o640 });
fs.renameSync(tmp, CFG_FILE);
}
// At home the kids just tap their name: the Amazon Kids browser forgets the saved sign-in whenever it closes.
// Home = the address games.503mail.com points at (the house's internet address, looked up again every 10 minutes),
// or a LAN address talking to this CT directly. Only home-family kids: not admin, cousins/friends or own passwords.
const dns = require('dns');
let homeIps = new Set();
function lookUpHome() { dns.resolve4(cfg.homeHost || 'games.503mail.com', (e, a) => { if (!e && a.length) homeIps = new Set(a); }); }
lookUpHome(); setInterval(lookUpHome, 10 * 60000);
function clientIp(req) { // the edge Caddy replaces any forwarded header a visitor sends, so its last entry is the real address
const x = String(req.headers['x-forwarded-for'] || '').split(',').pop().trim();
return (x || String(req.socket.remoteAddress || '')).replace(/^::ffff:/, '');
}
function isHome(req) {
const ip = clientIp(req);
return homeIps.has(ip) || (!req.headers['x-forwarded-for'] && /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(ip));
}
function homeKid(nm, req) {
const listed = cfg.names.find(n => lc(n) === lc(nm));
return !!listed && lc(listed) !== 'admin' && !familyOf(listed) && !cfg.pw[lc(listed)] && isHome(req);
}
// ---------------------------------------------------------------- play time: 30 minutes, then a 1 hour break
// Counted per name on the server (the tablets forget everything), from the game connection and the single-player ping.
// config.json may set playMinutes, breakMinutes and untimed (names with no limit, default admin + Dietrich).
const PLAY_FILE = path.join(DATA, 'playtime.json');
let play = {}; try { play = JSON.parse(fs.readFileSync(PLAY_FILE, 'utf8')); } catch (e) {}
let playDirty = false;
const playSecs = () => (cfg.playMinutes || 30) * 60, breakMs = () => (cfg.breakMinutes || 60) * 60000;
const untimed = nm => (cfg.untimed || ['admin', 'Dietrich']).map(lc).includes(lc(nm));
function playState(nm, count) { // count = add the time since this name was last counted; returns { left (seconds), breakUntil }
if (untimed(nm)) return { left: null, breakUntil: 0 };
const now = Date.now(), k = lc(nm), p = play[k] || (play[k] = { used: 0, at: 0, breakUntil: 0 });
if (p.breakUntil > now) return { left: 0, breakUntil: p.breakUntil };
const gap = now - p.at;
if (gap > breakMs()) { p.used = 0; if (!count) return { left: playSecs(), breakUntil: 0 }; } // away longer than a break: a fresh 30 minutes
if (!count) return { left: Math.round(playSecs() - p.used), breakUntil: 0 };
if (gap <= 75000) p.used += gap / 1000; // only counts while play goes on (pings come every 10 to 30 seconds)
p.at = now; playDirty = true;
if (p.used >= playSecs()) {
p.used = 0; p.breakUntil = now + breakMs();
console.log(new Date().toISOString(), 'break for', nm, 'until', new Date(p.breakUntil).toISOString());
return { left: 0, breakUntil: p.breakUntil };
}
return { left: Math.round(playSecs() - p.used), breakUntil: 0 };
}
function savePlay() { if (!playDirty) return; playDirty = false; fs.writeFileSync(PLAY_FILE + '.tmp', JSON.stringify(play)); fs.renameSync(PLAY_FILE + '.tmp', PLAY_FILE); }
function newCode() { // easy to read out loud: no 0/o, 1/l/i
const A = 'abcdefghjkmnpqrstuvwxyz23456789', b = require('crypto').randomBytes(8);
let s = ''; for (let i = 0; i < 8; i++) { s += A[b[i] % A.length]; if (i === 3) s += '-'; } return s;
}
// every family gets a lasting id (its own world's file name), even if renamed later
let idsAdded = false;
for (const f of cfg.families) if (!f.id) { f.id = crypto.randomBytes(4).toString('hex'); idsAdded = true; }
if (idsAdded) saveCfg();
// ---------------------------------------------------------------- worlds
// The shared world (data/world.json) is where the home family plays, with every family set to "everyone".
// A family set to "own world" (f.own) plays in data/world-<family id>.json, made the first time one of them joins.
const conns = new Map(); // player id -> { ws, name, dev, W }
const worlds = new Map(); // '' = shared world, else family id -> world
let nextId = 1;
function getWorld(key) {
if (worlds.has(key)) return worlds.get(key);
const file = key ? path.join(DATA, 'world-' + key + '.json') : WORLD_FILE;
let saved = null;
try { saved = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { saved = null; }
const W = { key, file, seed: saved ? saved.seed : (Math.random() * 2147483647) | 0, playersData: (saved && saved.players) || {}, dirty: true };
W.send = (msg, to) => {
const s = JSON.stringify(msg);
if (to == null) { for (const c of conns.values()) if (c.W === W && c.ws.readyState === 1) c.ws.send(s); }
else { const c = conns.get(to); if (c && c.W === W && c.ws.readyState === 1) c.ws.send(s); }
};
const sim = W.sim = new BC.Sim({ seed: W.seed, difficulty: cfg.difficulty, time: saved ? saved.time : 0.02, chests: saved ? saved.chests : {},
vehicles: saved ? saved.vehicles : [], owned: saved ? saved.owned : [], dungeon: saved ? saved.dungeon : null, pets: saved ? saved.pets : {}, kingdom: saved ? saved.kingdom : null, send: W.send });
sim.unloadFar = true;
if (saved && saved.edits) sim.world.decodeEdits(saved.edits);
W.spawn = (saved && saved.spawn) || sim.spawnPoint();
sim.ensureEntrance(W.spawn); // the dungeon shrine next to spawn (built once, then it's part of the saved changes)
sim.ensureAirfields(W.spawn); // pets + play add-on: three runways with jets to find
sim.ensureKingdomGate(W.spawn); // the Story Book arch to the fairy tale kingdom, on the other side of spawn
const origSet = sim.world.set.bind(sim.world);
sim.world.set = (...a) => { const r = origSet(...a); if (r) W.dirty = true; return r; };
worlds.set(key, W);
console.log(new Date().toISOString(), 'world', key || 'shared', 'seed', W.seed, saved ? '(loaded)' : '(new)');
return W;
}
function worldKeyFor(nm) { const f = familyOf(nm); return f && f.own ? f.id : ''; }
function saveWorld(W) {
const sim = W.sim;
const data = { seed: W.seed, time: sim.time, spawn: W.spawn, edits: sim.world.encodeEdits(), chests: sim.chests, vehicles: sim.saveVehicles(), owned: sim.owned, dungeon: sim.dungeon, pets: sim.petData, kingdom: sim.kingdom, players: W.playersData };
const tmp = W.file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(data));
fs.renameSync(tmp, W.file);
W.dirty = false;
}
const shared = getWorld('');
// ---------------------------------------------------------------- web server
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.png': 'image/png', '.css': 'text/css', '.mp3': 'audio/mpeg' };
const server = http.createServer((req, res) => {
let p = decodeURIComponent((req.url || '/').split('?')[0]);
if (p === '/' || p === '/blockcraft') { res.writeHead(301, { Location: '/blockcraft/' }); res.end(); return; }
if (p === '/login' || p === '/login/') p = '/blockcraft/login.html'; // games.503mail.com/login (edge sends /login here)
if (!p.startsWith('/blockcraft/')) { res.writeHead(404); res.end('not found'); return; }
if (p === '/blockcraft/api/admin') { adminApi(req, res); return; }
if (/^\/blockcraft\/api\/(login|signup|invite|family|who|play)$/.test(p)) { publicApi(p.split('/').pop(), req, res); return; }
if (p === '/blockcraft/api/group') { groupApi(req, res); return; }
if (p === '/blockcraft/api/tales') { talesApi(req, res); return; }
if (p === '/blockcraft/players' || p === '/blockcraft/players/') p = '/blockcraft/players.html';
p = p.slice('/blockcraft/'.length) || 'index.html';
const file = path.normalize(path.join(PUB, p));
if (!file.startsWith(PUB + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) { res.writeHead(404); res.end('not found'); return; }
res.writeHead(200, { 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
fs.createReadStream(file).pipe(res);
});
// ---------------------------------------------------------------- Players page (admin only)
// POST /blockcraft/api/admin {code: admin password, action, ...}. 5 wrong passwords per address = 15 min wait.
const fails = new Map();
const NAME_RE = /^[A-Za-z0-9 _-]{1,16}$/, FAM_RE = /^[A-Za-z0-9 '&._-]{1,30}$/;
function readJson(req, res, then) {
const out = (st, o) => { res.writeHead(st, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(o)); };
if (req.method !== 'POST') { out(405, { error: 'POST only' }); return; }
const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress).split(',')[0].trim();
let body = '';
req.on('data', d => { body += d; if (body.length > 10000) req.destroy(); });
req.on('end', () => {
let m; try { m = JSON.parse(body); } catch (e) { out(400, { error: 'Bad request.' }); return; }
if (!m || typeof m !== 'object') { out(400, { error: 'Bad request.' }); return; }
then(m, ip, out);
});
}
// ---------------------------------------------------------------- fairy tales read in ABC Books (add-on 4)
// ABC Books (abcbooks.fyi or games.503mail.com/abcbooks/) reports a kid's finished Grimm tales here, so their places open in
// the Fairy Tale Kingdom on any tablet and any site. data/tales-read.json: { "<lower-case name>": { "<tale id>": time } }.
// POST /blockcraft/api/tales {name, tales: [ABC Books tale titles or tale ids]} GET /blockcraft/api/tales?name=<name>
// Only names on the family list count. Nothing secret: it only says which stories a kid has read.
const TALES_FILE = path.join(DATA, 'tales-read.json'), taleHits = new Map();
let talesRead = {}; try { talesRead = JSON.parse(fs.readFileSync(TALES_FILE, 'utf8')); } catch (e) { talesRead = {}; }
const CORS_OK = ['https://abcbooks.fyi', 'https://www.abcbooks.fyi', 'https://games.503mail.com'];
const talesOf = nm => Object.keys(talesRead[lc(nm)] || {});
function talesApi(req, res) {
const origin = req.headers.origin || '', head = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' };
if (CORS_OK.includes(origin)) Object.assign(head, { 'Access-Control-Allow-Origin': origin, 'Access-Control-Allow-Methods': 'GET, POST', 'Access-Control-Allow-Headers': 'Content-Type', Vary: 'Origin' });
const out = (st, o) => { res.writeHead(st, head); res.end(JSON.stringify(o)); };
if (req.method === 'OPTIONS') { res.writeHead(204, head); res.end(); return; }
const known = nm => NAME_RE.test(nm) && cfg.names.some(n => lc(n) === lc(nm));
if (req.method === 'GET') {
const nm = String(new URL(req.url, 'http://x').searchParams.get('name') || '').trim();
out(200, { name: nm, tales: known(nm) ? talesOf(nm) : [] }); return;
}
if (req.method !== 'POST') { out(405, { error: 'GET or POST' }); return; }
const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress).split(',')[0].trim();
if (limited(taleHits, ip, 60, 3600000)) { out(429, { error: 'Too many, try again later.' }); return; }
let body = '';
req.on('data', d => { body += d; if (body.length > 4000) req.destroy(); });
req.on('end', () => {
let m; try { m = JSON.parse(body); } catch (e) { out(400, { error: 'Bad request.' }); return; }
const nm = String((m && m.name) || '').trim();
if (!known(nm) || !Array.isArray(m.tales)) { out(200, { name: nm, tales: [], note: 'not a BlockCraft player' }); return; }
const mine = talesRead[lc(nm)] = talesRead[lc(nm)] || {}; let added = 0;
for (const t of m.tales.slice(0, 50)) { const T = BC.TALES.find(q => q.abc === t || q.id === t); if (T && !mine[T.id]) { mine[T.id] = Date.now(); added++; } }
if (added) {
try { fs.writeFileSync(TALES_FILE + '.tmp', JSON.stringify(talesRead)); fs.renameSync(TALES_FILE + '.tmp', TALES_FILE); } catch (e) { console.error(e); }
console.log(new Date().toISOString(), 'tales read', nm, Object.keys(mine).join(','));
for (const c of conns.values()) if (lc(c.name) === lc(nm) && c.ws.readyState === 1) c.ws.send(JSON.stringify({ t: 'tales', tales: Object.keys(mine) }));
}
out(200, { name: nm, tales: Object.keys(mine) });
});
}
// a few tries per address per window (sign-in, sign-up)
function limited(map, ip, max, ms) {
const f = map.get(ip), now = Date.now();
if (!f || now - f.t > ms) { map.set(ip, { n: 1, t: now }); return false; }
f.n++; return f.n > max;
}
function nameTaken(nm) {
return lc(nm) === 'admin' || cfg.names.some(n => lc(n) === lc(nm)) || cfg.pending.some(p => lc(p.name) === lc(nm));
}
function liveInvite(code) {
return cfg.invites.find(i => sameText(i.code, String(code || '')) && i.expires > Date.now()) || null;
}
function famLabel(f) { return f ? f.name : 'the home family'; }
// ---------------------------------------------------------------- games.503mail.com/login
// invite: what family an invite link is for. signup: invite + name + own password -> waits for admin approval.
// login: checks a name + password (or family code) so the page can sign the tablet in to every game.
const loginFails = new Map(), signups = new Map();
function publicApi(what, req, res) {
readJson(req, res, (m, ip, out) => {
const nm = String(m.name || '').trim(), pw = String(m.password || '');
if (what === 'invite') {
const inv = liveInvite(m.invite);
if (!inv) { out(404, { error: 'This invite link is not valid any more. Ask for a new one.' }); return; }
out(200, { family: famLabel(inv.family ? findFam(inv.family) : null) }); return;
}
if (what === 'signup') {
const su = signups.get(ip); // 10 accepted sign-ups per address per hour
if (su && su.n >= 10 && Date.now() - su.t < 60 * 60000) { out(429, { error: 'Too many sign-ups from here. Try again in an hour.' }); return; }
const inv = liveInvite(m.invite);
if (!inv) { out(404, { error: 'This invite link is not valid any more. Ask for a new one.' }); return; }
if (!NAME_RE.test(nm)) { out(400, { error: 'Player names: letters, numbers, spaces, - or _ (up to 16).' }); return; }
if (nameTaken(nm)) { out(400, { error: 'Someone already has the name ' + nm + '. Pick a different one.' }); return; }
if (pw.length < 6 || pw.length > 64) { out(400, { error: 'Passwords need 6 to 64 characters.' }); return; }
if (cfg.pending.length >= 30) { out(400, { error: 'Too many people are waiting already. Ask to be approved first.' }); return; }
cfg.pending.push({ name: nm, family: inv.family, hash: hashPw(pw), at: Date.now(), by: inv.by || '' });
limited(signups, ip, 1e9, 60 * 60000);
saveCfg(); console.log(new Date().toISOString(), 'sign-up waiting for approval:', JSON.stringify(nm), 'for', famLabel(findFam(inv.family)), ip);
out(200, { ok: true, name: nm }); return;
}
if (what === 'who') { // the game's "who is playing?" screen: at home it lists the kids who can just tap their name
const home = isHome(req);
out(200, { home, names: home ? cfg.names.filter(n => homeKid(n, req)) : [] }); return;
}
if (what === 'play') { // pick a player (tap at home, or name + code) and see their play time; ping: true counts single-player time
const f = loginFails.get(ip);
if (f && f.n >= 10 && Date.now() - f.t < 15 * 60000) { out(429, { error: 'Too many wrong tries. Wait 15 minutes.' }); return; }
const listed = cfg.names.find(n => lc(n) === lc(nm));
if (!listed || !(homeKid(listed, req) || checkLogin(listed, String(m.code || '')))) {
limited(loginFails, ip, 1e9, 15 * 60000);
console.log(new Date().toISOString(), 'who is playing: wrong name or code for', JSON.stringify(nm.slice(0, 16)), ip);
out(403, { error: listed ? 'Wrong family code.' : 'That name is not on the family list.' }); return;
}
out(200, Object.assign({ ok: true, name: listed }, playState(listed, !!m.ping))); return;
}
if (what === 'login') {
const f = loginFails.get(ip);
if (f && f.n >= 10 && Date.now() - f.t < 15 * 60000) { out(429, { error: 'Too many wrong tries. Wait 15 minutes.' }); return; }
const waiting = cfg.pending.find(p => lc(p.name) === lc(nm));
if (waiting && checkPw(pw, waiting.hash)) { out(403, { error: nm + ' is still waiting to be approved.' }); return; }
const listed = cfg.names.find(n => lc(n) === lc(nm)) || (lc(nm) === 'admin' ? 'admin' : null);
if (!listed || !checkLogin(listed, pw)) {
limited(loginFails, ip, 1e9, 15 * 60000);
console.log(new Date().toISOString(), 'login page: wrong name or password for', JSON.stringify(nm.slice(0, 16)), ip);
out(403, { error: 'Wrong name or password.' }); return;
}
loginFails.delete(ip);
out(200, { ok: true, name: listed }); return;
}
if (what === 'family') { // a signed-in cousin/friend: see their family, make an invite link for it (admin still approves)
const f0 = loginFails.get(ip);
if (f0 && f0.n >= 10 && Date.now() - f0.t < 15 * 60000) { out(429, { error: 'Too many wrong tries. Wait 15 minutes.' }); return; }
const listed = cfg.names.find(n => lc(n) === lc(nm));
if (!listed || !checkLogin(listed, pw)) { limited(loginFails, ip, 1e9, 15 * 60000); out(403, { error: 'Sign in again: wrong name or password.' }); return; }
const f = familyOf(listed);
if (!f) { out(200, { home: true }); return; } // the home family's invites come from the admin
const now = Date.now(), live = () => cfg.invites.filter(i => i.family === f.name && i.expires > now);
if (m.action === 'invite') {
let inv = live().find(i => lc(i.by || '') === lc(listed));
if (!inv) {
if (live().length >= 3) { out(400, { error: 'Your family already has 3 invite links. Use one of those.' }); return; }
inv = { code: crypto.randomBytes(9).toString('base64url'), family: f.name, expires: now + 7 * 86400000, by: listed };
cfg.invites = cfg.invites.filter(i => i.expires > now); cfg.invites.push(inv); saveCfg();
console.log(new Date().toISOString(), 'family invite link made by', JSON.stringify(listed), 'for', f.name, ip);
}
}
out(200, { family: f.name, own: !!f.own, members: f.players.slice(),
invites: live().map(i => ({ code: i.code, expires: i.expires, by: i.by || '' })) }); return;
}
out(404, { error: 'Not found.' });
});
}
// For the games relay on this container (Super Pip, Dash Rush, Robot Rumble): which group a signed-in
// player plays in. 'shared' = with everyone; 'f-<id>' = a family with its own world. Only answers 127.0.0.1.
const groupTries = new Map();
function groupApi(req, res) {
const local = !req.headers['x-forwarded-for'] && /^(::ffff:)?127\.0\.0\.1$|^::1$/.test(req.socket.remoteAddress || '');
if (!local) { res.writeHead(404); res.end('not found'); return; }
readJson(req, res, (m, ip, out) => {
const nm = String(m.name || '').trim(), listed = cfg.names.find(n => lc(n) === lc(nm));
if (!listed || limited(groupTries, lc(listed), 30, 15 * 60000) || !checkLogin(listed, String(m.password || ''))) { out(200, { group: 'shared' }); return; }
const f = familyOf(listed);
out(200, { group: f && f.own ? 'f-' + f.id : 'shared' });
});
}
function adminApi(req, res) {
readJson(req, res, (m, ip, out) => {
const f = fails.get(ip);
if (f && f.n >= 5 && Date.now() - f.t < 15 * 60000) { out(429, { error: 'Too many wrong passwords. Wait 15 minutes.' }); return; }
if (!cfg.adminCode) { out(403, { error: 'No admin password is set. Run set-admin-code.sh first.' }); return; }
if (!sameText(m.code || '', cfg.adminCode)) {
fails.set(ip, { n: (f && Date.now() - f.t < 15 * 60000 ? f.n : 0) + 1, t: Date.now() });
console.log(new Date().toISOString(), 'players page: wrong admin password', ip);
out(403, { error: 'Wrong admin password.' }); return;
}
fails.delete(ip);
const r = adminAction(m);
if (r.error) { out(400, r); return; }
if (r.changed) { saveCfg(); console.log(new Date().toISOString(), 'players page:', r.changed, ip); }
out(200, Object.assign(listing(), { done: r.changed || '', once: r.once || '' }));
});
}
function listing() {
const inFam = new Set(cfg.families.flatMap(f => f.players.map(lc)));
const online = [...conns.values()].map(c => c.name), now = Date.now();
const invites = fam => cfg.invites.filter(i => i.family === fam && i.expires > now).map(i => ({ code: i.code, expires: i.expires, by: i.by || '' }));
return { home: { code: cfg.code, players: cfg.names.filter(n => lc(n) !== 'admin' && !inFam.has(lc(n))), invites: invites('') },
families: cfg.families.map(f => ({ name: f.name, code: f.code, players: f.players.slice(), invites: invites(f.name), own: !!f.own })), online,
ownPw: cfg.names.filter(n => cfg.pw[lc(n)]),
pending: cfg.pending.map(p => ({ name: p.name, family: famLabel(findFam(p.family)), at: p.at, by: p.by || '' })) };
}
function findFam(name) { return cfg.families.find(f => lc(f.name) === lc(name)) || null; }
// t 'error' signs the tablet out; t 'busy' keeps it signed in and it rejoins by itself (into its new world)
function kick(nm, text, t) {
for (const [oid, c] of conns) if (lc(c.name) === lc(nm)) {
try { c.ws.send(JSON.stringify({ t: t || 'error', text })); } catch (e) {}
setTimeout(() => c.ws.terminate(), 200); conns.delete(oid); c.W.sim.removePlayer(oid);
c.W.send({ t: 'msg', text: c.name + ' left the game' }, null);
}
}
function adminAction(m) {
const fam = String(m.family || '').trim(), nm = String(m.name || '').trim(), code = String(m.newCode || '').trim();
const okCode = c => c.length >= 4 && c.length <= 40;
switch (m.action) {
case 'list': return {};
case 'addFamily': {
if (!FAM_RE.test(fam)) return { error: 'Family name: up to 30 letters, numbers or spaces.' };
if (findFam(fam) || lc(fam) === 'home family') return { error: 'There is already a family called ' + fam + '.' };
if (code && !okCode(code)) return { error: 'Codes need 4 to 40 characters.' };
cfg.families.push({ id: crypto.randomBytes(4).toString('hex'), name: fam, code: code || newCode(), players: [], own: !!m.own });
return { changed: 'added family ' + fam + (m.own ? ' (own world)' : '') };
}
case 'setOwn': { // own: true = their own private world + game rooms, false = play with everyone
const f = findFam(fam); if (!f) return { error: 'No family called ' + fam + '.' };
if (!!f.own === !!m.own) return { error: f.name + ' already plays ' + (f.own ? 'in their own world' : 'with everyone') + '.' };
f.own = !!m.own;
for (const p of f.players) kick(p, 'Moving you to ' + (f.own ? 'your family\'s own world' : 'the world with everyone') + '...', 'busy');
return { changed: f.name + ' now plays ' + (f.own ? 'in their own world' : 'with everyone') };
}
case 'setCode': {
if (!okCode(code)) return { error: 'Codes need 4 to 40 characters.' };
if (!fam) { cfg.code = code; return { changed: 'changed the home family code' }; }
const f = findFam(fam); if (!f) return { error: 'No family called ' + fam + '.' };
f.code = code; return { changed: 'changed the code for ' + f.name };
}
case 'randomCode': return adminAction(Object.assign({}, m, { action: 'setCode', newCode: newCode() }));
case 'addPlayer': {
if (!NAME_RE.test(nm)) return { error: 'Player names: letters, numbers, spaces, - or _ (up to 16).' };
if (nameTaken(nm)) return { error: nm + ' is already on the list (or waiting). Pick a different name.' };
const f = fam ? findFam(fam) : null; if (fam && !f) return { error: 'No family called ' + fam + '.' };
cfg.names.push(nm); if (f) f.players.push(nm);
return { changed: 'added ' + nm + ' to ' + (f ? f.name : 'the home family') };
}
case 'makeInvite': { // a link anyone can use for 7 days to ask to join this family (you still approve each one)
const f = fam ? findFam(fam) : null; if (fam && !f) return { error: 'No family called ' + fam + '.' };
cfg.invites = cfg.invites.filter(i => i.expires > Date.now());
cfg.invites.push({ code: crypto.randomBytes(9).toString('base64url'), family: f ? f.name : '', expires: Date.now() + 7 * 86400000 });
return { changed: 'made an invite link for ' + famLabel(f) };
}
case 'stopInvite': {
const before = cfg.invites.length; cfg.invites = cfg.invites.filter(i => i.code !== String(m.invite || ''));
return before === cfg.invites.length ? { error: 'That invite link was already stopped.' } : { changed: 'stopped an invite link' };
}
case 'approve': case 'deny': {
const p = cfg.pending.find(x => lc(x.name) === lc(nm)); if (!p) return { error: nm + ' is not waiting.' };
cfg.pending = cfg.pending.filter(x => x !== p);
if (m.action === 'deny') return { changed: 'said no to ' + p.name };
if (cfg.names.some(n => lc(n) === lc(p.name))) return { error: p.name + ' is already on the list.' };
const f = findFam(p.family); // family removed meanwhile -> home family
cfg.names.push(p.name); if (f) f.players.push(p.name); cfg.pw[lc(p.name)] = p.hash;
return { changed: 'approved ' + p.name + ' for ' + famLabel(f) };
}
case 'resetPw': { // new password, shown once on the page (never logged)
if (lc(nm) === 'admin' || !cfg.names.some(n => lc(n) === lc(nm))) return { error: nm + ' is not on the list.' };
const pw = newCode(); cfg.pw[lc(nm)] = hashPw(pw);
return { changed: 'reset the password for ' + nm, once: 'New password for ' + nm + ': ' + pw };
}
case 'clearPw': {
if (!cfg.pw[lc(nm)]) return { error: nm + ' has no own password.' };
delete cfg.pw[lc(nm)];
return { changed: nm + ' now signs in with the family code' };
}
case 'removePlayer': {
if (lc(nm) === 'admin' || !cfg.names.some(n => lc(n) === lc(nm))) return { error: nm + ' is not on the list.' };
cfg.names = cfg.names.filter(n => lc(n) !== lc(nm)); delete cfg.pw[lc(nm)];
for (const f of cfg.families) f.players = f.players.filter(p => lc(p) !== lc(nm));
kick(nm, 'That name is not on the family list.');
return { changed: 'removed ' + nm + ' (their saved stuff in the world is kept)' };
}
case 'removeFamily': {
const f = findFam(fam); if (!f) return { error: 'No family called ' + fam + '.' };
cfg.families = cfg.families.filter(x => x !== f);
cfg.names = cfg.names.filter(n => !f.players.some(p => lc(p) === lc(n)));
cfg.invites = cfg.invites.filter(i => i.family !== f.name);
cfg.pending = cfg.pending.filter(p => p.family !== f.name);
for (const p of f.players) { delete cfg.pw[lc(p)]; kick(p, 'That name is not on the family list.'); }
return { changed: 'removed family ' + f.name + (f.players.length ? ' and its players ' + f.players.join(', ') : '') };
}
}
return { error: 'Unknown action.' };
}
// ---------------------------------------------------------------- players
const wss = new WebSocket.Server({ server, path: '/blockcraft/ws', maxPayload: 256 * 1024 });
const ALLOWED = new Set(['move', 'block', 'hit', 'shoot', 'ignite', 'chest', 'chestSet', 'sleep', 'chat',
'vplace', 'vride', 'vmove', 'vleave', 'vpickup', 'kit', 'stairs', 'travel', 'pet', 'petname', 'feed', 'tame', 'wake', 'petgift']);
wss.on('connection', (ws, req) => {
let id = null, name = null, W = null; // W = the world this player is in
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
ws.alive = true; ws.on('pong', () => { ws.alive = true; });
ws.on('message', raw => {
let m; try { m = JSON.parse(raw); } catch (e) { return; }
if (!m || typeof m.t !== 'string') return;
if (id === null) {
if (m.t !== 'join') return;
const nm = String(m.name || '').trim();
// admin has its own password (config adminCode) once one is set; everyone else uses the family code
// cousins/friends families have their own code, invited players their own password (see checkLogin)
const isAdmin = nm.toLowerCase() === 'admin' && !!cfg.adminCode;
if (!checkLogin(nm, m.code || '') && !homeKid(nm, req)) {
console.log(new Date().toISOString(), 'bad code for', JSON.stringify(nm.slice(0, 16)), ip, 'dev', String(m.dev || '').slice(0, 6), m.typed ? 'typed' : 'saved');
ws.send(JSON.stringify({ t: 'error', text: isAdmin ? 'Wrong admin password.' : 'Wrong family code.' })); return;
}
if (!/^[A-Za-z0-9 _-]{1,16}$/.test(nm)) { ws.send(JSON.stringify({ t: 'error', text: 'Names can use letters and numbers (up to 16).' })); return; }
if (cfg.names.length && !cfg.names.map(n => n.toLowerCase()).includes(nm.toLowerCase())) { ws.send(JSON.stringify({ t: 'error', text: 'That name is not on the family list.' })); return; }
const brk = playState(nm, false).breakUntil;
if (brk) { ws.send(JSON.stringify({ t: 'break', until: brk, name: nm })); setTimeout(() => ws.close(), 200); return; }
// one name plays on one tablet at a time: the same tablet (dev id) may replace its old connection
// (reload, Wi-Fi blip), another tablet is turned away instead of stealing the name
const dev = String(m.dev || '').slice(0, 40);
for (const [oid, c] of conns) if (c.name.toLowerCase() === nm.toLowerCase()) {
if (!dev || c.dev !== dev) {
console.log(new Date().toISOString(), 'refused', JSON.stringify(nm), '(playing on another tablet)', ip);
// 'busy', not 'error': the tablet stays signed in (older pages ignore it and keep their sign-in too)
ws.send(JSON.stringify({ t: 'busy', text: c.name + ' is already playing on another tablet.' }));
setTimeout(() => ws.close(), 200); return;
}
c.ws.terminate(); conns.delete(oid); c.W.sim.removePlayer(oid);
console.log(new Date().toISOString(), 'replaced', c.name, '(same tablet)');
}
id = nextId++; name = nm; W = getWorld(worldKeyFor(nm));
const sim = W.sim, you = W.playersData[nm.toLowerCase()] || null;
conns.set(id, { ws, name, dev, W });
sim.addPlayer(id, name, you ? { x: you.x, y: you.y, z: you.z } : W.spawn);
ws.send(JSON.stringify({ t: 'welcome', id, name, seed: W.seed, time: sim.time, edits: sim.world.encodeEdits(), spawn: W.spawn, you, owned: sim.owned, pet: sim.petsOf(nm), air: sim.dungeon.air || [], dungeon: sim.dungeon.entrance, kingdom: sim.kingdom.gate, tales: talesOf(nm) }));
W.send({ t: 'msg', text: name + ' joined the game' }, null);
// dev + typed: a new dev for the same kid means the tablet lost its saved sign-in; typed means someone had to type it
console.log(new Date().toISOString(), 'join', name, 'world', W.key || 'shared', ip, 'dev', dev.slice(0, 6), m.typed ? 'typed' : 'saved');
return;
}
if (m.t === 'save') {
if (m.data && JSON.stringify(m.data).length < 30000) { W.playersData[name.toLowerCase()] = m.data; W.dirty = true; }
return;
}
if (!ALLOWED.has(m.t)) return;
if (m.t === 'block' && !((m.id >= 0 && m.id < 61) || (m.id >= 92 && m.id <= 96))) return; // players place ordinary blocks (+ playground pieces, heart blocks): stairwells and story blocks come from the game
W.sim.handle(id, m);
if (m.t[0] === 'v' || m.t[0] === 'p' || m.t === 'kit' || m.t === 'stairs' || m.t === 'travel' || m.t === 'hit') W.dirty = true;
});
ws.on('close', () => {
if (id === null || !conns.has(id) || conns.get(id).ws !== ws) return;
conns.delete(id); W.sim.removePlayer(id);
W.send({ t: 'msg', text: name + ' left the game' }, null);
console.log(new Date().toISOString(), 'leave', name);
});
});
// ---------------------------------------------------------------- loop
let last = Date.now();
setInterval(() => {
const now = Date.now(), dt = Math.min(0.1, (now - last) / 1000); last = now;
const busy = new Set([...conns.values()].map(c => c.W));
for (const W of busy) W.sim.tick(dt);
}, 50);
const saveAll = () => { for (const W of worlds.values()) if (W.dirty) saveWorld(W); savePlay(); };
setInterval(saveAll, 30000);
// play time: count everyone online every 10 seconds; at 30 minutes send them to their break
setInterval(() => {
for (const [cid, c] of conns) {
const s = playState(c.name, true);
try { c.ws.send(JSON.stringify(s.breakUntil ? { t: 'break', until: s.breakUntil, name: c.name } : { t: 'play', left: s.left })); } catch (e) {}
if (s.breakUntil) setTimeout(() => { if (conns.get(cid) === c) c.ws.close(); }, 1000);
}
}, 10000);
// drop tablets that vanished without closing (Wi-Fi off, sleep) so their name is free again
setInterval(() => {
for (const ws of wss.clients) { if (!ws.alive) { ws.terminate(); continue; } ws.alive = false; try { ws.ping(); } catch (e) {} }
}, 15000);
const stop = () => { try { saveAll(); } catch (e) { console.error(e); } process.exit(0); };
process.on('SIGTERM', stop); process.on('SIGINT', stop);
server.listen(cfg.port, () => console.log('BlockCraft on port ' + cfg.port + ', seed ' + shared.seed + ', spawn ' + JSON.stringify(shared.spawn)));
EOF
test-client.js: the two-player check now also looks inside the nearest castle’s treasure chest (it only looks; nothing is taken).
cat > /root/blockcraft/test-client.js <<'EOF'
'use strict';
// Smoke test, run inside CT 127: node test-client.js
// Two fake players join on 127.0.0.1, one places a block, the other must see it.
const WebSocket = require('ws');
const cfg = require('./config.json');
const url = 'ws://127.0.0.1:' + cfg.port + '/blockcraft/ws';
function player(name, dev) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(url), p = { ws, name, msgs: [] };
ws.on('open', () => ws.send(JSON.stringify({ t: 'join', name, dev: dev || 'test-' + name, code: name === 'admin' && cfg.adminCode ? cfg.adminCode : cfg.code })));
ws.on('message', d => { const m = JSON.parse(d); p.msgs.push(m); if (m.t === 'welcome') { p.welcome = m; resolve(p); } if (m.t === 'error' || m.t === 'busy') reject(new Error(m.t + ': ' + m.text)); });
ws.on('error', reject);
setTimeout(() => reject(new Error('timeout ' + name)), 5000);
});
}
(async () => {
const bad = await new Promise(res => {
const ws = new WebSocket(url);
ws.on('open', () => ws.send(JSON.stringify({ t: 'join', name: 'Luca', code: 'wrong' })));
ws.on('message', d => { res(JSON.parse(d)); ws.close(); });
});
console.log('wrong code ->', bad.t, bad.text);
if (cfg.adminCode) {
const badAdmin = await new Promise(res => {
const ws = new WebSocket(url);
ws.on('open', () => ws.send(JSON.stringify({ t: 'join', name: 'admin', code: cfg.code })));
ws.on('message', d => { res(JSON.parse(d)); ws.close(); });
});
console.log('admin with family code ->', badAdmin.t, badAdmin.text);
if (badAdmin.t !== 'error') { console.log('FAIL: admin got in with the family code'); process.exit(1); }
}
const a = await player('admin'), b = await player('Luca');
console.log('joined', a.welcome.id, b.welcome.id, 'seed', a.welcome.seed, 'spawn', JSON.stringify(a.welcome.spawn));
const s = a.welcome.spawn, x = Math.floor(s.x) + 2, y = Math.floor(s.y) + 3, z = Math.floor(s.z);
a.ws.send(JSON.stringify({ t: 'move', x: s.x, y: s.y, z: s.z, yaw: 0, pitch: 0 }));
a.ws.send(JSON.stringify({ t: 'block', x, y, z, id: 49 }));
await new Promise(r => setTimeout(r, 600));
const seen = b.msgs.some(m => m.t === 'blocks' && m.l.some((v, i) => i % 4 === 0 && m.l[i] === x && m.l[i + 1] === y && m.l[i + 2] === z && m.l[i + 3] === 49));
const snaps = b.msgs.filter(m => m.t === 'snap');
console.log('B saw the block:', seen, '| snapshots:', snaps.length, '| players in last snap:', snaps.length ? snaps[snaps.length - 1].players.map(p => p[1]).join(',') : '-');
a.ws.send(JSON.stringify({ t: 'block', x, y, z, id: 0 }));
await new Promise(r => setTimeout(r, 300));
// vehicles: A sets down an airplane, B may not get in, A flies it, B sees it move, A picks it back up
const wait = ms => new Promise(r => setTimeout(r, ms)), last = p => p.msgs.filter(m => m.t === 'snap').pop();
a.ws.send(JSON.stringify({ t: 'vplace', kind: 'plane', x: s.x + 5, y: s.y + 20, z: s.z, yaw: 0 }));
await wait(400);
const pv = last(b).vehicles.find(v => v[9] === a.name);
b.ws.send(JSON.stringify({ t: 'vride', id: pv[0] })); a.ws.send(JSON.stringify({ t: 'vride', id: pv[0] }));
await wait(300);
const refused = b.msgs.some(m => m.t === 'msg' && /admin's/.test(m.text)), rideOk = a.msgs.some(m => m.t === 'vride');
a.ws.send(JSON.stringify({ t: 'vmove', id: pv[0], x: s.x + 9, y: s.y + 30, z: s.z + 3, yaw: 1, pitch: 0.2, roll: 0.1 }));
await wait(400);
const bv = last(b).vehicles.find(v => v[0] === pv[0]), flew = bv && bv[2] === s.x + 9 && bv[8] === a.welcome.id;
a.ws.send(JSON.stringify({ t: 'vleave', id: pv[0], x: s.x + 9, y: s.y, z: s.z + 3 }));
b.ws.send(JSON.stringify({ t: 'vpickup', id: pv[0] })); await wait(200);
a.ws.send(JSON.stringify({ t: 'vpickup', id: pv[0] })); await wait(400);
const back = a.msgs.some(m => m.t === 'drop' && m.items[0][0] === 144), gone = !last(b).vehicles.some(v => v[0] === pv[0]);
const vOK = refused && rideOk && flew && back && gone;
console.log('vehicle: placed', !!pv, '| other kid refused', refused, '| owner got in', rideOk, '| B saw it fly', flew, '| picked up', back, '| gone', gone);
// treasure: look inside the nearest castle's treasure chest (only looks, takes nothing)
const BC = require('./public/engine.js');
let near = null;
for (let r = -3; r <= 3; r++) for (let q = -3; q <= 3; q++) {
const c = BC.castleAt(Math.floor(s.x / BC.REG) + r, Math.floor(s.z / BC.REG) + q, a.welcome.seed);
if (c && (!near || Math.hypot(c.x0 - s.x, c.z0 - s.z) < Math.hypot(near.x0 - s.x, near.z0 - s.z))) near = c;
}
let tOK = !near;
if (near) {
const k = (near.x0 + 10) + ',' + (near.base + 1) + ',' + (near.z0 + 14);
a.ws.send(JSON.stringify({ t: 'chest', k })); await wait(400);
const ch = a.msgs.filter(m => m.t === 'chest' && m.k === k).pop();
tOK = !!ch && ch.slots.length > 0;
console.log('treasure: nearest is a', BC.CASTLES[near.type].name, 'at', near.x0 + 10, near.z0 + 10, '| chest has', ch ? ch.slots.length : 0, 'kinds of things | kit castles:', (a.welcome.owned || []).length);
}
// dungeon: walk to the shrine by spawn, take the stairs down to Floor 1, then the Way Up back
const e = a.welcome.dungeon;
let dOK = false;
if (e) {
a.ws.send(JSON.stringify({ t: 'move', x: e.x + 0.5, y: e.y + 1, z: e.z + 2.5, yaw: 0, pitch: 0 })); await wait(200);
a.ws.send(JSON.stringify({ t: 'stairs', x: e.x, y: e.y, z: e.z })); await wait(500);
const down = a.msgs.filter(m => m.t === 'tp').pop();
if (down && down.floor === 1) {
a.ws.send(JSON.stringify({ t: 'move', x: down.x, y: down.y, z: down.z, yaw: 0, pitch: 0 })); await wait(200);
a.ws.send(JSON.stringify({ t: 'stairs', x: Math.floor(down.x), y: down.y, z: Math.floor(down.z) - 2 })); await wait(500);
const up = a.msgs.filter(m => m.t === 'tp').pop();
dOK = up !== down && up.floor === 0;
}
console.log('dungeon: entrance at', e.x, e.y, e.z, '| went down to Floor', down ? down.floor : '-', '| came back up', dOK);
}
// fairy tale kingdom: through the Story Book arch and back by the Way Home (full checks: test-kingdom.js)
const g = a.welcome.kingdom;
let kOK = false;
if (g) {
a.ws.send(JSON.stringify({ t: 'move', x: g.x + 0.5, y: g.y, z: g.z + 2.5, yaw: 0, pitch: 0 })); await wait(200);
a.ws.send(JSON.stringify({ t: 'stairs', x: g.x, y: g.y, z: g.z })); await wait(500);
const tin = a.msgs.filter(m => m.t === 'tp').pop();
if (tin && tin.kingdom === 1) {
a.ws.send(JSON.stringify({ t: 'move', x: tin.x, y: tin.y, z: tin.z, yaw: 0, pitch: 0 })); await wait(200);
a.ws.send(JSON.stringify({ t: 'stairs', x: BC.PLAZA.x, y: BC.KY + 1, z: BC.PLAZA.z })); await wait(500);
const tout = a.msgs.filter(m => m.t === 'tp').pop();
kOK = tout.kingdom === 2;
}
}
console.log('fairy tale kingdom: arch at', g ? [g.x, g.y, g.z].join(',') : '-', '| in and back out', kOK);
// one name, one tablet: another tablet is turned away, the same tablet may reconnect
const other = await player('Luca', 'test-other-tablet').then(() => 'got in', err => err.message);
const again = await player('Luca').then(p => { p.ws.close(); return true; }, () => false);
const oOK = /^busy: .*another tablet/.test(other) && again; // busy, not error: the refused tablet stays signed in
console.log('one tablet per name: other tablet ->', other, '| same tablet reconnect', again);
a.ws.close(); b.ws.close();
setTimeout(() => process.exit(seen && vOK && tOK && dOK && kOK && oOK ? 0 : 1), 300);
})().catch(e => { console.error('FAIL', e.message); process.exit(1); });
EOF
3. Push the files into CT 127 and restart
It copies the game files in, restarts the server and prints active. The family code, the name list and the saved world are not touched. Anyone playing gets disconnected and the game rejoins by itself:
bash /root/blockcraft/04-push.sh
4. Check it
Copy the new test into CT 127:
pct push 127 /root/blockcraft/test-client.js /opt/blockcraft/test-client.js
Run it. Healthy output ends with a treasure: line naming the nearest castle to the spawn point, its position and how many kinds of things its chest holds (more than 0):
pct exec 127 -- node /opt/blockcraft/test-client.js
Then on a tablet: open https://games.503mail.com/blockcraft/, open MAP to find your way, and walk to the castle the test named (turn on Show position in the pause menu to see your X and Z).
Troubleshooting: where the logs are
The game server
- Where: the systemd journal for
blockcraftinside CT 127 (blockcraft). - Open: Proxmox host shell.
pct exec 127 -- journalctl -u blockcraft -n 50 --no-pager
- Look for:
BlockCraft on port 8080, seed ..., spawn {...}after the restart. A JavaScript stack trace followed byblockcraft.service: Main process exitedmeans a file didn’t paste completely; paste it again and rerun04-push.sh.
Kit castles and treasure chests
- Where:
/opt/blockcraft/data/world.jsonin CT 127:ownedlists every kit castle (corner position, type, owner) andchestsholds what is in every chest that has been opened. - Open: Proxmox host shell. Lists the kit castles:
pct exec 127 -- node -e "const w=require('/opt/blockcraft/data/world.json');console.log(w.owned||'no kit castles yet')"
- A new kit castle can take up to 30 seconds to show up in the file (the save interval).
In the game itself
- “This is Layla’s castle” / “Only Layla can open this chest”: working as intended; only the owner can change a kit castle.
- “Too close to Layla’s castle”: kit castles need a little space between them. The kit is given back.
- A recipe is grey: something is missing, or there is no crafting table within 4 blocks. Recipes show in Survival only.
- No new castles near home: castles appear in land nobody has changed yet, at most one every 128 blocks; use the map and explore further.
- A potion seems to do nothing: check the pink list in the top-left corner. Effects end when you die.
Notes
- Tested: in a single-player world in the browser (all five castle types generate, each chest holds its own treasure, a Desert Palace kit built itself with its owner’s flag, the speed and healing potions, wearing diamond boots and a diamond chestplate, armor cutting a 10-point hit to 5.6, the bag icons), the ownership rules with two pretend players (the other kid can’t break blocks, build next to it or open its chest; the owner can), and on the live family server with the test above. Not yet tried on the Fire 7 tablets.
- Kid-friendly choices: potions give the bottle back, effects are shown with a countdown, a kit that can’t be built is returned, and you keep your armor when you die.
- Ideas for later: showing worn armor on the player model, castle guards that protect the Royal Castle treasure, a brewing stand, and more fruit trees.