10 Copy-Paste Coding Game Snippets That Teach CSS, Regex & the Terminal

10 free coding game snippets that teach CSS selectors, regex, flexbox and the terminal. Live previews, vanilla JS, one-click React and Vue export.
10 Copy-Paste Coding Game Snippets

Most "learn to code" widgets are quizzes wearing a costume. You read a question, you pick an answer, a green tick appears, and nothing about the way you think has changed — because the thing you were tested on was recall, and the thing that's actually hard is prediction. Does [1, 2, 10].sort() give you what you expect? Does that selector match three elements or five? Does cp src backup work without a flag? You don't find out by being told. You find out by typing something, being wrong, and seeing precisely how wrong.

Below are ten free browser games that do exactly that: a CSS selector challenge that highlights your matches live, a flexbox alignment puzzle graded on pixels rather than properties, a regex trainer with a pass column and a fail column, a simulated terminal that accepts any correct spelling of a command, a bug hunt through seven real JavaScript defects, a timed "predict the output" quiz, a binary bit-flip game, a logic gate circuit puzzle with a full truth table, a sorting puzzle that computes the provable minimum number of swaps, and a robot loop programmer with repeat counts and par scores. Every one is a live, interactive preview — play them right here in the article — and each exports to React, Vue, Angular, or Tailwind in one click from the snippet page.

What makes these teach instead of test

  • They grade the result, not the recipe. The selector game compares the set of elements you matched against the set the answer matches, so any correct spelling passes. The flexbox game measures where the balls physically landed, within 6px, so it can't be gamed and can't be failed on a technicality. Neither one asks you to guess which string the author had in mind.
  • Being wrong is where the content lives. A miss in the selector game tells you whether you were too broad or too narrow, with counts, and outlines the intended targets in dashed amber. The regex game distinguishes "too strict" from "too loose". The bug hunt explains why the line is wrong after you click, not just that it was. Wrong answers are the lesson, so they get the most words.
  • The hard cases are the ones that actually bite. The bug hunt includes return inside a forEach, a debounce missing its clearTimeout, and a stray semicolon after an if. The output quiz covers microtask ordering, var capture in a loop, and lexicographic sort(). These are shipped-to-production bugs, not textbook trivia.

1. CSS Selector Challenge Game

Seven levels of live CSS targeting: read the goal, type a selector, and watch the matching elements glow as you type — from a bare li up through attribute selectors, :nth-child() and :not().

How it works: the whole game is stage.querySelectorAll(value) wrapped in a try/catch — scoped to the stage element, never the document, so a stray * can't select the page around it. That catch is doing more work than it looks: while you're mid-way through typing li:nth-child( the selector is genuinely invalid syntax, so match() returns null and the input border goes red instead of the game throwing. Grading is set equality, not string equality — sameSet() compares your matched elements against the elements the reference answer matches, so .sold.seasonal and li.sold.seasonal both pass, and there's no official answer to guess. The diagnosis on a miss is the part worth stealing: comparing found.length to wanted.length yields "too broad" versus "too narrow" with real counts, and the intended targets get a dashed want outline alongside your own glowing matches.

Best for: onboarding juniors, CSS workshop material, and documentation pages where a selector reference could be a playground instead. Tip: the levels are a LEVELS array of { goal, answer, hint, markup } — swap in your own design system's markup and you have a training tool for your actual class names in about ten minutes.

Grab the code: CSS Selector Challenge Game

2. Flexbox Alignment Game

Six levels of getting balls into ghost slots using nothing but flex-direction, justify-content and align-items — with the generated CSS shown live as you click.

How it works: two stacked flex containers occupy the same space — a ghost layer styled with the level's solution, and a live layer styled by your chips. The win check never compares property values. isSolved() reads getBoundingClientRect() for every ball and every slot and asks whether each ball centre sits within a 6px TOLERANCE of some slot centre. That single decision is what makes the game honest: any combination of properties that physically lands the balls counts as a solve, including the ones the author didn't think of, and a level can't be failed because you found a different route. The check runs inside requestAnimationFrame so the browser has finished laying out the new styles before anything is measured — measure synchronously after setting a style and you're reading the previous frame. A resize listener re-evaluates, because every one of those coordinates is invalidated by a width change.

Best for: teaching flexbox to people who have read the docs three times and still guess. Tip: the live .container { ... } code panel updates on every chip click, which is what closes the loop — you see the property change and the movement at the same instant, and that pairing is the entire pedagogical value.

Grab the code: Flexbox Alignment Game

3. Regex Match Game

Two columns — strings that must match, strings that must not — and one input. Seven levels from literal characters up to anchored email validation, with results repainting on every keystroke.

How it works: compile() runs new RegExp(pattern) inside a try/catch and returns null for anything not yet valid — the same defensive shape as the selector game, and necessary for the same reason, since half of every regex you type is a syntax error on the way to being correct. paint() then runs re.test(s) against each string and marks the row by whether the result equals what that column wants: a match in the "no" column is a failure, which is the distinction most regex tutorials skip entirely. That two-column design is the whole idea — writing a pattern that matches your examples is easy, and writing one that also rejects the near-misses is the actual skill. The feedback names which failure you have: all the "no" strings correct but "yes" strings unmatched reads as "too strict", the reverse reads as "too loose", and a mix reports a raw score.

Best for: regex training, validation-rule workshops, and any team that has shipped an email pattern nobody could review. Tip: results repaint on input but only announce a verdict on Enter or Check — you get continuous feedback without the game declaring you finished mid-keystroke on a pattern you were still extending.

Grab the code: Regex Match Game

4. Terminal Command Game

Eight shell tasks in a simulated terminal — list hidden files, recurse a grep, tail a log, chmod a script — with fake output and a one-line explanation printed on every correct command.

How it works: nothing is executed — each task carries an accept array of regex patterns, and your input is normalised (trim() plus replace(/\s+/g, ' '), so ls -a equals ls -a) before being tested against them. Those patterns are written to accept the real variety of correct answers rather than one blessed string: the hidden-files task accepts -a, -la and -al alike, and chmod takes both +x and the numeric 755 form. That tolerance is what separates a command trainer from a spelling test — a learner who types a genuinely correct variant and gets marked wrong learns the wrong lesson. Success prints plausible output followed by the why line, which is where the teaching actually happens: that quoting "*.log" stops the shell expanding the glob before find ever sees it, that cp refuses directories without -r.

Best for: bootcamps, internal onboarding for a CLI-heavy toolchain, and docs pages where "run this command" could be "try this command". Tip: Skip prints the explanation before advancing rather than silently moving on — a stuck learner still gets the content, which is the difference between a skip button and a give-up button.

Grab the code: Terminal Command Game

5. Bug Hunt Game

Seven short JavaScript functions, each with exactly one real defect. Read the brief, click the offending line, and get the fix plus the reason it fails.

How it works: mechanically it's small — a BUGS array of { file, brief, lines, bug, fix, why }, lines rendered as clickable <li> elements with a data-index, a click compared against bug, and a Fisher–Yates shuffle so the order differs every round. The value is entirely in the bug selection. Seeding let max = 0 makes the function return a number that was never in the input when every element is negative. return true inside a forEach callback exits the callback and nothing else, so the function always returns false. A debounce missing its clearTimeout still fires once per keystroke, just late — it looks like it works until you watch the network tab. And if (order.total > 100); with a trailing semicolon gives every order the discount, passes review, and passes a linter without the right rule enabled. Guessing locks the round so both the real bug and your miss stay highlighted side by side.

Best for: interview practice, code-review training, and the "why does this pass tests and still break" conversation. Tip: the why field is where each entry earns its place — if you fork this with your own team's recurring bugs, write that paragraph first and the rest of the level falls out of it.

Grab the code: Bug Hunt Game

6. Predict the Output Quiz

Eight JavaScript snippets, four options each, fifteen seconds on the clock — typeof null, 0.1 + 0.2, microtask ordering, and the rest of the language's greatest hits.

How it works: a one-second setInterval drains a fifteen-second timer bar via timerFill.style.width, flags itself low under five seconds, and calls reveal(-1) on expiry — timing out is a distinct outcome ("Out of time") rather than a wrong answer. Every path clears the interval and sets an answered guard first, so a click landing in the same tick as the timeout can't score twice. The explanations are the product: typeof null returns 'object' because of low-bit type tagging in the original implementation and was never fixed; [1, 2, 10].sort() gives [1, 10, 2] because the default comparator stringifies; the var-in-a-loop question logs 3 3 3 because all three callbacks close over one binding; and the ordering question shows the microtask queue draining before the next macrotask even when that macrotask's delay is 0. Questions reshuffle each run, so a second pass isn't muscle memory.

Best for: team quiz sessions, interview prep, and JavaScript courses that need a checkpoint between chapters. Tip: keep the timer if you fork this. The pressure is doing real work — it forces prediction rather than the slow reasoning-backwards-from-options that makes multiple choice meaningless.

Grab the code: Predict the Output Quiz

7. Binary Bit Flip Game

Eight bits, one target number. Click or press 1–8 to flip bits and hit the target, with binary, decimal, hex and the place-value sum updating live.

How it works: the entire state is one integer. Bit i is worth Math.pow(2, BITS - 1 - i), and flipping it is value ^= placeValue(i) — XOR toggles exactly that bit and leaves the rest alone, which is both the correct implementation and the concept the game is teaching. Everything else is derived: value.toString(2).padStart(BITS, '0') for binary, toString(16) for hex, and a running 128 + 32 + 4 = 164 breakdown assembled from whichever place values are on. There's no separate array of bit states to fall out of sync, which is why the display can never lie. The streak record is stored in localStorage with both the read and the write wrapped in try/catch — storage access throws outright in sandboxed and opaque-origin iframes, so an unguarded getItem is a blank component in exactly the embedded context this snippet is designed for.

Best for: CS fundamentals, bitmask and permission-flag explainers, and anywhere you need someone to internalise place value rather than memorise a table. Tip: that localStorage guard is worth copying into any snippet you plan to embed. It's a few lines and it's the difference between degrading gracefully and not rendering at all.

Grab the code: Binary Bit Flip Game

8. Logic Gate Puzzle Game

Two gate slots, three input switches, and a live eight-row truth table. Pick AND, OR, XOR, NAND or NOR for each slot until every row matches the target.

How it works: the circuit shape is fixed at gate1(gate0(A, B), C), and each gate is a one-line function over JavaScript's bitwise operators — a & b, a | b, a ^ b, with NAND and NOR as inverted forms. The eight input rows are generated by bit-shifting the loop counter ((i >> 2) & 1, (i >> 1) & 1, i & 1), which is the same idea the game is about. The design decision that makes it work is that the win condition is the truth table, not the switches: every row is evaluated on every render, and you win when all eight match — so flipping switches is a way to understand your circuit, never a way to grind out a solve. The starting pair is ['OR', 'OR'] specifically because it solves none of the five levels, so no puzzle opens already complete.

Best for: digital logic courses, bitwise-operator explainers, and interview prep for anyone who has to reason about combined boolean conditions. Tip: the parity level — output on an odd number of inputs — is the one that teaches XOR properly. It's the level where guessing stops working and you have to read the table.

Grab the code: Logic Gate Puzzle Game

9. Sorting Swap Puzzle Game

Eight scrambled bars, any two swappable. Sort them — and find out whether you matched the provable minimum number of swaps, with a live inversion count as you go.

How it works: the par score is computed, not guessed. minSwaps() decomposes the permutation into cycles — walking each unvisited position to where its value belongs until it returns to the start — and sums size - 1 per cycle, because a cycle of length k takes exactly k − 1 swaps. That's a genuine result, so "you took 9, the minimum was 6" is a fact rather than an author's estimate. Alongside it, an inversion count (pairs in the wrong relative order) updates after every move, and it's shown because it's the other half of the lesson: one adjacent swap removes exactly one inversion, which is precisely why bubble sort costs what it costs, while an arbitrary swap can remove many. The auto-solver demonstrates the optimal strategy directly — repeatedly send the first misplaced value straight to its destination, which permanently places at least one bar per swap and therefore hits the minimum.

Best for: algorithms teaching, DSA interview prep, and making "minimum number of swaps" concrete instead of a whiteboard claim. Tip: play a round, note your count, then hit Solve on the same arrangement. Watching the optimal path next to the one you just took is where the cycle-decomposition idea lands.

Grab the code: Sorting Swap Puzzle Game

10. Robot Loop Programmer Game

Build a program from Forward, Left and Right blocks, give each a repeat count, and run it. Five maze levels, each with a par block count that only loops will hit.

How it works: a program is an array of { cmd, times } blocks — click a block to cycle its repeat count 1→9, right-click to delete it. Running the program calls expand(), which flattens those blocks into single steps, each tagged with the block it came from, which is what lets the UI highlight the currently executing block while the robot moves. Direction is an index into a four-entry DIRS array, so turning is modular arithmetic — (dir + 1) % 4 right, (dir + 3) % 4 left — rather than a switch over compass names. Each step returns { ok, why }, so hitting a wall or driving off the edge stops the run, marks the guilty block red, and says which one failed. A MAX_STEPS ceiling of 60 rejects a program before it runs, which is the honest way to handle an unbounded loop in a UI: refuse it up front rather than letting a setInterval spin. Par is set so the spiral and zig-zag levels are only reachable under budget with repeat counts — the game teaches loops by making the naive solution too expensive.

Best for: teaching loops and sequencing to beginners or kids, CS-outreach pages, and anyone who has tried to explain "iteration" with a for loop and lost the room. Tip: the par comparison is the entire pedagogy. Solving under par requires noticing repetition and collapsing it, which is the actual mental move behind every loop anyone ever writes.

Grab the code: Robot Loop Programmer Game

How to drop these into your project

  1. Open any snippet and hit View / Edit Code to see the HTML, CSS, and JS in separate tabs — every one of these is pure vanilla JavaScript with zero dependencies and no CDN scripts required.
  2. Paste the HTML into your markup, the CSS into your stylesheet, and the JS before your closing </body> tag, or use the one-click export to React, Vue, Angular, or Tailwind right from the snippet page.
  3. Every game keeps its content in a LEVELS, BUGS, QUESTIONS or TASKS array at the top of the file, deliberately separated from the engine below it. Replacing that array with your own material — your class names, your team's recurring bugs, your CLI's commands — is the intended way to adapt these, and it needs no changes to the logic.
  4. Several of these run timers: the quiz's countdown, the robot's step interval, the sorting auto-solver. If you wrap one in a React or Vue component, clear those in a cleanup function on unmount — each of those three already calls clearInterval on every path that ends a run, so you're extending an existing pattern rather than inventing one.
  5. Copy the defensive bits, not just the fun ones: the try/catch around new RegExp() and querySelectorAll() for user-typed input, the guarded localStorage access for anything that might render in a sandboxed iframe, and the step ceiling that refuses a runaway program before it starts.

Final thought

The thing these ten share isn't the game format — it's that each one grades an outcome and then explains the gap. Set equality instead of string matching, pixel positions instead of property names, a computed minimum instead of an asserted one, an accept-list of regexes instead of one correct command. That design costs a little more to build and it's the reason a learner can be wrong in an interesting way instead of just wrong, which is the only kind of wrong anybody learns from.

Play any of them right here, tweak the levels, and export to your framework of choice in one click. Browse the full collection at FWD Tools UI Snippets — it's free and runs entirely in your browser.

About the author

Puneet Sharma
Puneet Sharma is a freelance web developer and the creator of FWD Tools and WebDevPuneet. Follow him on X/Twitter

Post a Comment