RotNot / src /lib /puzzles /wordscramble.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
18.4 kB
/**
* Word scramble puzzle generator.
* Generates anagram puzzles where the player unscrambles letters to form a word.
*
* Difficulty scaling:
* easy: 4-5 letter words, 1 hint letter revealed
* medium: 6-7 letter words, no hints
* hard: 8-10 letter words, no hints, timed pressure (UI handles timer)
*
* All words are common English words — no obscure vocabulary.
*/
export type WordScrambleDifficulty = "easy" | "medium" | "hard";
export interface WordScramblePuzzle {
/** The scrambled letters (uppercase) */
scrambled: string;
/** The correct answer (uppercase) */
answer: string;
/** Indices in the scrambled string that are revealed as hints (for easy mode) */
hintIndices: number[];
/** A contextual hint about the word's meaning */
hint: string;
/** Difficulty level */
difficulty: WordScrambleDifficulty;
/** Word category for metadata */
category: string;
/** Word length */
length: number;
}
// ---------- Word pools by difficulty ----------
export interface WordEntry {
word: string;
hint: string;
category: string;
}
export const EASY_WORDS: WordEntry[] = [
{ word: "TREE", hint: "Found in a forest", category: "nature" },
{ word: "BIRD", hint: "It flies in the sky", category: "nature" },
{ word: "FISH", hint: "Lives in water", category: "nature" },
{ word: "CAKE", hint: "A birthday treat", category: "food" },
{ word: "MILK", hint: "White drink from cows", category: "food" },
{ word: "RAIN", hint: "Falls from clouds", category: "weather" },
{ word: "STAR", hint: "Twinkles at night", category: "space" },
{ word: "MOON", hint: "Orbits the Earth", category: "space" },
{ word: "FIRE", hint: "Hot and bright", category: "elements" },
{ word: "WIND", hint: "You can feel it but not see it", category: "weather" },
{ word: "LAKE", hint: "A body of still water", category: "nature" },
{ word: "SEED", hint: "A plant grows from this", category: "nature" },
{ word: "DRUM", hint: "A percussion instrument", category: "music" },
{ word: "SHIP", hint: "Sails across the ocean", category: "transport" },
{ word: "COIN", hint: "Metal money", category: "objects" },
{ word: "LAMP", hint: "Gives off light", category: "objects" },
{ word: "FROG", hint: "A green amphibian", category: "nature" },
{ word: "DOOR", hint: "You open this to enter a room", category: "objects" },
{ word: "ROPE", hint: "Used for tying things", category: "objects" },
{ word: "LEAF", hint: "Part of a tree that falls in autumn", category: "nature" },
{ word: "FLAME", hint: "The visible part of fire", category: "elements" },
{ word: "CLOUD", hint: "White and fluffy in the sky", category: "weather" },
{ word: "STONE", hint: "A small rock", category: "nature" },
{ word: "BEACH", hint: "Sandy shore by the sea", category: "nature" },
{ word: "BREAD", hint: "A baked food staple", category: "food" },
{ word: "MUSIC", hint: "Art of sound", category: "music" },
{ word: "HORSE", hint: "You can ride this animal", category: "nature" },
{ word: "GLOBE", hint: "A round model of the Earth", category: "objects" },
{ word: "CHESS", hint: "A strategy board game", category: "games" },
{ word: "LIGHT", hint: "Opposite of dark", category: "elements" },
{ word: "WOLF", hint: "Howls at the moon", category: "nature" },
{ word: "NEST", hint: "A bird's home", category: "nature" },
{ word: "BELL", hint: "Rings to make a sound", category: "objects" },
{ word: "IRON", hint: "A strong metal", category: "science" },
{ word: "GOLD", hint: "A precious yellow metal", category: "science" },
{ word: "BONE", hint: "Part of a skeleton", category: "science" },
{ word: "FORK", hint: "Used for eating", category: "objects" },
{ word: "WAVE", hint: "Rolls across the ocean", category: "nature" },
{ word: "DESK", hint: "You sit at one to work", category: "objects" },
{ word: "CLAY", hint: "Moldable earth material", category: "nature" },
{ word: "KNOT", hint: "A tied loop in rope", category: "objects" },
{ word: "HARP", hint: "A stringed instrument", category: "music" },
{ word: "MAZE", hint: "A confusing network of paths", category: "games" },
{ word: "DICE", hint: "Cubes with dots used in games", category: "games" },
{ word: "CORAL", hint: "Grows in the ocean", category: "nature" },
{ word: "FLUTE", hint: "A wind instrument", category: "music" },
{ word: "BRUSH", hint: "Used for painting or hair", category: "objects" },
{ word: "GRAIN", hint: "Wheat, rice, or oats", category: "food" },
{ word: "CREST", hint: "The top of a wave or hill", category: "nature" },
{ word: "TORCH", hint: "A portable light source", category: "objects" },
{ word: "PEARL", hint: "Gem from an oyster", category: "nature" },
{ word: "SWAMP", hint: "Wet, marshy land", category: "nature" },
{ word: "SKULL", hint: "Bone that protects the brain", category: "science" },
{ word: "STORM", hint: "Violent weather event", category: "weather" },
{ word: "CANAL", hint: "A man-made waterway", category: "structures" },
{ word: "PIANO", hint: "A keyboard instrument", category: "music" },
{ word: "CROWN", hint: "Worn on a royal head", category: "objects" },
{ word: "STEEL", hint: "An alloy of iron and carbon", category: "science" },
{ word: "BADGE", hint: "Worn to show identity or rank", category: "objects" },
{ word: "FROST", hint: "Thin ice crystals on surfaces", category: "weather" },
];
export const MEDIUM_WORDS: WordEntry[] = [
{ word: "BRIDGE", hint: "Connects two sides over water", category: "structures" },
{ word: "CASTLE", hint: "A medieval fortress", category: "structures" },
{ word: "PLANET", hint: "Orbits a star", category: "space" },
{ word: "JUNGLE", hint: "Dense tropical forest", category: "nature" },
{ word: "ROCKET", hint: "Launches into space", category: "space" },
{ word: "FROZEN", hint: "Extremely cold, turned to ice", category: "weather" },
{ word: "RHYTHM", hint: "A repeated pattern of beats", category: "music" },
{ word: "DESERT", hint: "A dry, sandy landscape", category: "nature" },
{ word: "PUZZLE", hint: "A problem to be solved", category: "games" },
{ word: "GARDEN", hint: "Where flowers grow", category: "nature" },
{ word: "SIGNAL", hint: "A message or indicator", category: "objects" },
{ word: "CANDLE", hint: "Wax stick that gives light", category: "objects" },
{ word: "FLAVOR", hint: "The taste of food", category: "food" },
{ word: "ANCHOR", hint: "Keeps a ship in place", category: "transport" },
{ word: "BASKET", hint: "Used to carry things", category: "objects" },
{ word: "TURTLE", hint: "Slow reptile with a shell", category: "nature" },
{ word: "OXYGEN", hint: "Gas we breathe", category: "science" },
{ word: "COPPER", hint: "A reddish-brown metal", category: "science" },
{ word: "SUMMIT", hint: "The top of a mountain", category: "nature" },
{ word: "LEGEND", hint: "A famous story from the past", category: "stories" },
{ word: "CIPHER", hint: "A secret code", category: "science" },
{ word: "MARKET", hint: "A place to buy and sell goods", category: "places" },
{ word: "SHADOW", hint: "Dark shape cast by blocking light", category: "elements" },
{ word: "BRANCH", hint: "Part of a tree extending from the trunk", category: "nature" },
{ word: "VOYAGE", hint: "A long journey by sea", category: "transport" },
{ word: "CRYSTAL", hint: "A clear, sparkling mineral", category: "science" },
{ word: "HARVEST", hint: "Gathering crops", category: "nature" },
{ word: "COMPASS", hint: "Points north", category: "objects" },
{ word: "PRISM", hint: "Splits light into colors", category: "science" },
{ word: "THRONE", hint: "A royal seat", category: "objects" },
{ word: "MAGNET", hint: "Attracts metal objects", category: "science" },
{ word: "TEMPLE", hint: "A place of worship", category: "structures" },
{ word: "FOSSIL", hint: "Preserved remains of ancient life", category: "science" },
{ word: "PIRATE", hint: "Sails the seas seeking treasure", category: "stories" },
{ word: "METEOR", hint: "A shooting star in the sky", category: "space" },
{ word: "VALLEY", hint: "Low land between hills", category: "nature" },
{ word: "POISON", hint: "A harmful substance", category: "science" },
{ word: "PALACE", hint: "A grand royal residence", category: "structures" },
{ word: "RIDDLE", hint: "A tricky question or puzzle", category: "games" },
{ word: "SALMON", hint: "A pink fish that swims upstream", category: "nature" },
{ word: "QUARTZ", hint: "A common crystal mineral", category: "science" },
{ word: "TABLET", hint: "A flat computing device", category: "objects" },
{ word: "NAPKIN", hint: "Used to wipe your hands at dinner", category: "objects" },
{ word: "FURROW", hint: "A groove made in soil by plowing", category: "nature" },
{ word: "GALLON", hint: "A unit of liquid measurement", category: "science" },
{ word: "FALCON", hint: "A fast bird of prey", category: "nature" },
{ word: "SPIDER", hint: "Spins webs to catch insects", category: "nature" },
{ word: "TROPHY", hint: "A prize for winning", category: "games" },
{ word: "BREEZE", hint: "A gentle wind", category: "weather" },
{ word: "GOBLET", hint: "A fancy drinking cup", category: "objects" },
{ word: "SHIELD", hint: "Protects a warrior in battle", category: "objects" },
{ word: "VELVET", hint: "A soft, smooth fabric", category: "objects" },
{ word: "PEBBLE", hint: "A small, smooth stone", category: "nature" },
{ word: "BONFIRE", hint: "A large outdoor fire", category: "elements" },
{ word: "CANYON", hint: "A deep gorge carved by a river", category: "nature" },
{ word: "NECTAR", hint: "Sweet liquid in flowers", category: "nature" },
{ word: "PARROT", hint: "A colorful bird that can talk", category: "nature" },
{ word: "WALRUS", hint: "A large tusked marine mammal", category: "nature" },
{ word: "TUNNEL", hint: "An underground passage", category: "structures" },
{ word: "BADGER", hint: "A burrowing nocturnal mammal", category: "nature" },
];
export const HARD_WORDS: WordEntry[] = [
{ word: "MOUNTAIN", hint: "A tall natural landform", category: "nature" },
{ word: "ALPHABET", hint: "Set of letters in a language", category: "language" },
{ word: "SYMPHONY", hint: "A large musical composition", category: "music" },
{ word: "TREASURE", hint: "Valuable hidden wealth", category: "stories" },
{ word: "LABYRINTH", hint: "A complex maze", category: "structures" },
{ word: "SPECTRUM", hint: "A range of colors or wavelengths", category: "science" },
{ word: "BLIZZARD", hint: "A severe snowstorm", category: "weather" },
{ word: "CHAMPION", hint: "A winner of a competition", category: "games" },
{ word: "DINOSAUR", hint: "Extinct prehistoric creature", category: "science" },
{ word: "ELECTRON", hint: "Subatomic particle with negative charge", category: "science" },
{ word: "FORENSIC", hint: "Related to criminal investigation science", category: "science" },
{ word: "GARGOYLE", hint: "Stone creature on old buildings", category: "structures" },
{ word: "HANDBOOK", hint: "A manual or guide", category: "objects" },
{ word: "IMPERIAL", hint: "Related to an empire", category: "history" },
{ word: "JUKEBOX", hint: "Coin-operated music machine", category: "music" },
{ word: "MAGNETIC", hint: "Attracts iron and steel", category: "science" },
{ word: "NAVIGATE", hint: "To find your way", category: "transport" },
{ word: "OBSTACLE", hint: "Something in the way", category: "games" },
{ word: "PENDULUM", hint: "Swings back and forth", category: "science" },
{ word: "THOUSAND", hint: "The number 1,000", category: "language" },
{ word: "PROLOGUE", hint: "Introduction to a story", category: "stories" },
{ word: "SKELETON", hint: "Framework of bones", category: "science" },
{ word: "TRIBUNAL", hint: "A court of justice", category: "history" },
{ word: "UPSTREAM", hint: "Against the flow of a river", category: "nature" },
{ word: "VANGUARD", hint: "The leading position", category: "history" },
{ word: "WORKSHOP", hint: "A place where things are made", category: "places" },
{ word: "YEARBOOK", hint: "Annual school publication", category: "objects" },
{ word: "ABSOLUTE", hint: "Complete, with no exceptions", category: "language" },
{ word: "BACKFLIP", hint: "An acrobatic backward somersault", category: "games" },
{ word: "CONQUEST", hint: "The act of conquering", category: "history" },
{ word: "COMPOUND", hint: "Made of two or more parts", category: "science" },
{ word: "SANDWICH", hint: "Bread with filling in between", category: "food" },
{ word: "MINOTAUR", hint: "Mythical half-bull creature", category: "stories" },
{ word: "WIRELESS", hint: "Without cables or cords", category: "science" },
{ word: "GRAPHITE", hint: "Mineral used in pencils", category: "science" },
{ word: "CINNAMON", hint: "A sweet brown spice", category: "food" },
{ word: "BOOKMARK", hint: "Marks your place in a book", category: "objects" },
{ word: "STAMPEDE", hint: "A sudden rush of animals", category: "nature" },
{ word: "GUARDIAN", hint: "A protector or keeper", category: "stories" },
{ word: "MOLECULE", hint: "The smallest unit of a compound", category: "science" },
{ word: "PLATFORM", hint: "A raised flat surface", category: "structures" },
{ word: "LIFEBOAT", hint: "Emergency boat on a ship", category: "transport" },
{ word: "TWILIGHT", hint: "The dim light after sunset", category: "elements" },
{ word: "PARACHUTE", hint: "Slows a fall from the sky", category: "transport" },
{ word: "CROSSBOW", hint: "A medieval ranged weapon", category: "history" },
{ word: "DYNAMITE", hint: "An explosive invented by Nobel", category: "science" },
{ word: "MACARONI", hint: "A curved pasta shape", category: "food" },
{ word: "ORGANISM", hint: "Any living thing", category: "science" },
{ word: "MONOPOLY", hint: "A popular board game", category: "games" },
{ word: "CALCULUS", hint: "A branch of advanced mathematics", category: "science" },
{ word: "TRIANGLE", hint: "A three-sided shape", category: "science" },
{ word: "PREDATOR", hint: "An animal that hunts others", category: "nature" },
{ word: "ASTEROID", hint: "A rocky body orbiting the sun", category: "space" },
{ word: "INCIDENT", hint: "An unexpected event", category: "language" },
{ word: "MEDIEVAL", hint: "Relating to the Middle Ages", category: "history" },
{ word: "FIREWALL", hint: "A network security barrier", category: "science" },
{ word: "AQUARIUM", hint: "A tank for keeping fish", category: "objects" },
{ word: "FOLKLORE", hint: "Traditional stories and beliefs", category: "stories" },
{ word: "KNAPSACK", hint: "A bag carried on the back", category: "objects" },
{ word: "COLOSSEUM", hint: "Ancient Roman amphitheater", category: "history" },
];
// ---------- Scrambling ----------
/**
* Scramble a word ensuring the result differs from the original.
* Uses Fisher-Yates shuffle. Re-shuffles up to 20 times if the result
* matches the original (possible with short words like "NOON").
*/
export function scrambleWord(word: string): string {
const letters = word.split("");
let attempts = 0;
do {
for (let i = letters.length - 1; i > 0; i--) {
const j = randomInt(0, i);
[letters[i], letters[j]] = [letters[j], letters[i]];
}
attempts++;
} while (letters.join("") === word && attempts < 20);
return letters.join("");
}
// ---------- Hint indices ----------
/**
* Pick hint indices for easy mode. Reveals 1 letter for 4-char words,
* 1-2 for 5-char words. Reveals the first letter position in the scrambled word.
*/
export function pickHintIndices(
scrambled: string,
answer: string,
difficulty: WordScrambleDifficulty,
): number[] {
if (difficulty !== "easy") return [];
const hints: number[] = [];
// Reveal the position(s) where the first letter of the answer appears in scrambled
const firstLetter = answer[0];
for (let i = 0; i < scrambled.length; i++) {
if (scrambled[i] === firstLetter && hints.length === 0) {
hints.push(i);
break;
}
}
// For 5+ letter easy words, also reveal position of the last letter
if (answer.length >= 5) {
const lastLetter = answer[answer.length - 1];
for (let i = scrambled.length - 1; i >= 0; i--) {
if (scrambled[i] === lastLetter && !hints.includes(i)) {
hints.push(i);
break;
}
}
}
return hints.sort((a, b) => a - b);
}
// ---------- Validation ----------
/**
* Check if the player's guess matches the answer (case-insensitive).
*/
export function validateWordScramble(guess: string, answer: string): boolean {
if (!guess || !answer) return false;
return guess.trim().toUpperCase() === answer.trim().toUpperCase();
}
/**
* Score a word scramble puzzle. Returns 1 for correct, 0 for wrong.
* (Binary scoring — no partial credit for anagrams.)
*/
export function scoreWordScramble(guess: string, answer: string): number {
return validateWordScramble(guess, answer) ? 1 : 0;
}
// ---------- Generation ----------
/**
* Get the word pool for a given difficulty.
*/
export function getWordPool(difficulty: WordScrambleDifficulty): WordEntry[] {
switch (difficulty) {
case "easy":
return EASY_WORDS;
case "medium":
return MEDIUM_WORDS;
case "hard":
return HARD_WORDS;
default:
return MEDIUM_WORDS;
}
}
/**
* Generate a word scramble puzzle for the given difficulty.
* Optionally filter by word category.
*/
export function generateWordScramble(
difficulty: WordScrambleDifficulty,
wordCategory?: string,
): WordScramblePuzzle {
let pool = getWordPool(difficulty);
if (wordCategory) {
const filtered = pool.filter(
(w) => w.category.toLowerCase() === wordCategory.toLowerCase(),
);
if (filtered.length > 0) pool = filtered;
}
const entry = pool[randomInt(0, pool.length - 1)];
const scrambled = scrambleWord(entry.word);
const hintIndices = pickHintIndices(scrambled, entry.word, difficulty);
return {
scrambled,
answer: entry.word,
hintIndices,
hint: entry.hint,
difficulty,
category: entry.category,
length: entry.word.length,
};
}
// ---------- Utility ----------
function randomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}