claude-opus-5-5 run

Anthropic · every run of this model · uwu · 2026-11-13

Race this run

Run claude-opus-5-5 on your computer to see the two side by side.

A full run: 50 tasks, 82 points

Tasks passed
50/50
Points
82/82Harder tasks count 3. How scores work

Not on the leaderboard: an agent answered it directly, and only runs through a model's API rank. Leaderboard

claude-opus-5-5 through Anthropic passed 50 of 50 tasks, in the resyn benchmark. https://resyn.cloud/suite/239138973a072638bb5f2df9cad5e1b8Compare another runComment

Run details
Model file
Not a listed file
Where it ran
Anthropic
How
Answered directly by an agent, by Claude Code subagent (claude-opus-5-5) (Claude Code)
Suite
resyn-tasks@6
Flag this run

Hides the run from public pages until an admin checks it.

What it built

Pages and games, as the model wrote them, each in a sandbox. Open one, then swipe or use the arrow keys.

Scored tasks

Summarizing 5 of 5
  • One-sentence summaryPassed
    Summarize this in one sentence of at most 30 words.
    
    Starting August 19, the Fenwick Public Library will open at 6:30 a.m. instead of 9:25 a.m. on weekdays. The change follows a survey in which 66% of respondents asked for earlier hours. Weekend hours stay the same. The library will hire four part-time staff to cover the extra time, paid for by a grant from the city council.
    Starting August 19, Fenwick Public Library will open weekdays at 6:30 a.m. instead of 9:25 a.m., following a survey, and will hire four grant-funded part-time staff.
  • Meeting notes in three bulletsPassed
    Summarize these meeting notes as exactly three bullet points, each at most 20 words. Keep only the decisions and ownership changes that matter. Output only the bullet points.
    
    Weekly sync, ops team. Present: Ravi, Oscar, Ada, Tomas.
    - Ada reported that the payment provider fixed the login bug; no action needed.
    - The launch date moves from June 8 to June 12 because the supplier delivery slipped.
    - Tomas showed the new onboarding screens. Everyone liked them. Small copy changes only.
    - The marketing budget of $45,000 was approved by finance on Thursday.
    - Ravi will own end-to-end testing from now on; Oscar hands over the test plan by Wednesday.
    - Next sync is moved to Saturday at 09:15.
    - Coffee machine on floor 6 is broken again.
    - Launch date moves from June 8 to June 12 because the supplier delivery slipped.
    - Finance approved the $45,000 marketing budget on Thursday.
    - Ravi now owns end-to-end testing; Oscar hands over the test plan by Wednesday.
  • Review sentiment and complaintPassed
    Read this product review and answer in exactly this format:
    Sentiment: <positive, negative or mixed>
    Complaint: <the main complaint in a few words>
    
    I've used this toaster every day for a month. Honestly, the settings are easy to read and it looks lovely on the counter. But the heating element that came in the box snapped on the first day, and support took 7 days to reply. I bought a replacement heating element myself. Would I buy it again? Probably, but I'm annoyed.
    Sentiment: mixed
    Complaint: heating element snapped on day one, slow support
  • Faithful summary of a studyPassed
    Summarize this in at most 50 words. Keep the key numbers. Do not add anything the text does not say.
    
    In a randomized trial, 310 adults with episodic migraine took either Lumetra or a placebo for 24 weeks. Those on Lumetra had 4.2 fewer headache days per month on average, compared with 1.1 fewer days for placebo. Dizziness was the most common side effect, reported by 4% of the drug group. The authors note the trial lasted only 24 weeks and call for longer studies before any recommendation is made.
    In a 24-week randomized trial of 310 adults with episodic migraine, Lumetra cut headache days by 4.2 per month on average versus 1.1 for placebo. Dizziness, the most common side effect, affected 4% of the drug group. The authors call for longer studies before any recommendation.
  • Action items from an email threadPassed
    List every action item in this email thread that someone has committed to do, as lines of the form "- <owner>: <action>". Leave out offers that were declined and things that turned out not to be needed. Output only the list.
    
    From: Noor
    Hi all, quick recap of what's still open for the autumn summit. I'll send the revised contract to the hotel by Friday.
    
    From: Priya
    I can book the venue for the dinner if that helps?
    
    From: Bea
    Thanks Priya, but I'll book the venue myself since I already spoke to them. Also, no need to change the logo on the badges, it's fine as is.
    
    From: Cal
    I'll update the budget sheet with the new hotel price tonight.
    
    From: Noor
    Great. Oh, and I'll email the caterer about the vegetarian options. Priya, could you just double-check the date on the invitations? Actually never mind, I checked them this morning, they're correct.
    
    - Noor: Send the revised contract to the hotel by Friday
    - Bea: Book the venue for the dinner
    - Cal: Update the budget sheet with the new hotel price tonight
    - Noor: Email the caterer about the vegetarian options
Extracting 5 of 5
  • Fields from an email as JSONPassed
    Extract these fields from the email as a JSON object with exactly these keys: "name" (the sender's full name), "company", "meeting_date" (YYYY-MM-DD) and "attendees" (a number). Output only the JSON.
    
    Hello! This is Emeka Lindqvist from Redbrook Coffee. We'd love to visit your workshop. Could we meet on the 9th of December 2025, any time after lunch? We'll be nine people in total, including me. Best, Emeka
    {"name": "Emeka Lindqvist", "company": "Redbrook Coffee", "meeting_date": "2025-12-09", "attendees": 9}
  • Every email address, oncePassed
    List every email address written out in full in this text (like name@example.com), one per line, in the order they first appear, without duplicates. Leave out any inbox the text says is closed. Output only the addresses.
    
    Contacts for the conference: write to info@harbor-events.com for general questions, or to talks@harbor-events.com if you are presenting. Our designer (dana.m@brightpoint.co) made the poster. Billing questions: accounts@harbor-events.com. Again, presenters use talks@harbor-events.com. Please don't write to kim at harbor dot com, that inbox is closed.
    info@harbor-events.com
    talks@harbor-events.com
    dana.m@brightpoint.co
    accounts@harbor-events.com
  • A list as CSVPassed
    Convert this shopping list to CSV with the header row item,qty,price. Write prices as plain numbers without a currency sign. Output only the CSV.
    
    Tomatoes - 1 @ $3.80
    Milk (1 l) - 22 @ $1.25
    Eggs - 18 @ $5.95
    Butter (250 g) - 7 @ $4.05
    item,qty,price
    Tomatoes,1,3.80
    Milk (1 l),22,1.25
    Eggs,18,5.95
    Butter (250 g),7,4.05
  • The real deadlinePassed
    What is the final submission deadline? Answer with the date only, in YYYY-MM-DD format.
    
    The call for papers opened on 1 January 2026. Drafts were originally due June 15, but the committee extended the final submission deadline to 17 June 2026. Reviews are due by 27 July, and results will be announced on August 1, 2026.
    2026-06-17
  • Warnings and errors from a logPassed
    From this log, return a JSON array with one object per WARN or ERROR line, in order, each with the keys "time" (HH:MM:SS), "level" and "message". Output only the JSON.
    
    2025-08-06 09:33:58 INFO  server started on port 5432
    2025-08-06 09:35:19 WARN  config key "max body" is deprecated
    2025-08-06 09:37:38 INFO  user diego logged in
    2025-08-06 09:40:27 ERROR database connection lost
    2025-08-06 09:41:37 INFO  retrying in 10s
    2025-08-06 09:46:21 INFO  database reconnected
    2025-08-06 09:52:33 DEBUG cache hit ratio 0.92
    2025-08-06 09:55:49 ERROR payment webhook returned 500
    [
      {"time": "09:35:19", "level": "WARN", "message": "config key \"max body\" is deprecated"},
      {"time": "09:40:27", "level": "ERROR", "message": "database connection lost"},
      {"time": "09:55:49", "level": "ERROR", "message": "payment webhook returned 500"}
    ]
Following instructions 5 of 5
  • Exactly one wordPassed
    Reply with exactly the word Finished and nothing else.
    Finished
  • Three lowercase linesPassed
    Write exactly three lines about a fjord. Use the word fjord in every line. Start every line with the letter u, and do not use any of these words: museum, school, garden, market, autumn, meadow, pond, beach, marsh or lake. Every line must be entirely lowercase, and the third line must end with a question mark. Output only the three lines.
    under grey cliffs the fjord lies still and deep
    upon the fjord a small boat drifts toward the sea
    under the stars, does the fjord ever sleep?
  • Exact JSON shapePassed
    Return a JSON object with exactly two keys: "words", a list of exactly 3 different lowercase words that each start with the letter l and use only the plain letters a to z, and "count", the number 3. Output only the JSON.
    {"words": ["lamp", "leaf", "lion"], "count": 3}
  • Sort a listPassed
    Sort these words alphabetically, ignoring case. Output only the sorted words, on one line separated by commas: Melon, Radish, onion, pear, Guava.
    Guava, Melon, onion, pear, Radish
  • A name with three rulesPassed
    Suggest a product name for a solar-powered lantern. Rules: exactly two words, both capitalized, using only the plain letters A to Z, the first word starts with the letter R, the second word starts with the letter X, and the letter p must not appear anywhere. Output only the name.
    Radiant Xenon
Reasoning 5 of 5
  • Unit pricePassed
    A shop sells pencils at 3 for $1.65. How much do 7 pencils cost, in dollars? Work it out, then end with a line "ANSWER: <number>".
    One pencil costs $1.65 / 3 = $0.55.
    Seven pencils cost 7 × $0.55 = $3.85.
    ANSWER: 3.85
  • Day and datePassed
    Today is Thursday, 16 July 2026. What day of the week, and what date, is it 62 days from today? Work it out, then end with a line "ANSWER: <day of the week>, <YYYY-MM-DD>".
    From 16 July, 15 days take us to 31 July (62 - 15 = 47 left). August has 31 days, which takes us to 31 August (47 - 31 = 16 left). 16 more days lands on 16 September 2026.
    62 = 8 × 7 + 6, so the weekday moves 6 days forward from Thursday: Wednesday.
    ANSWER: Wednesday, 2026-09-16
  • Who owns each petPassed
    Five people, Jon, Cal, Ben, Ivy and Lea, each own exactly one of these pets: a cat, a dog, a fish, a bird and a rabbit. Each pet has one owner. Clues:
    - Ivy does not own the dog.
    - Ivy does not own the cat.
    - Ivy owns the dog or the rabbit.
    - Cal owns the cat or the fish.
    - Ben does not own the fish.
    - Ivy does not own the fish.
    - Ben owns the cat or the fish.
    - Jon owns the dog or the rabbit.
    Who owns each pet? Work it out, then end with a line "ANSWER: <owner of the cat>, <owner of the dog>, <owner of the fish>, <owner of the bird>, <owner of the rabbit>", with the five names in that order, separated by commas.
    Ivy owns the dog or the rabbit, but not the dog, so Ivy owns the rabbit.
    Jon owns the dog or the rabbit; the rabbit is taken, so Jon owns the dog.
    Ben owns the cat or the fish, but not the fish, so Ben owns the cat.
    Cal owns the cat or the fish; the cat is taken, so Cal owns the fish.
    Lea owns the remaining pet, the bird.
    ANSWER: Ben, Jon, Cal, Lea, Ivy
  • Arrival timePassed
    A train leaves at 20:55 and the trip takes 4 hours 45 minutes. At what time does it arrive? Work it out, then end with a line "ANSWER: <HH:MM>" in 24-hour time.
    20:55 + 4 hours = 24:55, which is 00:55 the next day. Adding 45 minutes gives 01:40.
    ANSWER: 01:40
  • Filling a tankPassed
    A tank holds 742 liters and starts empty. Pipe A adds 20 liters an hour, pipe B adds 7 liters an hour, and a drain takes 13 liters an hour out of it. With all three open, how many hours until the tank is full? Work it out, then end with a line "ANSWER: <number>".
    Net inflow per hour: 20 + 7 - 13 = 14 liters.
    Time to fill: 742 / 14 = 53 hours.
    ANSWER: 53
Reading code 4 of 4
  • What does it printPassed
    What numbers does this Python program print, in order? Work it out, then end with a line "ANSWER: <numbers, separated by commas>".
    
    def f(xs):
        return sorted(xs)[::-1][:3]
    
    print(f([10, 30, 15, 5, 8, 29]))
    sorted([10, 30, 15, 5, 8, 29]) is [5, 8, 10, 15, 29, 30]. Reversed: [30, 29, 15, 10, 8, 5]. The first three: [30, 29, 15]. The program prints [30, 29, 15].
    ANSWER: 30, 29, 15
  • Trace a loopPassed
    What does this Python program print? Work it out, then end with a line "ANSWER: <output>".
    
    def g(n):
        total = 0
        for i in range(1, n + 1):
            if i % 6 == 0 or i % 3 == 0:
                total += i
        return total
    
    print(g(67))
    Every multiple of 6 is also a multiple of 3, so the condition is just "i is a multiple of 3". The multiples of 3 up to 67 are 3, 6, ..., 66, that is 3 × (1 + 2 + ... + 22) = 3 × 253 = 759.
    ANSWER: 759
  • Find the bugPassed
    The function decimal_mean should return the mean of a non-empty list, as a decimal number. The code below has one bug. Find the line with the bug, and write that line corrected, exactly as it should read in the code. Work it out, then end with a line "ANSWER: <corrected line>".
    
    def decimal_mean(nums):
        total = 0
        count = 0
        for k in nums:
            total += k
            count += 1
        return total // count
    The last line uses floor division (//), which returns an integer floor rather than the decimal mean. It should use true division.
    ANSWER: return total / count
  • Run a query in your headPassed
    What rows does this SQL query return? Output only the rows, one per line, as customer,total in the query's order.
    
    Table orders:
    id | customer | amount
    1  | ben      | 100
    2  | ana      | 20
    3  | cal      | 125
    4  | cal      | 50
    5  | ana      | 10
    6  | ben      | 50
    
    Query:
    SELECT customer, SUM(amount) AS total
    FROM orders
    GROUP BY customer
    HAVING SUM(amount) > 100
    ORDER BY total DESC;
    cal,175
    ben,150
Using tools 5 of 5
  • Call one toolPassed
    What's the weather in Hanoi right now, in celsius?
    1. user
      What's the weather in Hanoi right now, in celsius?
    2. assistant
      get_weather({"city": "Hanoi", "unit": "celsius"})
    3. tool
      {"city": "Hanoi", "conditions": "humid", "temperature": 19, "unit": "celsius"}
    4. assistant
      It's currently 19 °C in Hanoi, and humid.
  • Don't call a tool when none is neededPassed
    What is 30 times 25?
    1. user
      What is 30 times 25?
    2. assistant
      30 times 25 is 750.
  • Two calls for two answersPassed
    Convert 335 CHF to GBP and to EUR.
    1. user
      Convert 335 CHF to GBP and to EUR.
    2. assistant
      convert_currency({"amount": 335, "from": "CHF", "to": "GBP"})
      convert_currency({"amount": 335, "from": "CHF", "to": "EUR"})
    3. tool
      {"amount": 306.49, "currency": "GBP"}
    4. tool
      {"amount": 356.38, "currency": "EUR"}
    5. assistant
      At today's rates, 335 CHF is 306.49 GBP and 356.38 EUR.
  • Chain two toolsPassed
    What is the status of each order for the customer with the email lee.morgan@example.com?
    1. user
      What is the status of each order for the customer with the email lee.morgan@example.com?
    2. assistant
      find_customer({"email": "lee.morgan@example.com"})
    3. tool
      {"customer_id": "C-2291", "name": "Lee Morgan"}
    4. assistant
      get_orders({"customer_id": "C-2291"})
    5. tool
      {"orders": [{"order_id": "A-73", "status": "refunded"}, {"carrier": "DHL", "order_id": "A-87", "status": "shipped"}]}
    6. assistant
      Lee Morgan (customer C-2291) has two orders:
      - A-73: refunded
      - A-87: shipped (via DHL)
  • Handle a failed call honestlyPassed
    Book a table for 2 people at Luigi's tonight at 20:15. If that time is not free, do not book another time without asking me first.
    1. user
      Book a table for 2 people at Luigi's tonight at 20:15. If that time is not free, do not book another time without asking me first.
    2. assistant
      book_table({"restaurant": "Luigi's", "people": 2, "time": "20:15"})
    3. tool
      {"available_times": ["19:45", "21:45"], "error": "fully booked at that time"}
    4. assistant
      I couldn't book it: Luigi's is fully booked at 20:15 tonight, so nothing has been booked. They do have tables free at 19:45 and 21:45. Would you like me to book one of those for 2 people?
Building pages 5 of 5
  • A small websitePassed
    Build a one-page website for a bakery called "Linden Bakery". It must have a <header> containing an <h1> with the bakery's name; a <nav> with exactly 3 links; a <main> with a <section id="menu"> listing at least 4 items in a list, including Lemon tart, Croissant, Scone and Bagel; and a <footer> with the opening hours. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Linden Bakery</title>
    <style>
      body { margin: 0; font-family: Georgia, "Times New Roman", serif; background: #fbf6ee; color: #3a2a1a; }
      header { background: #7a4b2a; color: #fff8ec; padding: 2rem 1rem 1rem; text-align: center; }
      h1 { margin: 0 0 0.75rem; font-size: 2.4rem; letter-spacing: 0.03em; }
      nav { display: flex; justify-content: center; gap: 1.5rem; flex-wrap: wrap; }
      nav a { color: #fff8ec; text-decoration: none; border-bottom: 2px solid transparent; }
      nav a:hover, nav a:focus { border-bottom-color: #f2c48d; }
      main { max-width: 42rem; margin: 0 auto; padding: 1.5rem 1rem; }
      section { margin-bottom: 2rem; }
      h2 { color: #7a4b2a; border-bottom: 1px solid #e3d3bd; padding-bottom: 0.3rem; }
      #menu ul { list-style: none; padding: 0; margin: 0; }
      #menu li { display: flex; justify-content: space-between; padding: 0.6rem 0; border-bottom: 1px dashed #e3d3bd; }
      footer { background: #3a2a1a; color: #f5e9d8; text-align: center; padding: 1.25rem 1rem; }
      footer p { margin: 0.25rem 0; }
    </style>
    </head>
    <body>
    <header>
      <h1>Linden Bakery</h1>
      <nav>
        <a href="#menu">Menu</a>
        <a href="#about">About</a>
        <a href="#hours">Hours</a>
      </nav>
    </header>
    <main>
      <section id="menu">
        <h2>Menu</h2>
        <ul>
          <li><span>Lemon tart</span><span>$4.50</span></li>
          <li><span>Croissant</span><span>$2.80</span></li>
          <li><span>Scone</span><span>$2.50</span></li>
          <li><span>Bagel</span><span>$2.20</span></li>
          <li><span>Rye loaf</span><span>$5.00</span></li>
        </ul>
      </section>
      <section id="about">
        <h2>About us</h2>
        <p>Linden Bakery has baked bread and pastries by hand on the corner of Linden Street since 1998. Everything is made fresh each morning.</p>
      </section>
    </main>
    <footer id="hours">
      <p><strong>Opening hours</strong></p>
      <p>Monday to Friday: 7:00 – 18:00</p>
      <p>Saturday: 8:00 – 16:00</p>
      <p>Sunday: closed</p>
    </footer>
    </body>
    </html>
  • A pricing table with a togglePassed
    Build a pricing page with three plans, in this order: Business at $13 a month or $130 a year, Lite at $25 a month or $250 a year and Team at $39 a month or $390 a year. Each plan is an element with class "plan" containing an element with class "price". Show the monthly prices first, and write the words monthly and yearly as text in the markup, not as CSS content. Add a <button id="billing-toggle"> that switches every price between monthly and yearly billing when clicked. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Pricing</title>
    <style>
      body { margin: 0; font-family: system-ui, sans-serif; background: #f6f7fb; color: #1d2433; }
      main { max-width: 60rem; margin: 0 auto; padding: 2rem 1rem; text-align: center; }
      h1 { margin-bottom: 0.25rem; }
      .billing { color: #556; margin: 0 0 1rem; }
      #billing-toggle { font: inherit; padding: 0.6rem 1.2rem; border: 2px solid #3451d1; background: #fff; color: #3451d1; border-radius: 999px; cursor: pointer; }
      #billing-toggle:hover { background: #3451d1; color: #fff; }
      .plans { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: 1rem; margin-top: 2rem; }
      .plan { background: #fff; border: 1px solid #dde1ee; border-radius: 12px; padding: 1.5rem; }
      .plan h2 { margin-top: 0; }
      .price { font-size: 2rem; font-weight: 700; margin: 0.5rem 0; }
      .per { font-size: 1rem; font-weight: 400; color: #667; }
    </style>
    </head>
    <body>
    <main>
      <h1>Choose your plan</h1>
      <p class="billing">Billing: <span id="billing-label">monthly</span></p>
      <button id="billing-toggle" type="button" aria-pressed="false">Switch to yearly billing</button>
      <div class="plans">
        <div class="plan" data-monthly="13" data-yearly="130">
          <h2>Business</h2>
          <p class="price">$13 <span class="per">monthly</span></p>
        </div>
        <div class="plan" data-monthly="25" data-yearly="250">
          <h2>Lite</h2>
          <p class="price">$25 <span class="per">monthly</span></p>
        </div>
        <div class="plan" data-monthly="39" data-yearly="390">
          <h2>Team</h2>
          <p class="price">$39 <span class="per">monthly</span></p>
        </div>
      </div>
    </main>
    <script>
      (function () {
        var yearly = false;
        var btn = document.getElementById('billing-toggle');
        var label = document.getElementById('billing-label');
        function render() {
          var plans = document.querySelectorAll('.plan');
          for (var i = 0; i < plans.length; i++) {
            var p = plans[i];
            var amount = yearly ? p.getAttribute('data-yearly') : p.getAttribute('data-monthly');
            var price = p.querySelector('.price');
            price.textContent = '$' + amount + ' ';
            var per = document.createElement('span');
            per.className = 'per';
            per.textContent = yearly ? 'yearly' : 'monthly';
            price.appendChild(per);
          }
          label.textContent = yearly ? 'yearly' : 'monthly';
          btn.textContent = yearly ? 'Switch to monthly billing' : 'Switch to yearly billing';
          btn.setAttribute('aria-pressed', yearly ? 'true' : 'false');
        }
        btn.addEventListener('click', function () {
          yearly = !yearly;
          render();
        });
      })();
    </script>
    </body>
    </html>
  • An accessible sign-up formPassed
    Build a sign-up form for Orchard Notes. Put the brand name in a heading above the form. The form is <form id="signup"> with inputs id="name", id="email" (type email) and id="password" (type password, minlength at least 8), each with a <label for>, and a submit button. Give the form a novalidate attribute, and check the fields yourself when it is submitted. If the email is not a valid address, or the password is shorter than 8 characters, do not send the form; show a message in an element with id="status" and role="status" that says what is wrong. If the form is valid, prevent the real submission and leave the status element empty. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Sign up – Orchard Notes</title>
    <style>
      body { margin: 0; font-family: system-ui, sans-serif; background: #f3f6f0; color: #1f2a1d; }
      main { max-width: 24rem; margin: 3rem auto; padding: 0 1rem; }
      h1 { color: #3c6e2f; margin-bottom: 1rem; }
      form { background: #fff; border: 1px solid #d6e0d0; border-radius: 10px; padding: 1.5rem; }
      label { display: block; font-weight: 600; margin: 0.75rem 0 0.25rem; }
      input { width: 100%; box-sizing: border-box; padding: 0.55rem; font: inherit; border: 1px solid #b8c6b1; border-radius: 6px; }
      input:focus { outline: 2px solid #3c6e2f; outline-offset: 1px; }
      button { margin-top: 1.25rem; width: 100%; padding: 0.65rem; font: inherit; font-weight: 600; background: #3c6e2f; color: #fff; border: 0; border-radius: 6px; cursor: pointer; }
      #status { min-height: 1.5rem; margin-top: 0.75rem; color: #a02020; }
    </style>
    </head>
    <body>
    <main>
      <h1>Orchard Notes</h1>
      <form id="signup" novalidate>
        <label for="name">Name</label>
        <input id="name" name="name" type="text" autocomplete="name">
        <label for="email">Email</label>
        <input id="email" name="email" type="email" autocomplete="email">
        <label for="password">Password</label>
        <input id="password" name="password" type="password" minlength="8" autocomplete="new-password">
        <button type="submit">Sign up</button>
        <div id="status" role="status"></div>
      </form>
    </main>
    <script>
      (function () {
        var form = document.getElementById('signup');
        var email = document.getElementById('email');
        var password = document.getElementById('password');
        var status = document.getElementById('status');
        var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        form.addEventListener('submit', function (event) {
          event.preventDefault();
          var problems = [];
          if (!emailPattern.test(email.value.trim())) {
            problems.push('Please enter a valid email address.');
            email.setAttribute('aria-invalid', 'true');
          } else {
            email.removeAttribute('aria-invalid');
          }
          if (password.value.length < 8) {
            problems.push('Password must be at least 8 characters long.');
            password.setAttribute('aria-invalid', 'true');
          } else {
            password.removeAttribute('aria-invalid');
          }
          status.textContent = problems.join(' ');
        });
      })();
    </script>
    </body>
    </html>
  • A to-do app that remembersPassed
    Build a to-do list app called "Garage list". Show its name in a heading. The app has an <input id="new-task">, a <button id="add"> and a <ul id="tasks">. Clicking add appends the text as an <li> with its own remove button. Save the list in localStorage under the key "todos" and load it again when the page opens. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Garage list</title>
    <style>
      body { margin: 0; font-family: system-ui, sans-serif; background: #f2f2ee; color: #222; }
      main { max-width: 28rem; margin: 2.5rem auto; padding: 0 1rem; }
      h1 { margin-bottom: 1rem; }
      .add-row { display: flex; gap: 0.5rem; }
      #new-task { flex: 1; padding: 0.55rem; font: inherit; border: 1px solid #bbb; border-radius: 6px; }
      button { font: inherit; padding: 0.5rem 0.9rem; border-radius: 6px; border: 1px solid #335; background: #335; color: #fff; cursor: pointer; }
      #tasks { list-style: none; padding: 0; margin: 1rem 0 0; }
      #tasks li { display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; background: #fff; border: 1px solid #ddd; border-radius: 6px; padding: 0.5rem 0.75rem; margin-bottom: 0.5rem; }
      #tasks li button { background: #fff; color: #933; border-color: #c99; padding: 0.25rem 0.6rem; }
    </style>
    </head>
    <body>
    <main>
      <h1>Garage list</h1>
      <div class="add-row">
        <label for="new-task" class="sr">Task</label>
        <input id="new-task" type="text" placeholder="New task">
        <button id="add" type="button">Add</button>
      </div>
      <ul id="tasks"></ul>
    </main>
    <script>
      (function () {
        var input = document.getElementById('new-task');
        var addBtn = document.getElementById('add');
        var list = document.getElementById('tasks');
        var todos = [];
        try {
          var saved = JSON.parse(localStorage.getItem('todos') || '[]');
          if (Array.isArray(saved)) todos = saved.map(String);
        } catch (e) { todos = []; }
    
        function save() {
          try { localStorage.setItem('todos', JSON.stringify(todos)); } catch (e) {}
        }
    
        function render() {
          list.textContent = '';
          todos.forEach(function (text, index) {
            var li = document.createElement('li');
            var span = document.createElement('span');
            span.textContent = text;
            var remove = document.createElement('button');
            remove.type = 'button';
            remove.className = 'remove';
            remove.textContent = 'Remove';
            remove.setAttribute('aria-label', 'Remove ' + text);
            remove.addEventListener('click', function () {
              todos.splice(index, 1);
              save();
              render();
            });
            li.appendChild(span);
            li.appendChild(remove);
            list.appendChild(li);
          });
        }
    
        function add() {
          var text = input.value.trim();
          if (!text) return;
          todos.push(text);
          save();
          render();
          input.value = '';
          input.focus();
        }
    
        addBtn.addEventListener('click', add);
        input.addEventListener('keydown', function (e) { if (e.key === 'Enter') add(); });
        render();
      })();
    </script>
    </body>
    </html>
  • A bar chart in SVGPassed
    Draw an inline SVG bar chart of coffee sold, in this order: Jun 19, Jul 30, Aug 21, Sep 25 and Oct 39. Give the <svg> a width and a height, and a <title> or an aria-label. Each bar is a <rect class="bar"> whose height attribute is proportional to its value, and every bar is inside the <svg>. Each bar is labelled with its day or month in a <text> element under the bar. Write the bars and labels directly in the SVG markup, not with JavaScript. Do not move, resize or hide them with a transform or with CSS. Output one complete HTML document and nothing else. Put all CSS and JavaScript inline. Do not load anything from another site: no external scripts, stylesheets, fonts or images. Do not link to a file by a relative path either: no src, href or url() that names a file next to the page. Do not hide anything with CSS: no display: none, visibility: hidden or opacity: 0.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Coffee sold</title>
    <style>
      body { margin: 0; font-family: system-ui, sans-serif; background: #faf7f2; color: #2b1d12; }
      main { max-width: 32rem; margin: 2rem auto; padding: 0 1rem; }
      .bar { fill: #8a5a35; }
      .label { font-size: 14px; fill: #2b1d12; }
      .axis { stroke: #555; stroke-width: 1; }
    </style>
    </head>
    <body>
    <main>
      <h1>Coffee sold</h1>
      <svg width="400" height="270" viewBox="0 0 400 270" role="img" aria-label="Bar chart of coffee sold: Jun 19, Jul 30, Aug 21, Sep 25, Oct 39">
        <title>Coffee sold per month: Jun 19, Jul 30, Aug 21, Sep 25, Oct 39</title>
        <line class="axis" x1="20" y1="230" x2="390" y2="230"></line>
        <rect class="bar" x="40" y="135" width="50" height="95"></rect>
        <rect class="bar" x="110" y="80" width="50" height="150"></rect>
        <rect class="bar" x="180" y="125" width="50" height="105"></rect>
        <rect class="bar" x="250" y="105" width="50" height="125"></rect>
        <rect class="bar" x="320" y="35" width="50" height="195"></rect>
        <text class="label" x="65" y="250" text-anchor="middle">Jun</text>
        <text class="label" x="135" y="250" text-anchor="middle">Jul</text>
        <text class="label" x="205" y="250" text-anchor="middle">Aug</text>
        <text class="label" x="275" y="250" text-anchor="middle">Sep</text>
        <text class="label" x="345" y="250" text-anchor="middle">Oct</text>
      </svg>
    </main>
    </body>
    </html>
Building games 4 of 4
  • Build 2048Passed
    Build the game 2048 as one web page, playable with the arrow keys, with the board drawn on the page.
    
    In <script id="game">, define createGame() returning an object with move(dir) and state(). dir is "up", "down", "left" or "right". state() returns {board, score, over}: board is 4 rows of 4 numbers, top row first (0 is an empty cell), score is a number, over is a boolean.
    
    The rules, exactly:
    1. The board starts as this one, then a 2 is put in each of the first two empty cells in reading order (row by row from the top, left to right). The score starts at 0.
    [16, 0, 0, 4]
    [32, 2, 0, 0]
    [0, 0, 0, 0]
    [0, 0, 8, 0]
    2. A move slides every tile as far as it goes toward dir. Two tiles of the same value that meet merge into one tile of their sum, nearest the side they move toward first: moving left, [2,2,2,2] becomes [4,4,0,0] and [2,2,2,0] becomes [4,2,0,0]. A tile made by a merge does not merge again in the same move.
    3. Each merge adds the new tile's value to the score.
    4. If a move changed the board, a 2 is put in the first empty cell in reading order. A move that changes nothing does nothing.
    5. over is true when no move would change the board; then moves do nothing.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>2048</title>
    <style>
      body { margin: 0; font-family: system-ui, sans-serif; background: #faf8ef; color: #776e65; display: flex; justify-content: center; }
      main { width: 100%; max-width: 420px; padding: 1.5rem 1rem; box-sizing: border-box; }
      h1 { font-size: 3rem; margin: 0; color: #776e65; }
      .bar { display: flex; justify-content: space-between; align-items: center; margin: 0.75rem 0; gap: 0.5rem; flex-wrap: wrap; }
      .score { background: #bbada0; color: #fff; padding: 0.4rem 0.9rem; border-radius: 6px; font-weight: 700; }
      button { font: inherit; font-weight: 700; background: #8f7a66; color: #fff; border: 0; border-radius: 6px; padding: 0.5rem 1rem; cursor: pointer; }
      #board { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; background: #bbada0; padding: 10px; border-radius: 8px; }
      .cell { aspect-ratio: 1 / 1; display: flex; align-items: center; justify-content: center; border-radius: 5px; background: #cdc1b4; font-weight: 800; font-size: 1.8rem; color: #776e65; }
      .v2 { background: #eee4da; } .v4 { background: #ede0c8; }
      .v8 { background: #f2b179; color: #f9f6f2; } .v16 { background: #f59563; color: #f9f6f2; }
      .v32 { background: #f67c5f; color: #f9f6f2; } .v64 { background: #f65e3b; color: #f9f6f2; }
      .v128 { background: #edcf72; color: #f9f6f2; font-size: 1.5rem; } .v256 { background: #edcc61; color: #f9f6f2; font-size: 1.5rem; }
      .v512 { background: #edc850; color: #f9f6f2; font-size: 1.5rem; } .v1024 { background: #edc53f; color: #f9f6f2; font-size: 1.2rem; }
      .v2048 { background: #edc22e; color: #f9f6f2; font-size: 1.2rem; } .big { background: #3c3a32; color: #f9f6f2; font-size: 1.1rem; }
      #message { min-height: 1.5rem; font-weight: 700; margin-top: 0.75rem; }
      p.help { font-size: 0.9rem; }
    </style>
    </head>
    <body>
    <main>
      <h1>2048</h1>
      <div class="bar">
        <div class="score">Score: <span id="score">0</span></div>
        <button id="restart" type="button">New game</button>
      </div>
      <div id="board" role="grid" aria-label="2048 board"></div>
      <div id="message" role="status" aria-live="polite"></div>
      <p class="help">Use the arrow keys to slide the tiles. Equal tiles merge.</p>
    </main>
    
    <script id="game">
    function createGame() {
      var START = [
        [16, 0, 0, 4],
        [32, 2, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 8, 0]
      ];
      var board = START.map(function (row) { return row.slice(); });
      var score = 0;
      var over = false;
    
      function placeTwo() {
        for (var r = 0; r < 4; r++) {
          for (var c = 0; c < 4; c++) {
            if (board[r][c] === 0) { board[r][c] = 2; return true; }
          }
        }
        return false;
      }
    
      function slideLine(line) {
        var tiles = line.filter(function (v) { return v !== 0; });
        var out = [];
        var gained = 0;
        for (var i = 0; i < tiles.length; i++) {
          if (i + 1 < tiles.length && tiles[i] === tiles[i + 1]) {
            var v = tiles[i] * 2;
            out.push(v);
            gained += v;
            i++;
          } else {
            out.push(tiles[i]);
          }
        }
        while (out.length < 4) out.push(0);
        return { line: out, gained: gained };
      }
    
      function coords(dir, k, i) {
        // k: line index, i: position along the line starting at the side moved toward
        if (dir === 'left') return [k, i];
        if (dir === 'right') return [k, 3 - i];
        if (dir === 'up') return [i, k];
        return [3 - i, k]; // down
      }
    
      function canMove() {
        for (var r = 0; r < 4; r++) {
          for (var c = 0; c < 4; c++) {
            if (board[r][c] === 0) return true;
            if (c < 3 && board[r][c] === board[r][c + 1]) return true;
            if (r < 3 && board[r][c] === board[r + 1][c]) return true;
          }
        }
        return false;
      }
    
      placeTwo();
      placeTwo();
      over = !canMove();
    
      function move(dir) {
        if (over) return;
        if (dir !== 'left' && dir !== 'right' && dir !== 'up' && dir !== 'down') return;
        var next = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
        var gained = 0;
        var changed = false;
        for (var k = 0; k < 4; k++) {
          var line = [];
          for (var i = 0; i < 4; i++) {
            var p = coords(dir, k, i);
            line.push(board[p[0]][p[1]]);
          }
          var res = slideLine(line);
          gained += res.gained;
          for (var j = 0; j < 4; j++) {
            var q = coords(dir, k, j);
            next[q[0]][q[1]] = res.line[j];
            if (res.line[j] !== line[j]) changed = true;
          }
        }
        if (!changed) return;
        board = next;
        score += gained;
        placeTwo();
        over = !canMove();
      }
    
      function state() {
        return {
          board: board.map(function (row) { return row.slice(); }),
          score: score,
          over: over
        };
      }
    
      return { move: move, state: state };
    }
    </script>
    
    <script>
    (function () {
      var game = createGame();
      var boardEl = document.getElementById('board');
      var scoreEl = document.getElementById('score');
      var msgEl = document.getElementById('message');
    
      function render() {
        var s = game.state();
        boardEl.textContent = '';
        for (var r = 0; r < 4; r++) {
          for (var c = 0; c < 4; c++) {
            var v = s.board[r][c];
            var cell = document.createElement('div');
            cell.className = 'cell' + (v ? (v > 2048 ? ' big' : ' v' + v) : '');
            cell.setAttribute('role', 'gridcell');
            cell.setAttribute('aria-label', v ? String(v) : 'empty');
            cell.textContent = v ? String(v) : '';
            boardEl.appendChild(cell);
          }
        }
        scoreEl.textContent = String(s.score);
        msgEl.textContent = s.over ? 'Game over! Final score: ' + s.score : '';
      }
    
      var keys = { ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right' };
      document.addEventListener('keydown', function (e) {
        var dir = keys[e.key];
        if (!dir) return;
        e.preventDefault();
        game.move(dir);
        render();
      });
      document.getElementById('restart').addEventListener('click', function () {
        game = createGame();
        render();
      });
      render();
    })();
    </script>
    </body>
    </html>
  • Build SnakePassed
    Build Snake as one web page on a 10 by 10 grid, playable with the arrow keys (one key press, one step), with the grid drawn on the page.
    
    In <script id="game">, define createGame() returning an object with step(dir) and state(). dir is "up", "down", "left" or "right". state() returns {snake, food, score, over}: snake is a list of [x, y] cells, head first; food is [x, y]; score is a number; over is a boolean. x is the column (0 to 9, left to right), y the row (0 to 9, top to bottom); up is y - 1.
    
    The rules, exactly:
    1. The game starts with snake [[6, 6], [6, 7], [6, 8]], moving up, food at [9, 7], score 0.
    2. step(dir): if dir is the opposite of the current direction it is ignored and the snake keeps going; otherwise dir becomes the current direction. The head moves one cell that way.
    3. If the new head cell holds the food, the snake grows: its tail stays. Otherwise the tail cell is freed first.
    4. If the new head is off the grid or on a cell of the snake (after rule 3), the game is over: over becomes true and nothing else changes. Once over, step does nothing.
    5. Eating adds 1 to the score, and the next food goes to the first empty cell in reading order (row by row from the top, left to right) after the new head's cell, wrapping from [9, 9] to [0, 0].
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Snake</title>
    <style>
      body { margin: 0; font-family: system-ui, sans-serif; background: #f4f6f1; color: #1d2a1b; display: flex; justify-content: center; }
      main { width: 100%; max-width: 420px; padding: 1.5rem 1rem; box-sizing: border-box; }
      h1 { margin: 0 0 0.5rem; }
      .bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; }
      button { font: inherit; padding: 0.45rem 0.9rem; border-radius: 6px; border: 1px solid #2f5d2a; background: #2f5d2a; color: #fff; cursor: pointer; }
      #grid { display: grid; grid-template-columns: repeat(10, 1fr); gap: 2px; background: #c9d3c4; padding: 2px; border-radius: 6px; }
      .cell { aspect-ratio: 1 / 1; background: #fff; border-radius: 2px; }
      .snake { background: #3f8a36; }
      .head { background: #1f4f1a; }
      .food { background: #d0342c; border-radius: 50%; }
      #status { min-height: 1.5rem; margin-top: 0.75rem; font-weight: 600; }
    </style>
    </head>
    <body>
    <main>
      <h1>Snake</h1>
      <div class="bar">
        <div>Score: <span id="score">0</span></div>
        <button id="restart" type="button">Restart</button>
      </div>
      <div id="grid" aria-label="Snake grid, 10 by 10"></div>
      <div id="status" role="status" aria-live="polite">Use the arrow keys: one press, one step.</div>
    </main>
    
    <script id="game">
    function createGame() {
      var N = 10;
      var snake = [[6, 6], [6, 7], [6, 8]];
      var dir = 'up';
      var food = [9, 7];
      var score = 0;
      var over = false;
      var DELTA = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] };
      var OPPOSITE = { up: 'down', down: 'up', left: 'right', right: 'left' };
    
      function occupied(cells, x, y) {
        for (var i = 0; i < cells.length; i++) {
          if (cells[i][0] === x && cells[i][1] === y) return true;
        }
        return false;
      }
    
      function step(d) {
        if (over) return;
        if (d === 'up' || d === 'down' || d === 'left' || d === 'right') {
          if (d !== OPPOSITE[dir]) dir = d;
        }
        var delta = DELTA[dir];
        var head = [snake[0][0] + delta[0], snake[0][1] + delta[1]];
        var eats = head[0] === food[0] && head[1] === food[1];
        var body = eats ? snake.slice() : snake.slice(0, snake.length - 1);
        if (head[0] < 0 || head[0] >= N || head[1] < 0 || head[1] >= N || occupied(body, head[0], head[1])) {
          over = true;
          return;
        }
        snake = [head].concat(body);
        if (eats) {
          score += 1;
          var start = head[1] * N + head[0];
          for (var k = 1; k <= N * N; k++) {
            var idx = (start + k) % (N * N);
            var x = idx % N;
            var y = Math.floor(idx / N);
            if (!occupied(snake, x, y)) { food = [x, y]; break; }
          }
        }
      }
    
      function state() {
        return {
          snake: snake.map(function (c) { return [c[0], c[1]]; }),
          food: [food[0], food[1]],
          score: score,
          over: over
        };
      }
    
      return { step: step, state: state };
    }
    </script>
    
    <script>
    (function () {
      var game = createGame();
      var grid = document.getElementById('grid');
      var scoreEl = document.getElementById('score');
      var statusEl = document.getElementById('status');
      var cells = [];
      for (var i = 0; i < 100; i++) {
        var c = document.createElement('div');
        c.className = 'cell';
        grid.appendChild(c);
        cells.push(c);
      }
      function render() {
        var s = game.state();
        for (var i = 0; i < 100; i++) cells[i].className = 'cell';
        cells[s.food[1] * 10 + s.food[0]].className = 'cell food';
        s.snake.forEach(function (p, idx) {
          cells[p[1] * 10 + p[0]].className = 'cell snake' + (idx === 0 ? ' head' : '');
        });
        scoreEl.textContent = String(s.score);
        statusEl.textContent = s.over ? 'Game over! Score: ' + s.score + '. Press Restart to play again.' : 'Use the arrow keys: one press, one step.';
      }
      var keys = { ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right' };
      document.addEventListener('keydown', function (e) {
        var d = keys[e.key];
        if (!d) return;
        e.preventDefault();
        game.step(d);
        render();
      });
      document.getElementById('restart').addEventListener('click', function () {
        game = createGame();
        render();
      });
      render();
    })();
    </script>
    </body>
    </html>
  • Box-pushing puzzlePassed
    Build a box-pushing puzzle as one web page on an 8 by 7 grid, playable with the arrow keys, with the level drawn on the page. Give the page and its heading the title Box-pushing puzzle.
    
    In <script id="game">, define createGame() returning an object with walk(dir) and state(). dir is "up", "down", "left" or "right". state() returns {player, boxes, pushes, steps, solved}: player is [x, y]; boxes is a list of [x, y] sorted by row, then column; pushes and steps are numbers; solved is a boolean. x is the column (0 to 7, left to right), y the row (0 to 6, top to bottom); up is y - 1.
    
    The level, row 0 first, 8 characters to a row (a space is empty floor; the outer ring is all wall):
    ```
    ########
    #     ##
    ##  $  #
    ##     #
    # * $  #
    #  .+  #
    ########
    ```
    # wall, space floor, . goal, $ box, * box on a goal, @ player, + player on a goal.
    
    The rules, exactly:
    1. The game starts with this level, steps 0, pushes 0 and solved false. Walls and goals never change.
    2. walk(dir) moves the player one cell in dir. If that cell is a wall, nothing changes and nothing is counted. A goal is floor, so the player can stand on one.
    3. If that cell holds a box, the box moves one cell further in dir and the player takes the box's old cell. This push happens only if the cell beyond the box is empty floor or a goal: not a wall and not another box. Otherwise nothing changes and nothing is counted.
    4. A walk that moves the player adds 1 to steps. A push is a walk too, so it adds 1 to pushes as well.
    5. solved is true when every box is on a goal. Once solved, walk does nothing.
    
    The page: the arrow keys do the same walks as walk(dir), one walk for each key press (a key that repeats while held walks once). Four buttons with data-dir="up", data-dir="down", data-dir="left" and data-dir="right" do the same walks. Label them Up, Down, Left and Right, laid out like the arrow keys: Up above Down, with Left, Down and Right in one row. A button with id="restart", labelled Restart, starts the level over, with steps and pushes back at 0.
    The board is an element with id="board". It holds one element per cell, 56 in all, row by row from the top, 8 to a row, and nothing else. Each cell has role="img" and an aria-label that names what it holds: wall, empty floor, empty goal, box, box on a goal, you or you on a goal. Every cell except empty floor also shows a visible character as its text, so that a wall, a goal, a box and you can each be seen (the character is yours to choose).
    Show the steps in an element with id="steps" and the pushes in one with id="pushes", each as a plain number.
    The status line is an element with id="status". Until the level is solved, it must not say that it is solved (a line such as Not solved yet is fine). Once it is, it says solved, with the number of steps next to the word steps and the number of pushes next to the word pushes, for example: Solved in 12 steps with 3 pushes.
    A tenth of a second after each key press, button press or Restart, the board, the steps, the pushes and the status line show what state() says. A page may draw on the next animation frame or after a timer.
    The page must not use eval or Function, must not give a timer a string of text (a timer takes a function), must not add a script element to the page, must not set an event attribute such as onclick from text, and must not make network requests or load anything from another site: no fetch, XMLHttpRequest, WebSocket, EventSource, sendBeacon or importScripts, and no image or file from another site.
    The whole page must be under 65,536 characters, and the script with id="game" under 20,000 characters.
    Light background; walls dark, goals ringed, boxes and the player easy to tell apart. Tell a box on a goal from one off a goal by a mark or shape, not by colour alone. The two scripts share one global scope, so give the page's copy of the map another name than the logic's (a const MAP in both stops the second script with an error), or wrap the page's script in a function.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Box-pushing puzzle</title>
    <style>
      body { margin: 0; font-family: system-ui, sans-serif; background: #f7f5ef; color: #222; }
      main { max-width: 30rem; margin: 0 auto; padding: 1.5rem 1rem; box-sizing: border-box; }
      h1 { margin: 0 0 0.5rem; font-size: 1.7rem; }
      p.help { margin: 0 0 1rem; color: #555; }
      #board { display: grid; grid-template-columns: repeat(8, 1fr); gap: 2px; width: 100%; max-width: 26rem; background: #d9d4c7; padding: 2px; border-radius: 6px; box-sizing: border-box; }
      .cell { aspect-ratio: 1 / 1; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: clamp(1rem, 5vw, 1.6rem); background: #fffdf8; color: #222; border-radius: 3px; line-height: 1; box-sizing: border-box; }
      .wall { background: #2e2e33; color: #8b8b93; }
      .goal { box-shadow: inset 0 0 0 3px #c0392b; color: #c0392b; border-radius: 50%; }
      .box { background: #c98a3d; color: #3d2408; }
      .boxgoal { background: #3a8a4a; color: #fff; box-shadow: inset 0 0 0 3px #c0392b; }
      .player { background: #2f62c9; color: #fff; border-radius: 50%; }
      .playergoal { background: #2f62c9; color: #fff; border-radius: 50%; box-shadow: inset 0 0 0 3px #c0392b; }
      .info { display: flex; gap: 1.5rem; margin: 1rem 0 0.5rem; font-size: 1.05rem; }
      #status { min-height: 1.5rem; font-weight: 700; margin-bottom: 0.75rem; }
      .pad { display: grid; grid-template-columns: repeat(3, 4.5rem); grid-template-rows: auto auto; gap: 0.4rem; margin-bottom: 1rem; }
      .pad button, #restart { font: inherit; padding: 0.55rem 0; border-radius: 6px; border: 1px solid #333; background: #fff; color: #222; cursor: pointer; }
      .pad button:hover, #restart:hover { background: #ece8dc; }
      .pad [data-dir="up"] { grid-column: 2; grid-row: 1; }
      .pad [data-dir="left"] { grid-column: 1; grid-row: 2; }
      .pad [data-dir="down"] { grid-column: 2; grid-row: 2; }
      .pad [data-dir="right"] { grid-column: 3; grid-row: 2; }
      #restart { padding: 0.55rem 1.2rem; }
      .legend { font-size: 0.9rem; color: #555; margin-top: 1rem; }
    </style>
    </head>
    <body>
    <main>
      <h1>Box-pushing puzzle</h1>
      <p class="help">Push every box onto a goal. Use the arrow keys or the buttons.</p>
      <div id="board" aria-label="Puzzle board, 8 columns by 7 rows"></div>
      <div class="info">
        <div>Steps: <span id="steps">0</span></div>
        <div>Pushes: <span id="pushes">0</span></div>
      </div>
      <div id="status" role="status" aria-live="polite">Not solved yet</div>
      <div class="pad">
        <button type="button" data-dir="up">Up</button>
        <button type="button" data-dir="left">Left</button>
        <button type="button" data-dir="down">Down</button>
        <button type="button" data-dir="right">Right</button>
      </div>
      <button type="button" id="restart">Restart</button>
      <p class="legend"># wall, ○ goal, □ box, ▣ box on a goal, @ you.</p>
    </main>
    
    <script id="game">
    function createGame() {
      var LEVEL = [
        '########',
        '#     ##',
        '##  $  #',
        '##     #',
        '# * $  #',
        '#  .+  #',
        '########'
      ];
      var W = 8, H = 7;
      var walls = [];
      var goals = [];
      var boxes = [];
      var player = [0, 0];
      var steps = 0, pushes = 0, solved = false;
      for (var y = 0; y < H; y++) {
        walls.push([]);
        goals.push([]);
        for (var x = 0; x < W; x++) {
          var ch = LEVEL[y].charAt(x);
          walls[y].push(ch === '#');
          goals[y].push(ch === '.' || ch === '*' || ch === '+');
          if (ch === '$' || ch === '*') boxes.push([x, y]);
          if (ch === '@' || ch === '+') player = [x, y];
        }
      }
      var DELTA = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] };
    
      function isWall(x, y) {
        if (x < 0 || y < 0 || x >= W || y >= H) return true;
        return walls[y][x];
      }
      function boxAt(x, y) {
        for (var i = 0; i < boxes.length; i++) {
          if (boxes[i][0] === x && boxes[i][1] === y) return i;
        }
        return -1;
      }
      function checkSolved() {
        for (var i = 0; i < boxes.length; i++) {
          if (!goals[boxes[i][1]][boxes[i][0]]) return false;
        }
        return true;
      }
    
      function walk(dir) {
        if (solved) return;
        if (dir !== 'up' && dir !== 'down' && dir !== 'left' && dir !== 'right') return;
        var d = DELTA[dir];
        var nx = player[0] + d[0], ny = player[1] + d[1];
        if (isWall(nx, ny)) return;
        var b = boxAt(nx, ny);
        if (b >= 0) {
          var bx = nx + d[0], by = ny + d[1];
          if (isWall(bx, by) || boxAt(bx, by) >= 0) return;
          boxes[b] = [bx, by];
          player = [nx, ny];
          steps += 1;
          pushes += 1;
        } else {
          player = [nx, ny];
          steps += 1;
        }
        solved = checkSolved();
      }
    
      function state() {
        var sorted = boxes.map(function (b) { return [b[0], b[1]]; });
        sorted.sort(function (a, b) { return a[1] - b[1] || a[0] - b[0]; });
        return { player: [player[0], player[1]], boxes: sorted, pushes: pushes, steps: steps, solved: solved };
      }
    
      return { walk: walk, state: state };
    }
    </script>
    
    <script>
    (function () {
      var PAGE_LEVEL = [
        '########',
        '#     ##',
        '##  $  #',
        '##     #',
        '# * $  #',
        '#  .+  #',
        '########'
      ];
      var game = createGame();
      var boardEl = document.getElementById('board');
      var stepsEl = document.getElementById('steps');
      var pushesEl = document.getElementById('pushes');
      var statusEl = document.getElementById('status');
      var cells = [];
      for (var i = 0; i < 56; i++) {
        var cell = document.createElement('div');
        cell.setAttribute('role', 'img');
        boardEl.appendChild(cell);
        cells.push(cell);
      }
    
      function render() {
        var s = game.state();
        for (var y = 0; y < 7; y++) {
          for (var x = 0; x < 8; x++) {
            var ch = PAGE_LEVEL[y].charAt(x);
            var wall = ch === '#';
            var goal = ch === '.' || ch === '*' || ch === '+';
            var hasBox = false;
            for (var k = 0; k < s.boxes.length; k++) {
              if (s.boxes[k][0] === x && s.boxes[k][1] === y) { hasBox = true; break; }
            }
            var isPlayer = s.player[0] === x && s.player[1] === y;
            var label, text, cls;
            if (wall) { label = 'wall'; text = '#'; cls = 'wall'; }
            else if (isPlayer) {
              label = goal ? 'you on a goal' : 'you'; text = '@'; cls = goal ? 'playergoal' : 'player';
            } else if (hasBox) {
              label = goal ? 'box on a goal' : 'box'; text = goal ? '▣' : '□'; cls = goal ? 'boxgoal' : 'box';
            } else if (goal) { label = 'empty goal'; text = '○'; cls = 'goal'; }
            else { label = 'empty floor'; text = ''; cls = 'floor'; }
            var el = cells[y * 8 + x];
            el.className = 'cell ' + cls;
            el.setAttribute('aria-label', label);
            el.textContent = text;
          }
        }
        stepsEl.textContent = String(s.steps);
        pushesEl.textContent = String(s.pushes);
        statusEl.textContent = s.solved
          ? 'Solved in ' + s.steps + ' steps with ' + s.pushes + ' pushes'
          : 'Not solved yet';
      }
    
      function doWalk(dir) {
        game.walk(dir);
        render();
      }
    
      var keys = { ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right' };
      document.addEventListener('keydown', function (e) {
        var dir = keys[e.key];
        if (!dir) return;
        e.preventDefault();
        if (e.repeat) return;
        doWalk(dir);
      });
      var pads = document.querySelectorAll('button[data-dir]');
      for (var j = 0; j < pads.length; j++) {
        pads[j].addEventListener('click', function (e) {
          doWalk(e.currentTarget.getAttribute('data-dir'));
        });
      }
      document.getElementById('restart').addEventListener('click', function () {
        game = createGame();
        render();
      });
      render();
    })();
    </script>
    </body>
    </html>
  • MinesweeperPassed
    Build Minesweeper as one web page: a 9 by 9 board with 10 mines, in the layout below, with the board drawn on the page.
    
    In <script id="game">, define createGame() returning an object with press(move) and state(). The site plays the game more than once, calling createGame() again each time, so every game starts from the layout. move is an array [kind, row, col]: kind is "open" or "flag", row is 0 (top) to 8 (bottom), col is 0 (left) to 8 (right). state() returns {cells, status, mines_left}: cells is 9 strings of 9 characters, one per row from the top. A character is "#" for a hidden cell, "F" for a flagged cell, "." for an opened cell with no mines around it, "1" to "8" for an opened cell with that many mines among the 8 cells around it, and "*" for a mine after a loss. status is "playing", "won" or "lost". mines_left is 10 minus the number of flagged cells, and can be negative.
    
    The mines, row by row from the top. In this layout * is a mine and . is a safe cell.
    row 0  .........
    row 1  ......*..
    row 2  .*...*...
    row 3  .......*.
    row 4  ........*
    row 5  ......*..
    row 6  *........
    row 7  ..*....*.
    row 8  ....*....
    
    The rules, exactly:
    1. The game starts with every cell hidden, no flags, and status "playing".
    2. press(["open", r, c]) on a hidden cell opens it. If it is a mine, status becomes "lost" and every mine shows "*", flagged or not. Otherwise the cell shows its number, or "." when no mine is among the cells around it.
    3. An opened cell with no mines around it also opens each hidden, unflagged cell around it (8 directions). Each of those with no mines around it opens its own hidden, unflagged neighbours the same way, repeatedly, until nothing more opens. A flagged cell is never opened this way, and nothing spreads from it. A numbered cell opens, but nothing spreads from it.
    4. press(["open", r, c]) on a flagged cell or an opened cell does nothing.
    5. press(["flag", r, c]) on a hidden cell flags it. On a flagged cell it removes the flag, and the cell is hidden again. On an opened cell it does nothing.
    6. status becomes "won" when every cell without a mine is opened, however the last cell is opened. A flag does not count: a flagged cell without a mine must be unflagged and opened. After a win every mine shows "F" and counts as flagged, whether or not the player flagged it, so mines_left is 0.
    7. Once status is "won" or "lost", press does nothing.
    After a loss a flag still counts in mines_left, even on a mine that shows "*", and a flag on a safe cell still shows "F".
    
    The page: a title, a short paragraph of rules, then one white panel holding a status line, a Flag mode button and the board, on a warm off-white page. The type is the system sans-serif (font-family: system-ui, sans-serif); load no font. Give these parts these names, so the site can read them:
    - an element with role="status": it shows "Mines left" and mines_left as a number, with a minus sign when it is below zero, then the status word, "Playing", "Won" (green) or "Lost" (red);
    - a button with id="flag-mode": it starts with the text "Flag mode: off" and aria-pressed="false". When it is on, its text is "Flag mode: on", aria-pressed="true", and it is drawn in the pink accent;
    - the board, which is either 81 cell buttons, each with data-row (0 at the top to 8) and data-col (0 at the left to 8), or one canvas that draws all of it, with the id board: 324 pixels across and down (set its width and height attributes), nine squares of 36 pixels each way, row 0 at the top and column 0 at the left. On a canvas, a click or a right-click acts on the square under the pointer: find the square from the event's offsetX and offsetY, each scaled by the canvas's width over its clientWidth (or its height over its clientHeight), since a phone may draw the canvas smaller.
    A click on a cell calls press(["open", row, col]) for that cell, unless Flag mode is on: then it calls press(["flag", row, col]). A right-click on a cell (the contextmenu event) calls press(["flag", row, col]) and prevents the browser's own menu. Draw the board from state() after every press: a hidden or empty cell shows no text, a numbered cell shows its number, and a flag or a mine shows a mark with text in it (a symbol, or a word hidden from sight). On a canvas, clear the whole canvas and draw it again after every press, the cells in reading order (row 0 first, columns left to right): a numbered cell as its number in text, a flag or a mine as one short mark in text (F, *, or another plain symbol), and a hidden or empty cell as nothing; the canvas draws nothing else. Flags and mines are simple marks, not emoji. The page fits a phone with no sideways scrolling. A reload of the page starts a new game: every cell is hidden, no flag is set, Flag mode is off and the status reads "Playing", so nothing from the last load is kept. The keyboard is welcome but not checked: Tab moves between cells, Enter or Space opens one, and F flags it.
    The page runs its own code only: no eval, no Function(), no timer given as text, and no network request (fetch, XMLHttpRequest, WebSocket, EventSource, sendBeacon or importScripts). It loads nothing from another site.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Minesweeper</title>
    <style>
      * { box-sizing: border-box; }
      body { margin: 0; font-family: system-ui, sans-serif; background: #f8f4ec; color: #2a2522; }
      main { max-width: 26rem; margin: 0 auto; padding: 1.25rem 0.75rem 2rem; }
      h1 { margin: 0 0 0.4rem; font-size: 1.7rem; }
      p.rules { margin: 0 0 1rem; color: #5a524c; line-height: 1.45; font-size: 0.95rem; }
      .panel { background: #fff; border: 1px solid #e4dccf; border-radius: 12px; padding: 0.9rem; }
      .top { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.5rem; margin-bottom: 0.75rem; }
      [role="status"] { font-weight: 600; }
      .word-playing { color: #2a2522; }
      .word-won { color: #1d7a33; }
      .word-lost { color: #c0262d; }
      #flag-mode { font: inherit; font-size: 0.95rem; padding: 0.45rem 0.8rem; border-radius: 8px; border: 1px solid #c9bfb2; background: #fff; color: #2a2522; cursor: pointer; }
      #flag-mode[aria-pressed="true"] { background: #d6336c; border-color: #d6336c; color: #fff; }
      #board { display: grid; grid-template-columns: repeat(9, 1fr); gap: 3px; width: 100%; max-width: 324px; margin: 0 auto; }
      .cell { aspect-ratio: 1 / 1; width: 100%; padding: 0; font: inherit; font-weight: 700; font-size: 1.05rem; border: 1px solid #b9b0a3; border-radius: 4px; background: #d9d1c4; color: #2a2522; cursor: pointer; display: flex; align-items: center; justify-content: center; }
      .cell:focus-visible { outline: 2px solid #d6336c; outline-offset: 1px; }
      .cell.open { background: #fdfbf7; border-color: #e7e0d5; cursor: default; }
      .cell.flag { background: #f3c3d4; color: #8a1240; }
      .cell.mine { background: #f2b6b6; color: #7a0d0d; }
      .n1 { color: #1f5fbf; } .n2 { color: #1d7a33; } .n3 { color: #c0262d; } .n4 { color: #2c2a8a; }
      .n5 { color: #7a2d0f; } .n6 { color: #137a7a; } .n7 { color: #222; } .n8 { color: #666; }
    </style>
    </head>
    <body>
    <main>
      <h1>Minesweeper</h1>
      <p class="rules">Open every safe square without hitting one of the 10 mines. A number tells how many mines touch that square. Right-click a square, or turn on Flag mode and click, to flag a mine you suspect.</p>
      <div class="panel">
        <div class="top">
          <div role="status" id="status">Mines left: <span id="mines-left">10</span> · <span id="word" class="word-playing">Playing</span></div>
          <button type="button" id="flag-mode" aria-pressed="false">Flag mode: off</button>
        </div>
        <div id="board" aria-label="Minesweeper board, 9 by 9"></div>
      </div>
    </main>
    
    <script id="game">
    function createGame() {
      var LAYOUT = [
        '.........',
        '......*..',
        '.*...*...',
        '.......*.',
        '........*',
        '......*..',
        '*........',
        '..*....*.',
        '....*....'
      ];
      var N = 9;
      var mine = [], opened = [], flagged = [], counts = [];
      var status = 'playing';
      var r, c;
      for (r = 0; r < N; r++) {
        mine.push([]); opened.push([]); flagged.push([]);
        for (c = 0; c < N; c++) {
          mine[r].push(LAYOUT[r].charAt(c) === '*');
          opened[r].push(false);
          flagged[r].push(false);
        }
      }
      function around(rr, cc, fn) {
        for (var dr = -1; dr <= 1; dr++) {
          for (var dc = -1; dc <= 1; dc++) {
            if (dr === 0 && dc === 0) continue;
            var nr = rr + dr, nc = cc + dc;
            if (nr >= 0 && nr < N && nc >= 0 && nc < N) fn(nr, nc);
          }
        }
      }
      for (r = 0; r < N; r++) {
        counts.push([]);
        for (c = 0; c < N; c++) {
          var n = 0;
          around(r, c, function (a, b) { if (mine[a][b]) n++; });
          counts[r].push(n);
        }
      }
    
      function checkWin() {
        for (var i = 0; i < N; i++) {
          for (var j = 0; j < N; j++) {
            if (!mine[i][j] && !opened[i][j]) return false;
          }
        }
        return true;
      }
    
      function openCell(r0, c0) {
        if (mine[r0][c0]) { status = 'lost'; return; }
        var stack = [[r0, c0]];
        opened[r0][c0] = true;
        while (stack.length) {
          var cur = stack.pop();
          if (counts[cur[0]][cur[1]] !== 0) continue;
          around(cur[0], cur[1], function (a, b) {
            if (!opened[a][b] && !flagged[a][b] && !mine[a][b]) {
              opened[a][b] = true;
              stack.push([a, b]);
            }
          });
        }
        if (checkWin()) status = 'won';
      }
    
      function press(move) {
        if (status !== 'playing') return;
        if (!Array.isArray(move) || move.length !== 3) return;
        var kind = move[0], rr = move[1], cc = move[2];
        if (typeof rr !== 'number' || typeof cc !== 'number') return;
        if (!Number.isInteger(rr) || !Number.isInteger(cc)) return;
        if (rr < 0 || rr >= N || cc < 0 || cc >= N) return;
        if (kind === 'open') {
          if (opened[rr][cc] || flagged[rr][cc]) return;
          openCell(rr, cc);
        } else if (kind === 'flag') {
          if (opened[rr][cc]) return;
          flagged[rr][cc] = !flagged[rr][cc];
        }
      }
    
      function state() {
        var cells = [];
        var flags = 0;
        for (var i = 0; i < N; i++) {
          var row = '';
          for (var j = 0; j < N; j++) {
            if (flagged[i][j]) flags++;
            var ch;
            if (mine[i][j] && status === 'lost') ch = '*';
            else if (mine[i][j] && status === 'won') ch = 'F';
            else if (flagged[i][j]) ch = 'F';
            else if (opened[i][j]) ch = counts[i][j] === 0 ? '.' : String(counts[i][j]);
            else ch = '#';
            row += ch;
          }
          cells.push(row);
        }
        return { cells: cells, status: status, mines_left: status === 'won' ? 0 : 10 - flags };
      }
    
      return { press: press, state: state };
    }
    </script>
    
    <script>
    (function () {
      var game = createGame();
      var flagMode = false;
      var boardEl = document.getElementById('board');
      var minesEl = document.getElementById('mines-left');
      var wordEl = document.getElementById('word');
      var flagBtn = document.getElementById('flag-mode');
      var buttons = [];
    
      for (var r = 0; r < 9; r++) {
        for (var c = 0; c < 9; c++) {
          var b = document.createElement('button');
          b.type = 'button';
          b.className = 'cell';
          b.setAttribute('data-row', String(r));
          b.setAttribute('data-col', String(c));
          boardEl.appendChild(b);
          buttons.push(b);
        }
      }
    
      function cellOf(target) {
        var el = target && target.closest ? target.closest('.cell') : null;
        if (!el) return null;
        return [Number(el.getAttribute('data-row')), Number(el.getAttribute('data-col'))];
      }
    
      function render() {
        var s = game.state();
        for (var r = 0; r < 9; r++) {
          for (var c = 0; c < 9; c++) {
            var ch = s.cells[r].charAt(c);
            var b = buttons[r * 9 + c];
            var pos = 'row ' + (r + 1) + ', column ' + (c + 1) + ': ';
            b.className = 'cell';
            if (ch === '#') {
              b.textContent = '';
              b.setAttribute('aria-label', pos + 'hidden');
            } else if (ch === 'F') {
              b.textContent = 'F';
              b.className = 'cell flag';
              b.setAttribute('aria-label', pos + 'flag');
            } else if (ch === '*') {
              b.textContent = '*';
              b.className = 'cell mine';
              b.setAttribute('aria-label', pos + 'mine');
            } else if (ch === '.') {
              b.textContent = '';
              b.className = 'cell open';
              b.setAttribute('aria-label', pos + 'empty');
            } else {
              b.textContent = ch;
              b.className = 'cell open n' + ch;
              b.setAttribute('aria-label', pos + ch);
            }
          }
        }
        minesEl.textContent = String(s.mines_left);
        var word = s.status === 'won' ? 'Won' : s.status === 'lost' ? 'Lost' : 'Playing';
        wordEl.textContent = word;
        wordEl.className = 'word-' + s.status;
      }
    
      boardEl.addEventListener('click', function (e) {
        var rc = cellOf(e.target);
        if (!rc) return;
        game.press([flagMode ? 'flag' : 'open', rc[0], rc[1]]);
        render();
      });
      boardEl.addEventListener('contextmenu', function (e) {
        var rc = cellOf(e.target);
        if (!rc) return;
        e.preventDefault();
        game.press(['flag', rc[0], rc[1]]);
        render();
      });
      boardEl.addEventListener('keydown', function (e) {
        if (e.key !== 'f' && e.key !== 'F') return;
        var rc = cellOf(e.target);
        if (!rc) return;
        e.preventDefault();
        game.press(['flag', rc[0], rc[1]]);
        render();
      });
      flagBtn.addEventListener('click', function () {
        flagMode = !flagMode;
        flagBtn.textContent = flagMode ? 'Flag mode: on' : 'Flag mode: off';
        flagBtn.setAttribute('aria-pressed', flagMode ? 'true' : 'false');
      });
      render();
    })();
    </script>
    </body>
    </html>
Building apps 4 of 4
  • Step sequencerPassed
    Build a web page called "Step sequencer": three rows labelled Kick, Snare and Hat, of 16 step buttons each, a Play button and a Stop button, and drums made with the Web Audio API, with no sound files.
    
    In <script id="game">, define createGame() returning an object with press(cmd) and state(). The page calls createGame() at load or on the first press. The logic keeps the pattern, whether it is playing, the playhead and the hits. The page makes the sound. Do not use eval or Function, and never run text as code: give a timer a function, not a string.
    
    The starting pattern, one row per track. Steps are numbered from 1 in the rows below: each row is 16 characters, 1 for on and 0 for off. The first character is step 1 on the page and step 0 for press():
    kick   1000001000100000
    snare  0000100010001000
    hat    1011101011101010
    
    The rules, exactly:
    1. At the start, playing is false, playhead is 0 and hits is [].
    2. press([track, step]) toggles one cell: track 0 is kick, 1 snare, 2 hat; step is 0 to 15, where 0 is the first step. Toggling changes the pattern and nothing else.
    3. press('play') does nothing when playing is already true. Otherwise it sets playing to true, and hits becomes the list of track numbers (0 kick, 1 snare, 2 hat) whose cell at the playhead is 1, in ascending order ([] when there are none). So the step under the playhead sounds as play starts.
    4. press('stop') sets playing to false, playhead to 0 and hits to [].
    5. press('tick') does nothing unless playing is true. When it is, playhead goes on by one, and after 15 it goes back to 0. hits becomes the list of track numbers whose cell at the new playhead is 1, in ascending order ([] when there are none).
    6. Any other cmd does nothing: a list that is not exactly two whole numbers (such as [0, 1, 2], [1], [] or [true, 0]), null, a number, true or false, a word other than play, stop or tick, and a track or step outside the ranges above.
    Track and step are whole numbers.
    
    state() returns {playing, playhead, hits, pattern}: playing is true or false; playhead is 0 to 15; hits lists the track numbers set by the last tick or by the play that started playback, in ascending order ([] at the start and after stop); pattern is three strings of 16 characters, kick first, each character 1 or 0.
    
    The page:
    - Each step button is a real button with the attributes data-track (0, 1 or 2) and data-step (0 to 15), and aria-pressed set to true or false to match its state. A click calls press([track, step]), and after every press, the page draws from state().
    - A step that is on has the class on, and the stylesheet fills it dark; a step that is off has no class on.
    - Play has the id play and Stop the id stop. Play calls press('play') and starts one timer that calls press('tick') every 125 ms: 120 quarter-note beats a minute, four steps to a beat. Stop calls press('stop') and clears the timer. Each play and each tick sounds the hits that state() then reports, and nothing else sounds.
    - Play has the disabled attribute while playing, and Stop has it while stopped.
    - A status line with the id status reads "Stopped", or "Playing, step N of 16" with N the playhead plus 1. Give it a fixed height, so the grid does not move when its text changes.
    - A span with the id announce, set to aria-live polite, is empty until playback starts for the first time. From then on it says "Playing" when playback starts and "Stopped" when it stops, and changes at no other time.
    - The cells in the playhead column have the class playhead while playing, and no cell has it while stopped.
    - The numbers 1 to 16, as text, sit above the grid, and the playhead's number is pink. Under 720 px each step shows its number.
    - When the page becomes hidden, it presses Stop, so nothing sounds in a background tab.
    - Each track in hits plays its drum: kick is a falling sine tone, snare a short noise burst with a low body tone, hat a short high noise burst. Tones use oscillators; noise bursts use buffer sources playing a buffer of random samples: the kick is one oscillator, the snare one buffer source and one oscillator, the hat one buffer source. Hits that land together must not clip, so put a gain or a limiter before the output. Create the AudioContext inside the first click (browsers need a click before they make sound), and resume it if it is suspended.
    - Flat and plain: a light background, dark ink, no shadows or gradients, Play the one pink button (#b31f57), and the playhead cell outlined in pink where you are. At 1280 px the 16 steps sit in one row; under 720 px they form two bars of 8. The page never scrolls sideways.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the sequencer through createGame(). Wire the page in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Step sequencer</title>
    <style>
      * { box-sizing: border-box; }
      html, body { overflow-x: hidden; }
      body { margin: 0; font-family: system-ui, sans-serif; background: #f7f7f4; color: #1b1b1f; }
      main { max-width: 1200px; margin: 0 auto; padding: 1.5rem 1rem 2rem; }
      h1 { margin: 0 0 1rem; font-size: 1.6rem; }
      .controls { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; }
      .controls button { font: inherit; font-weight: 600; padding: 0.5rem 1.4rem; border-radius: 6px; cursor: pointer; border: 2px solid #1b1b1f; background: #fff; color: #1b1b1f; }
      #play { background: #b31f57; border-color: #b31f57; color: #fff; }
      .controls button[disabled] { cursor: default; background: #e4e4df; border-color: #c9c9c3; color: #77777a; }
      #status { height: 1.5rem; line-height: 1.5rem; margin: 0 0 0.75rem; font-variant-numeric: tabular-nums; }
      .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
      .row { display: grid; grid-template-columns: 4rem 1fr; gap: 0.5rem; align-items: center; margin-bottom: 0.5rem; }
      .label { font-weight: 700; }
      .steps { display: grid; grid-template-columns: repeat(16, minmax(0, 1fr)); gap: 4px; }
      .num { text-align: center; font-size: 0.8rem; color: #55555a; font-variant-numeric: tabular-nums; }
      .num.current { color: #b31f57; font-weight: 700; }
      .step { font: inherit; font-size: 0.75rem; min-width: 0; height: 2.6rem; padding: 0; border: 2px solid #1b1b1f; border-radius: 4px; background: #fff; color: #55555a; cursor: pointer; }
      .step:nth-child(4n+1) { border-left-width: 4px; }
      .step.on { background: #1b1b1f; color: #fff; }
      .step.playhead { outline: 3px solid #b31f57; outline-offset: 1px; }
      .step:focus-visible { outline: 3px solid #1b1b1f; outline-offset: 2px; }
      .step.playhead:focus-visible { outline-color: #b31f57; }
      @media (max-width: 719px) {
        .steps { grid-template-columns: repeat(8, minmax(0, 1fr)); row-gap: 8px; }
        .row { grid-template-columns: 3.2rem 1fr; }
      }
    </style>
    </head>
    <body>
    <main>
      <h1>Step sequencer</h1>
      <div class="controls">
        <button type="button" id="play">Play</button>
        <button type="button" id="stop" disabled>Stop</button>
        <span id="announce" class="sr" aria-live="polite"></span>
      </div>
      <p id="status">Stopped</p>
      <div class="row" aria-hidden="true">
        <span class="label"></span>
        <div class="steps" id="numbers"></div>
      </div>
      <div id="grid"></div>
    </main>
    
    <script id="game">
    function createGame() {
      var pattern = [
        '1000001000100000'.split('').map(Number),
        '0000100010001000'.split('').map(Number),
        '1011101011101010'.split('').map(Number)
      ];
      var playing = false;
      var playhead = 0;
      var hits = [];
    
      function hitsAt(step) {
        var out = [];
        for (var t = 0; t < 3; t++) if (pattern[t][step] === 1) out.push(t);
        return out;
      }
      function isWhole(n) { return typeof n === 'number' && Number.isInteger(n); }
    
      function press(cmd) {
        if (Array.isArray(cmd)) {
          if (cmd.length !== 2) return;
          var track = cmd[0], step = cmd[1];
          if (!isWhole(track) || !isWhole(step)) return;
          if (track < 0 || track > 2 || step < 0 || step > 15) return;
          pattern[track][step] = pattern[track][step] ? 0 : 1;
          return;
        }
        if (cmd === 'play') {
          if (playing) return;
          playing = true;
          hits = hitsAt(playhead);
          return;
        }
        if (cmd === 'stop') {
          playing = false;
          playhead = 0;
          hits = [];
          return;
        }
        if (cmd === 'tick') {
          if (!playing) return;
          playhead = (playhead + 1) % 16;
          hits = hitsAt(playhead);
        }
      }
    
      function state() {
        return {
          playing: playing,
          playhead: playhead,
          hits: hits.slice(),
          pattern: pattern.map(function (row) { return row.join(''); })
        };
      }
    
      return { press: press, state: state };
    }
    </script>
    
    <script>
    (function () {
      var game = createGame();
      var NAMES = ['Kick', 'Snare', 'Hat'];
      var grid = document.getElementById('grid');
      var numbers = document.getElementById('numbers');
      var playBtn = document.getElementById('play');
      var stopBtn = document.getElementById('stop');
      var statusEl = document.getElementById('status');
      var announceEl = document.getElementById('announce');
      var stepButtons = [[], [], []];
      var numEls = [];
      var timer = null;
    
      for (var s = 0; s < 16; s++) {
        var n = document.createElement('span');
        n.className = 'num';
        n.textContent = String(s + 1);
        numbers.appendChild(n);
        numEls.push(n);
      }
    
      for (var t = 0; t < 3; t++) {
        var row = document.createElement('div');
        row.className = 'row';
        var label = document.createElement('span');
        label.className = 'label';
        label.id = 'label-' + t;
        label.textContent = NAMES[t];
        var steps = document.createElement('div');
        steps.className = 'steps';
        steps.setAttribute('role', 'group');
        steps.setAttribute('aria-labelledby', label.id);
        for (var k = 0; k < 16; k++) {
          var b = document.createElement('button');
          b.type = 'button';
          b.className = 'step';
          b.setAttribute('data-track', String(t));
          b.setAttribute('data-step', String(k));
          b.setAttribute('aria-pressed', 'false');
          b.setAttribute('aria-label', NAMES[t] + ' step ' + (k + 1));
          b.textContent = String(k + 1);
          b.addEventListener('click', onStepClick);
          steps.appendChild(b);
          stepButtons[t].push(b);
        }
        row.appendChild(label);
        row.appendChild(steps);
        grid.appendChild(row);
      }
    
      function onStepClick(e) {
        var el = e.currentTarget;
        var tr = Number(el.getAttribute('data-track'));
        var st = Number(el.getAttribute('data-step'));
        game.press([tr, st]);
        draw();
      }
    
      function draw() {
        var st = game.state();
        for (var t = 0; t < 3; t++) {
          for (var k = 0; k < 16; k++) {
            var b = stepButtons[t][k];
            var on = st.pattern[t].charAt(k) === '1';
            b.classList.toggle('on', on);
            b.setAttribute('aria-pressed', on ? 'true' : 'false');
            b.classList.toggle('playhead', st.playing && k === st.playhead);
          }
        }
        for (var i = 0; i < 16; i++) {
          numEls[i].classList.toggle('current', i === st.playhead);
        }
        statusEl.textContent = st.playing ? 'Playing, step ' + (st.playhead + 1) + ' of 16' : 'Stopped';
        if (st.playing) { playBtn.setAttribute('disabled', ''); stopBtn.removeAttribute('disabled'); }
        else { playBtn.removeAttribute('disabled'); stopBtn.setAttribute('disabled', ''); }
      }
    
      // ---- Audio ----
      var ctx = null, master = null, noiseBuffer = null;
      function ensureAudio() {
        if (!ctx) {
          var AC = window.AudioContext || window.webkitAudioContext;
          if (!AC) return;
          ctx = new AC();
          var limiter = ctx.createDynamicsCompressor();
          limiter.threshold.value = -6;
          limiter.knee.value = 0;
          limiter.ratio.value = 20;
          limiter.attack.value = 0.002;
          limiter.release.value = 0.1;
          master = ctx.createGain();
          master.gain.value = 0.4;
          master.connect(limiter);
          limiter.connect(ctx.destination);
          var len = Math.floor(ctx.sampleRate * 0.3);
          noiseBuffer = ctx.createBuffer(1, len, ctx.sampleRate);
          var data = noiseBuffer.getChannelData(0);
          for (var i = 0; i < len; i++) data[i] = Math.random() * 2 - 1;
        }
        if (ctx.state === 'suspended') ctx.resume();
      }
    
      function kick(time) {
        var osc = ctx.createOscillator();
        var g = ctx.createGain();
        osc.type = 'sine';
        osc.frequency.setValueAtTime(150, time);
        osc.frequency.exponentialRampToValueAtTime(40, time + 0.15);
        g.gain.setValueAtTime(1, time);
        g.gain.exponentialRampToValueAtTime(0.001, time + 0.3);
        osc.connect(g); g.connect(master);
        osc.start(time); osc.stop(time + 0.32);
      }
      function snare(time) {
        var src = ctx.createBufferSource();
        src.buffer = noiseBuffer;
        var hp = ctx.createBiquadFilter();
        hp.type = 'highpass'; hp.frequency.value = 1000;
        var ng = ctx.createGain();
        ng.gain.setValueAtTime(0.7, time);
        ng.gain.exponentialRampToValueAtTime(0.001, time + 0.18);
        src.connect(hp); hp.connect(ng); ng.connect(master);
        src.start(time); src.stop(time + 0.2);
        var osc = ctx.createOscillator();
        var og = ctx.createGain();
        osc.type = 'triangle';
        osc.frequency.setValueAtTime(180, time);
        og.gain.setValueAtTime(0.5, time);
        og.gain.exponentialRampToValueAtTime(0.001, time + 0.1);
        osc.connect(og); og.connect(master);
        osc.start(time); osc.stop(time + 0.12);
      }
      function hat(time) {
        var src = ctx.createBufferSource();
        src.buffer = noiseBuffer;
        var hp = ctx.createBiquadFilter();
        hp.type = 'highpass'; hp.frequency.value = 7000;
        var g = ctx.createGain();
        g.gain.setValueAtTime(0.35, time);
        g.gain.exponentialRampToValueAtTime(0.001, time + 0.05);
        src.connect(hp); hp.connect(g); g.connect(master);
        src.start(time); src.stop(time + 0.06);
      }
      function sound(hits) {
        if (!ctx) return;
        var time = ctx.currentTime + 0.005;
        for (var i = 0; i < hits.length; i++) {
          if (hits[i] === 0) kick(time);
          else if (hits[i] === 1) snare(time);
          else if (hits[i] === 2) hat(time);
        }
      }
    
      function onTick() {
        game.press('tick');
        var st = game.state();
        if (st.playing) sound(st.hits);
        draw();
      }
    
      function startPlayback() {
        if (game.state().playing) return;
        ensureAudio();
        game.press('play');
        var st = game.state();
        sound(st.hits);
        if (timer !== null) clearInterval(timer);
        timer = setInterval(onTick, 125);
        announceEl.textContent = 'Playing';
        draw();
      }
    
      function stopPlayback() {
        var wasPlaying = game.state().playing;
        game.press('stop');
        if (timer !== null) { clearInterval(timer); timer = null; }
        if (wasPlaying) announceEl.textContent = 'Stopped';
        draw();
      }
    
      playBtn.addEventListener('click', startPlayback);
      stopBtn.addEventListener('click', stopPlayback);
      document.addEventListener('visibilitychange', function () {
        if (document.hidden && game.state().playing) stopPlayback();
      });
    
      draw();
    })();
    </script>
    </body>
    </html>
  • Grow a branching plantPassed
    Build a plant that grows by a rewrite rule (an L-system) as one web page: a heading, a canvas that draws the plant, a Grow button and a Reset button.
    
    In <script id="game">, define createGame() returning an object with grow() and state(). grow() takes no argument. state() returns {generation, text, segments}: generation is a number, text is a string, and segments is a list with one [x1, y1, x2, y2] entry for each F in text, in the order the Fs appear in text. [x1, y1] is the cell a segment starts from and [x2, y2] the cell it ends on.
    
    The rules, exactly:
    1. A pen starts at [0, 0] facing north, which is heading 6. Headings are numbered 0 to 7 clockwise, each one a step [dx, dy] with y growing downward: 0 [1, 0] east, 1 [1, 1] south-east, 2 [0, 1] south, 3 [-1, 1] south-west, 4 [-1, 0] west, 5 [-1, -1] north-west, 6 [0, -1] north, 7 [1, -1] north-east.
    2. The text starts as F, at generation 0. The pen reads the text from left to right. F moves the pen one step along its heading and adds the segment [x1, y1, x2, y2] for that step. + adds 1 to the heading and - subtracts 1, both modulo 8. [ saves the pen's position and heading. ] restores the last saved position and heading and forgets them. Any other symbol does nothing.
    3. grow() rewrites the text in one pass: every F becomes F[[--F]+F[++F]]F, and every other symbol stays as it is. The Fs that the rule adds are not rewritten in that pass. Then generation goes up by 1.
    4. segments is what the pen draws over the new text, starting again at [0, 0] facing north, as in rule 1.
    5. At the start, generation is 0, text is "F" and segments is [[0, 0, 0, -1]].
    6. grow() at generation 4 changes nothing: generation, text and segments stay as they are.
    
    The site calls grow() five times in a row, and reads state() before the first call and after each call, so every state must match these rules. The fifth call is made at generation 4. Keep the rule in the game script as one string, written exactly as rule 3 gives it: the site also runs the script with another rule in its place, and its states must follow that rule.
    
    The page: a heading (an <h1>) reading exactly "Grow a branching plant". Below it, one canvas draws each segment as a line from its start point to its end point, with the context's own moveTo, lineTo and stroke (not Path2D). The canvas draws nothing else: no other shapes, no text and no images. The drawing has the shape the segments give, with north up on the canvas: one scale on both axes, fitted to the canvas and centred. Each drawing starts by clearing the whole canvas (clearRect over all of it, or setting the canvas's width), so only the new plant is on it. Each press of Grow draws the whole plant again, at once, with one lineTo for each segment: no animation frames and no delays. The plant is drawn when the page loads, and Reset draws the stem again within a tenth of a second.
    Grow is a <button id="grow"> reading exactly "Grow". A press calls grow(), then draws and shows the new state, and Grow is disabled at generation 4. Reset is a <button id="reset"> reading exactly "Reset". A press calls createGame() for a new plant, draws it, and enables Grow again. Wire both with addEventListener('click', ...).
    A status line, an element with role="status", reads "Generation g of 4, n segments", where g is the generation and n the number of segments (the word is "segment" when n is 1), and it changes after each press.
    
    Look: plain and tidy, like a small app. A light, warm off-white page, the canvas in a white card with a thin border, the plant in dark ink, Grow as the main button and Reset as an outlined button under the card. The page must work at 390 px and at 1280 px wide with no sideways scrolling.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not use document, window, localStorage, sessionStorage or any timer, because the site runs that script on its own and plays the game through createGame(). The script is at most 20,000 characters. Wire the page in another <script>. Neither script may use eval or Function, reach Function through a constructor, or give a timer text to run; and neither may read window, self, globalThis, top, parent, frames or this with square brackets. A constructor() method in a class is fine, and so is a constructor key in an object; reading a constructor property, as x.constructor or x['constructor'], is not. A timer is given a function: one written in the call, or one the page declares by name. Square brackets take a number or a name, never quoted text, and window is used only as window.name.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Grow a branching plant</title>
    <style>
      * { box-sizing: border-box; }
      body { margin: 0; font-family: system-ui, sans-serif; background: #f7f3ea; color: #24211c; }
      main { max-width: 40rem; margin: 0 auto; padding: 1.5rem 1rem 2rem; }
      h1 { font-size: 1.6rem; margin: 0 0 1rem; }
      .card { background: #fff; border: 1px solid #ddd5c6; border-radius: 10px; padding: 0.75rem; }
      canvas { display: block; width: 100%; height: auto; aspect-ratio: 1 / 1; }
      #status { margin: 0.75rem 0 0; color: #5b554b; font-variant-numeric: tabular-nums; }
      .buttons { display: flex; flex-wrap: wrap; gap: 0.6rem; margin-top: 1rem; }
      button { font: inherit; font-weight: 600; padding: 0.55rem 1.4rem; border-radius: 8px; cursor: pointer; }
      #grow { background: #2f5d3a; color: #fff; border: 2px solid #2f5d3a; }
      #grow:disabled { background: #c9c3b6; border-color: #c9c3b6; color: #6b665d; cursor: default; }
      #reset { background: transparent; color: #2f5d3a; border: 2px solid #2f5d3a; }
      button:focus-visible { outline: 3px solid #e0a43a; outline-offset: 2px; }
    </style>
    </head>
    <body>
    <main>
      <h1>Grow a branching plant</h1>
      <div class="card">
        <canvas id="plant" width="600" height="600" aria-label="Drawing of the plant"></canvas>
        <p id="status" role="status">Generation 0 of 4, 1 segment</p>
      </div>
      <div class="buttons">
        <button type="button" id="grow">Grow</button>
        <button type="button" id="reset">Reset</button>
      </div>
    </main>
    
    <script id="game">
    function createGame() {
      var RULE = 'F[[--F]+F[++F]]F';
      var MAX_GENERATION = 4;
      var STEPS = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]];
      var generation = 0;
      var text = 'F';
      var segments = trace(text);
    
      function trace(t) {
        var x = 0, y = 0, h = 6;
        var saved = [];
        var out = [];
        for (var i = 0; i < t.length; i++) {
          var ch = t.charAt(i);
          if (ch === 'F') {
            var nx = x + STEPS[h][0];
            var ny = y + STEPS[h][1];
            out.push([x, y, nx, ny]);
            x = nx; y = ny;
          } else if (ch === '+') {
            h = (h + 1) % 8;
          } else if (ch === '-') {
            h = (h + 7) % 8;
          } else if (ch === '[') {
            saved.push([x, y, h]);
          } else if (ch === ']') {
            if (saved.length) {
              var p = saved.pop();
              x = p[0]; y = p[1]; h = p[2];
            }
          }
        }
        return out;
      }
    
      function grow() {
        if (generation >= MAX_GENERATION) return;
        var next = '';
        for (var i = 0; i < text.length; i++) {
          var ch = text.charAt(i);
          next += ch === 'F' ? RULE : ch;
        }
        text = next;
        generation += 1;
        segments = trace(text);
      }
    
      function state() {
        return {
          generation: generation,
          text: text,
          segments: segments.map(function (s) { return [s[0], s[1], s[2], s[3]]; })
        };
      }
    
      return { grow: grow, state: state };
    }
    </script>
    
    <script>
    (function () {
      var game = createGame();
      var canvas = document.getElementById('plant');
      var ctx = canvas.getContext('2d');
      var growBtn = document.getElementById('grow');
      var resetBtn = document.getElementById('reset');
      var statusEl = document.getElementById('status');
    
      function draw(st) {
        var W = canvas.width, H = canvas.height;
        ctx.clearRect(0, 0, W, H);
        var segs = st.segments;
        if (!segs.length) return;
        var minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
        for (var i = 0; i < segs.length; i++) {
          var s = segs[i];
          minX = Math.min(minX, s[0], s[2]); maxX = Math.max(maxX, s[0], s[2]);
          minY = Math.min(minY, s[1], s[3]); maxY = Math.max(maxY, s[1], s[3]);
        }
        var pad = 24;
        var w = maxX - minX, h = maxY - minY;
        var sx = w > 0 ? (W - 2 * pad) / w : Infinity;
        var sy = h > 0 ? (H - 2 * pad) / h : Infinity;
        var scale = Math.min(sx, sy);
        if (!isFinite(scale)) scale = 1;
        var ox = W / 2 - (minX + w / 2) * scale;
        var oy = H / 2 - (minY + h / 2) * scale;
        ctx.strokeStyle = '#24311f';
        ctx.lineWidth = Math.max(1, Math.min(4, scale / 6));
        ctx.lineCap = 'round';
        ctx.beginPath();
        for (var j = 0; j < segs.length; j++) {
          var g = segs[j];
          ctx.moveTo(ox + g[0] * scale, oy + g[1] * scale);
          ctx.lineTo(ox + g[2] * scale, oy + g[3] * scale);
        }
        ctx.stroke();
      }
    
      function show() {
        var st = game.state();
        draw(st);
        var n = st.segments.length;
        statusEl.textContent = 'Generation ' + st.generation + ' of 4, ' + n + (n === 1 ? ' segment' : ' segments');
        growBtn.disabled = st.generation >= 4;
      }
    
      growBtn.addEventListener('click', function () {
        game.grow();
        show();
      });
      resetBtn.addEventListener('click', function () {
        game = createGame();
        show();
      });
      show();
    })();
    </script>
    </body>
    </html>
  • Falling sandPassed
    Build a page called Falling sand: a 40 by 30 board drawn on a canvas. Sand falls one frame at a time and slides off the edges of piles. Pressing or dragging on the board pours sand, Play runs the frames, and Step runs one.
    
    In <script id="game">, define createGame(). It returns an object with play(move) and state(). move is "step" (run one frame) or [x, y] (pour one grain of sand into column x, row y). state() returns {frame, cells}: frame is the number of frames run so far (a pour is not a frame), and cells is 30 rows of 40 numbers, top row first: 0 is empty, 1 is sand, 2 is wall. Column x runs 0 to 39, left to right; row y runs 0 to 29, top to bottom.
    
    The start, exactly (both ends of each run are included):
    1. frame is 0. Row 29 is all wall.
    2. Walls: row 18, columns 4 to 10; column 34, rows 20 to 25; row 21, columns 16 to 21.
    3. Sand: column 15, row 1; row 2, columns 12 to 18; row 3, columns 11 to 19; row 4, columns 10 to 20; row 5, columns 11 to 19; row 6, columns 12 to 18; column 15, row 7.
    4. Every other cell is empty.
    
    The rules, exactly:
    1. A pour [x, y] puts one grain in that cell if it is empty; a cell holding sand or wall, or outside the grid, is not empty, so the pour does nothing.
    2. A step runs one frame, using frame as it is before the step, then frame goes up by 1. A frame scans the rows from row 28 up to row 0. Within a row it scans the columns from left to right when frame is even, and from right to left when frame is odd.
    3. Each sand cell the scan reaches moves at most once: to (x, y+1) if that cell is empty; otherwise to (x-1, y+1) if that is empty; otherwise to (x+1, y+1) if that is empty; otherwise it stays. Anything outside the grid counts as wall.
    4. Each check reads the cells as they are at that moment: a grain that has moved leaves its cell empty, and a cell an earlier grain filled in this frame is not empty.
    
    The site plays a list of moves through play() and checks state() after each one. Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the game logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and plays the game through createGame(). Wire the page in another <script>. Do not run a string as code: no eval, no Function (not even as a function's constructor property), no timer given a string, no javascript: address, and no script element made from text. Network requests are refused, and the game script is at most 20,000 characters.
    
    The page: a canvas with the id board and the width and height attributes 640 and 480. The board may be shown at any size and place on the page: a press or drag finds its cell from where the board is on screen not from its 640 by 480 pixels. A press on the board pours one grain into the cell under the pointer. A drag pours into every cell on the straight line from the cell the pointer left to the cell it reached, both ends included (Bresenham's line algorithm). Buttons with the ids play, step and reset. play runs one frame about every 50 ms, and its label reads Pause while it runs; pressing it again pauses, and the label reads Play. step runs one frame. reset calls createGame() again, back to the start, and stops Play if it is running. After each pour, after each frame that Play or Step runs, and after Reset, the board is cleared or filled once, then each grain of sand is drawn with fillRect in its own cell; empty cells are not drawn one by one. One line under the board, with the id status, reads "Frame N, M grains of sand" ("1 grain of sand" for one), N is the frame and M the grains.
    
    Not checked, but wanted: keyboard pouring (arrow keys move a pour cursor when the board has focus; Space or Enter pours at it); a live region with the id say that announces Play, Pause, Step and Reset; reduced motion (prefers-reduced-motion: reduce): a press of Play runs one frame; off screen, Play pauses for real (no frame runs, the label reads Play) and resumes on return only if it was playing, and a press of Play then does nothing, while Step still runs one frame.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Falling sand</title>
    <style>
      * { box-sizing: border-box; }
      body { margin: 0; font-family: system-ui, sans-serif; background: #f6f2ea; color: #2a241c; }
      main { max-width: 44rem; margin: 0 auto; padding: 1.25rem 1rem 2rem; }
      h1 { margin: 0 0 0.5rem; font-size: 1.6rem; }
      p.help { margin: 0 0 0.9rem; color: #5d554a; }
      #board { display: block; width: 100%; height: auto; aspect-ratio: 4 / 3; border: 1px solid #cfc5b4; border-radius: 6px; background: #fffdf8; touch-action: none; cursor: crosshair; }
      #board:focus-visible { outline: 3px solid #c47a1a; outline-offset: 2px; }
      #status { margin: 0.6rem 0 0.8rem; font-variant-numeric: tabular-nums; }
      .buttons { display: flex; flex-wrap: wrap; gap: 0.5rem; }
      button { font: inherit; font-weight: 600; padding: 0.5rem 1.2rem; border-radius: 6px; border: 2px solid #3b3227; background: #fff; color: #3b3227; cursor: pointer; }
      #play { background: #3b3227; color: #fff; }
      .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
    </style>
    </head>
    <body>
    <main>
      <h1>Falling sand</h1>
      <p class="help">Press or drag on the board to pour sand. With the board focused, arrow keys move the pour cursor and Space or Enter pours.</p>
      <canvas id="board" width="640" height="480" tabindex="0" aria-label="Sand board, 40 columns by 30 rows"></canvas>
      <p id="status">Frame 0, 0 grains of sand</p>
      <div class="buttons">
        <button type="button" id="play">Play</button>
        <button type="button" id="step">Step</button>
        <button type="button" id="reset">Reset</button>
      </div>
      <div id="say" class="sr" aria-live="polite"></div>
    </main>
    
    <script id="game">
    function createGame() {
      var W = 40, H = 30;
      var cells = [];
      var frame = 0;
      var x, y;
      for (y = 0; y < H; y++) {
        var row = [];
        for (x = 0; x < W; x++) row.push(0);
        cells.push(row);
      }
      function fillRow(ry, x1, x2, v) { for (var i = x1; i <= x2; i++) cells[ry][i] = v; }
      function fillCol(cx, y1, y2, v) { for (var i = y1; i <= y2; i++) cells[i][cx] = v; }
      fillRow(29, 0, 39, 2);
      fillRow(18, 4, 10, 2);
      fillCol(34, 20, 25, 2);
      fillRow(21, 16, 21, 2);
      cells[1][15] = 1;
      fillRow(2, 12, 18, 1);
      fillRow(3, 11, 19, 1);
      fillRow(4, 10, 20, 1);
      fillRow(5, 11, 19, 1);
      fillRow(6, 12, 18, 1);
      cells[7][15] = 1;
    
      function get(cx, cy) {
        if (cx < 0 || cx >= W || cy < 0 || cy >= H) return 2;
        return cells[cy][cx];
      }
    
      function stepFrame() {
        var leftToRight = frame % 2 === 0;
        for (var cy = H - 2; cy >= 0; cy--) {
          for (var k = 0; k < W; k++) {
            var cx = leftToRight ? k : W - 1 - k;
            if (cells[cy][cx] !== 1) continue;
            var tx = null;
            if (get(cx, cy + 1) === 0) tx = cx;
            else if (get(cx - 1, cy + 1) === 0) tx = cx - 1;
            else if (get(cx + 1, cy + 1) === 0) tx = cx + 1;
            if (tx !== null) {
              cells[cy][cx] = 0;
              cells[cy + 1][tx] = 1;
            }
          }
        }
        frame += 1;
      }
    
      function pour(px, py) {
        if (typeof px !== 'number' || typeof py !== 'number') return;
        if (!Number.isInteger(px) || !Number.isInteger(py)) return;
        if (get(px, py) !== 0) return;
        cells[py][px] = 1;
      }
    
      function play(move) {
        if (move === 'step') { stepFrame(); return; }
        if (Array.isArray(move) && move.length === 2) pour(move[0], move[1]);
      }
    
      function state() {
        return { frame: frame, cells: cells.map(function (r) { return r.slice(); }) };
      }
    
      return { play: play, state: state };
    }
    </script>
    
    <script>
    (function () {
      var COLS = 40, ROWS = 30, SIZE = 16;
      var game = createGame();
      var canvas = document.getElementById('board');
      var ctx = canvas.getContext('2d');
      var playBtn = document.getElementById('play');
      var stepBtn = document.getElementById('step');
      var resetBtn = document.getElementById('reset');
      var statusEl = document.getElementById('status');
      var sayEl = document.getElementById('say');
      var timer = null;
      var resumeOnReturn = false;
      var cursor = [20, 0];
      var showCursor = false;
      var reduceMotion = false;
      try { reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches; } catch (e) { reduceMotion = false; }
    
      function say(text) { sayEl.textContent = text; }
    
      function render() {
        var st = game.state();
        ctx.fillStyle = '#fffdf8';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = '#4a4540';
        ctx.beginPath();
        var grains = 0, y, x;
        for (y = 0; y < ROWS; y++) {
          for (x = 0; x < COLS; x++) {
            if (st.cells[y][x] === 2) ctx.rect(x * SIZE, y * SIZE, SIZE, SIZE);
          }
        }
        ctx.fill();
        ctx.fillStyle = '#d9a440';
        for (y = 0; y < ROWS; y++) {
          for (x = 0; x < COLS; x++) {
            if (st.cells[y][x] === 1) {
              ctx.fillRect(x * SIZE, y * SIZE, SIZE, SIZE);
              grains++;
            }
          }
        }
        if (showCursor) {
          ctx.strokeStyle = '#c0392b';
          ctx.lineWidth = 2;
          ctx.strokeRect(cursor[0] * SIZE + 1, cursor[1] * SIZE + 1, SIZE - 2, SIZE - 2);
        }
        statusEl.textContent = 'Frame ' + st.frame + ', ' + grains + (grains === 1 ? ' grain of sand' : ' grains of sand');
      }
    
      function pourAt(cx, cy) {
        game.play([cx, cy]);
        render();
      }
    
      function cellFromEvent(e) {
        var rect = canvas.getBoundingClientRect();
        if (rect.width <= 0 || rect.height <= 0) return null;
        var cx = Math.floor((e.clientX - rect.left) / rect.width * COLS);
        var cy = Math.floor((e.clientY - rect.top) / rect.height * ROWS);
        if (cx < 0 || cx >= COLS || cy < 0 || cy >= ROWS) return null;
        return [cx, cy];
      }
    
      function line(x0, y0, x1, y1) {
        var pts = [];
        var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
        var dy = -Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
        var err = dx + dy;
        while (true) {
          pts.push([x0, y0]);
          if (x0 === x1 && y0 === y1) break;
          var e2 = 2 * err;
          if (e2 >= dy) { err += dy; x0 += sx; }
          if (e2 <= dx) { err += dx; y0 += sy; }
        }
        return pts;
      }
    
      var dragging = false;
      var last = null;
      canvas.addEventListener('pointerdown', function (e) {
        var c = cellFromEvent(e);
        if (!c) return;
        e.preventDefault();
        dragging = true;
        try { canvas.setPointerCapture(e.pointerId); } catch (err) {}
        last = c;
        pourAt(c[0], c[1]);
      });
      canvas.addEventListener('pointermove', function (e) {
        if (!dragging) return;
        var c = cellFromEvent(e);
        if (!c) return;
        if (last && c[0] === last[0] && c[1] === last[1]) return;
        var from = last || c;
        var pts = line(from[0], from[1], c[0], c[1]);
        for (var i = 0; i < pts.length; i++) pourAt(pts[i][0], pts[i][1]);
        last = c;
      });
      function endDrag() { dragging = false; last = null; }
      canvas.addEventListener('pointerup', endDrag);
      canvas.addEventListener('pointercancel', endDrag);
    
      canvas.addEventListener('focus', function () { showCursor = true; render(); });
      canvas.addEventListener('blur', function () { showCursor = false; render(); });
      canvas.addEventListener('keydown', function (e) {
        var moved = true;
        if (e.key === 'ArrowLeft') cursor[0] = Math.max(0, cursor[0] - 1);
        else if (e.key === 'ArrowRight') cursor[0] = Math.min(COLS - 1, cursor[0] + 1);
        else if (e.key === 'ArrowUp') cursor[1] = Math.max(0, cursor[1] - 1);
        else if (e.key === 'ArrowDown') cursor[1] = Math.min(ROWS - 1, cursor[1] + 1);
        else if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); pourAt(cursor[0], cursor[1]); return; }
        else moved = false;
        if (moved) { e.preventDefault(); render(); }
      });
    
      function runFrame() {
        game.play('step');
        render();
      }
      function startPlay() {
        if (timer !== null) return;
        timer = setInterval(runFrame, 50);
        playBtn.textContent = 'Pause';
      }
      function stopPlay() {
        if (timer !== null) { clearInterval(timer); timer = null; }
        playBtn.textContent = 'Play';
      }
    
      playBtn.addEventListener('click', function () {
        if (document.hidden) return;
        if (reduceMotion) { runFrame(); say('Step'); return; }
        if (timer !== null) { stopPlay(); say('Pause'); }
        else { startPlay(); say('Play'); }
      });
      stepBtn.addEventListener('click', function () {
        runFrame();
        say('Step');
      });
      resetBtn.addEventListener('click', function () {
        stopPlay();
        resumeOnReturn = false;
        game = createGame();
        render();
        say('Reset');
      });
      document.addEventListener('visibilitychange', function () {
        if (document.hidden) {
          resumeOnReturn = timer !== null;
          stopPlay();
        } else if (resumeOnReturn) {
          resumeOnReturn = false;
          startPlay();
        }
      });
    
      render();
    })();
    </script>
    </body>
    </html>
  • Focus timerPassed
    Build a focus timer as one web page. Work periods alternate with breaks, and after every few finished work periods the break is long. The page shows the name of the period, the time left, an SVG ring that empties as the time runs down, and how many work periods are done.
    
    In <script id="game">, define createGame(). It returns an object with two methods, tick(cmd) and state(). The page's own timer calls tick() once a second, and its buttons call tick('start'), tick('pause'), tick('skip') and tick('reset'). Those four exact lowercase words are commands: they change the timer and pass no time. Any other value passes one second, and only while the timer is running: no argument, null, undefined, a number, true, false, an empty text, any other text such as 'Start' or 'tick', or an object. state() returns {phase, left, running, done}: phase is 'work', 'short' or 'long'; left is the whole number of seconds left in this period; running is true or false; done is a number. The script in <script id="game"> is at most 20,000 characters.
    
    This run's lengths: work 1200 seconds (20 minutes), short break 300 seconds (5 minutes), long break 600 seconds (10 minutes). A long break follows every 4th finished work period.
    
    The rules, exactly:
    1. The timer starts in work, with left 1200, running false and done 0.
    2. 'start' sets running to true, and 'pause' sets it to false. Neither changes anything else.
    3. While running, each passed second lowers left by 1. While paused, passed seconds change nothing.
    4. When left reaches 0, the period is over at once, so state() never shows 0. The next period starts with its full length and paused (running false). Seconds passed after that change nothing until 'start'.
    5. A work period that ends this way adds 1 to done. Then a long break comes when done is a multiple of 4, otherwise a short break.
    6. 'skip' ends the current period at once, whatever left is, and the next period starts paused. A skipped work period does not add to done, and the break after it is a short break whatever done is. A skipped break is followed by work.
    7. After any break comes work. A break never adds to done.
    8. 'reset' sets left back to the full length of the current period and sets running to false. It does not change the phase or done.
    
    The page:
    - A heading, "Focus timer".
    - The name of the period, alone in an element with the id phase: Focus, Short break or Long break.
    - The time left, as mm:ss with two digits each, alone in an element with the id time. At the start of this run's work period it reads 20:00.
    - An SVG ring around the time: a circle with pathLength="100" and stroke-dasharray="100". Set its stroke-dashoffset attribute to 100 times (1 minus left divided by the full length of the current period) on every redraw. The arc is full, with an offset of 0, at the start of a period, and it is empty, with an offset of 100, when the time is up. A track circle without a stroke-dashoffset may sit under it.
    - Four buttons in one row, with the ids start, pause, skip and reset, labelled Start, Pause, Skip and Reset. Each calls tick() with its command. Start is disabled while the timer runs, and Pause is disabled while it is paused. Skip and Reset are always enabled. Below 390 px they may wrap into two rows of two.
    - The count in an element with the id count, in words: "Focus periods done: 3".
    - The page's own timer calls tick() once a second, with no argument. After every call, the page redraws from state(). When a period ends, the page may play a short chime with the Web Audio API.
    - Look: a light, warm off-white page with one white card, dark ink text and muted grey for the small labels. One accent colour, used for the Start button only. Flat fills, no gradients or shadows, no outside fonts or images: use the system font. It must look tidy at 390 px and at 1280 px wide, with no sideways scrolling.
    
    Output one complete HTML document and nothing else, with all CSS and JavaScript inline and nothing loaded from another site. Put the timer's logic, and only it, in <script id="game">: it must not touch document, window or timers, because the site runs that script on its own and drives the timer through createGame(). Do not use eval, Function or any other way of running text as code: no string given to a timer, and no script element or event-handler attribute made from text while the page runs. Put the wiring in another <script>.

    Open the page on its own. It runs in a sandbox: no network, no access to this site.

    Page source
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Focus timer</title>
    <style>
      * { box-sizing: border-box; }
      body { margin: 0; font-family: system-ui, sans-serif; background: #f7f3ec; color: #23201c; }
      main { max-width: 26rem; margin: 0 auto; padding: 1.5rem 1rem 2rem; }
      h1 { font-size: 1.5rem; margin: 0 0 1rem; text-align: center; }
      .card { background: #fff; border: 1px solid #e3dccf; border-radius: 14px; padding: 1.5rem 1rem; text-align: center; }
      .label { color: #77706a; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.06em; margin: 0; }
      #phase { font-size: 1.25rem; font-weight: 600; margin: 0.25rem 0 1rem; }
      .ring { position: relative; width: min(16rem, 100%); aspect-ratio: 1 / 1; margin: 0 auto 1.25rem; }
      .ring svg { width: 100%; height: 100%; transform: rotate(-90deg); }
      .track { stroke: #ece6db; }
      .arc { stroke: #23201c; transition: stroke-dashoffset 0.3s linear; }
      #time { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: clamp(2.2rem, 12vw, 3.2rem); font-weight: 600; font-variant-numeric: tabular-nums; }
      .buttons { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.5rem; }
      @media (max-width: 389px) { .buttons { grid-template-columns: repeat(2, 1fr); } }
      button { font: inherit; font-weight: 600; padding: 0.6rem 0.4rem; border-radius: 8px; border: 1px solid #cfc7b9; background: #fff; color: #23201c; cursor: pointer; }
      button:disabled { color: #aaa39a; border-color: #e3dccf; cursor: default; }
      #start { background: #c2562b; border-color: #c2562b; color: #fff; }
      #start:disabled { background: #e8c3b2; border-color: #e8c3b2; color: #fff; }
      #count { color: #77706a; margin: 1.25rem 0 0; }
    </style>
    </head>
    <body>
    <main>
      <h1>Focus timer</h1>
      <div class="card">
        <p class="label">Now</p>
        <p id="phase">Focus</p>
        <div class="ring">
          <svg viewBox="0 0 120 120" aria-hidden="true">
            <circle class="track" cx="60" cy="60" r="52" fill="none" stroke-width="8"></circle>
            <circle id="arc" class="arc" cx="60" cy="60" r="52" fill="none" stroke-width="8" stroke-linecap="butt" pathLength="100" stroke-dasharray="100" stroke-dashoffset="0"></circle>
          </svg>
          <div id="time" aria-live="off">20:00</div>
        </div>
        <div class="buttons">
          <button type="button" id="start">Start</button>
          <button type="button" id="pause" disabled>Pause</button>
          <button type="button" id="skip">Skip</button>
          <button type="button" id="reset">Reset</button>
        </div>
        <p id="count">Focus periods done: 0</p>
      </div>
    </main>
    
    <script id="game">
    function createGame() {
      var LENGTHS = { work: 1200, short: 300, long: 600 };
      var LONG_EVERY = 4;
      var phase = 'work';
      var left = LENGTHS.work;
      var running = false;
      var done = 0;
    
      function lengthOf(p) {
        if (p === 'short') return LENGTHS.short;
        if (p === 'long') return LENGTHS.long;
        return LENGTHS.work;
      }
    
      function begin(p) {
        phase = p;
        left = lengthOf(p);
        running = false;
      }
    
      function tick(cmd) {
        if (cmd === 'start') { running = true; return; }
        if (cmd === 'pause') { running = false; return; }
        if (cmd === 'skip') {
          begin(phase === 'work' ? 'short' : 'work');
          return;
        }
        if (cmd === 'reset') {
          left = lengthOf(phase);
          running = false;
          return;
        }
        if (!running) return;
        left -= 1;
        if (left <= 0) {
          if (phase === 'work') {
            done += 1;
            begin(done % LONG_EVERY === 0 ? 'long' : 'short');
          } else {
            begin('work');
          }
        }
      }
    
      function state() {
        return { phase: phase, left: left, running: running, done: done };
      }
    
      return { tick: tick, state: state };
    }
    </script>
    
    <script>
    (function () {
      var FULL = { work: 1200, short: 300, long: 600 };
      var NAMES = { work: 'Focus', short: 'Short break', long: 'Long break' };
      var timer = createGame();
      var phaseEl = document.getElementById('phase');
      var timeEl = document.getElementById('time');
      var arcEl = document.getElementById('arc');
      var countEl = document.getElementById('count');
      var startBtn = document.getElementById('start');
      var pauseBtn = document.getElementById('pause');
      var skipBtn = document.getElementById('skip');
      var resetBtn = document.getElementById('reset');
      var audio = null;
    
      function pad(n) { return (n < 10 ? '0' : '') + n; }
    
      function draw() {
        var s = timer.state();
        var full = FULL[s.phase] || FULL.work;
        phaseEl.textContent = NAMES[s.phase] || 'Focus';
        timeEl.textContent = pad(Math.floor(s.left / 60)) + ':' + pad(s.left % 60);
        var offset = 100 * (1 - s.left / full);
        arcEl.setAttribute('stroke-dashoffset', String(Math.round(offset * 1000) / 1000));
        countEl.textContent = 'Focus periods done: ' + s.done;
        startBtn.disabled = s.running;
        pauseBtn.disabled = !s.running;
        document.title = timeEl.textContent + ' · ' + phaseEl.textContent + ' – Focus timer';
      }
    
      function chime() {
        try {
          if (!audio) {
            var AC = window.AudioContext || window.webkitAudioContext;
            if (!AC) return;
            audio = new AC();
          }
          if (audio.state === 'suspended') audio.resume();
          var t = audio.currentTime;
          [880, 1320].forEach(function (f, i) {
            var o = audio.createOscillator();
            var g = audio.createGain();
            o.type = 'sine';
            o.frequency.value = f;
            g.gain.setValueAtTime(0.0001, t + i * 0.18);
            g.gain.exponentialRampToValueAtTime(0.2, t + i * 0.18 + 0.02);
            g.gain.exponentialRampToValueAtTime(0.0001, t + i * 0.18 + 0.6);
            o.connect(g);
            g.connect(audio.destination);
            o.start(t + i * 0.18);
            o.stop(t + i * 0.18 + 0.65);
          });
        } catch (e) {}
      }
    
      function command(cmd) {
        if (cmd === 'start' && !audio) {
          try {
            var AC = window.AudioContext || window.webkitAudioContext;
            if (AC) audio = new AC();
          } catch (e) {}
        }
        timer.tick(cmd);
        draw();
      }
    
      startBtn.addEventListener('click', function () { command('start'); });
      pauseBtn.addEventListener('click', function () { command('pause'); });
      skipBtn.addEventListener('click', function () { command('skip'); });
      resetBtn.addEventListener('click', function () { command('reset'); });
    
      setInterval(function () {
        var before = timer.state();
        timer.tick();
        var after = timer.state();
        if (before.running && (after.phase !== before.phase || after.left > before.left)) chime();
        draw();
      }, 1000);
    
      draw();
    })();
    </script>
    </body>
    </html>
Writing code 3 of 3
  • Merge intervalsPassed
    Write a JavaScript function mergeIntervals(intervals). intervals is an array of [start, end] pairs of integers with start <= end, in any order, possibly empty. Return a new array of the merged intervals sorted by start: intervals that overlap or touch (one ends where the next starts) become one. Do not change the input array or its pairs.
    
    mergeIntervals([[8, 10], [1, 3], [2, 6], [6, 7]]) returns [[1, 7], [8, 10]].
    
    Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.
    ```js
    function mergeIntervals(intervals) {
      const sorted = intervals
        .map(function (p) { return [p[0], p[1]]; })
        .sort(function (a, b) { return a[0] - b[0] || a[1] - b[1]; });
      const out = [];
      for (const cur of sorted) {
        const last = out[out.length - 1];
        if (last && cur[0] <= last[1]) {
          if (cur[1] > last[1]) last[1] = cur[1];
        } else {
          out.push([cur[0], cur[1]]);
        }
      }
      return out;
    }
    ```
  • An LRU cachePassed
    Write a JavaScript class LRUCache: a least-recently-used cache of integer keys and values.
    
    - new LRUCache(capacity): capacity is an integer of at least 1.
    - get(key) returns the value stored for key, or -1 if there is none. A get that finds the key makes it the most recently used.
    - put(key, value) stores the value (replacing any value already there) and makes key the most recently used. If that leaves more than capacity keys, the least recently used key is removed.
    
    get and put should take constant time on average.
    
    Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.
    ```js
    class LRUCache {
      constructor(capacity) {
        this.capacity = capacity;
        this.map = new Map();
      }
    
      get(key) {
        if (!this.map.has(key)) return -1;
        const value = this.map.get(key);
        this.map.delete(key);
        this.map.set(key, value);
        return value;
      }
    
      put(key, value) {
        if (this.map.has(key)) this.map.delete(key);
        this.map.set(key, value);
        while (this.map.size > this.capacity) {
          const oldest = this.map.keys().next().value;
          this.map.delete(oldest);
        }
      }
    }
    ```
  • Evaluate arithmeticPassed
    Write a JavaScript function evaluate(expr) that returns the value of an arithmetic expression given as a string. The expression has non-negative integers, the operators + - * /, parentheses, unary minus (as in -3, - -3, 2 * -3 or -(1 + 2)) and spaces anywhere between tokens. * and / bind tighter than + and -, and operators of the same kind group from the left. / is integer division that truncates toward zero: 7 / 2 is 3 and -7 / 2 is -3. Dividing by zero must throw an Error. Do not use eval or Function.
    
    evaluate("2 + 3 * (4 - 6) / 4") returns 1.
    
    Reply with one ```js code block holding plain JavaScript (no imports, no exports, no DOM, no timers). The site runs it with hidden tests.
    ```js
    function evaluate(expr) {
      const tokens = [];
      let i = 0;
      while (i < expr.length) {
        const ch = expr[i];
        if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') { i++; continue; }
        if (ch >= '0' && ch <= '9') {
          let j = i;
          while (j < expr.length && expr[j] >= '0' && expr[j] <= '9') j++;
          tokens.push({ type: 'num', value: parseInt(expr.slice(i, j), 10) });
          i = j;
          continue;
        }
        if ('+-*/()'.indexOf(ch) !== -1) {
          tokens.push({ type: 'op', value: ch });
          i++;
          continue;
        }
        throw new Error('Unexpected character: ' + ch);
      }
    
      let pos = 0;
      function peek() { return tokens[pos]; }
      function isOp(v) { const t = tokens[pos]; return t && t.type === 'op' && t.value === v; }
    
      function parseExpr() {
        let left = parseTerm();
        while (isOp('+') || isOp('-')) {
          const op = tokens[pos++].value;
          const right = parseTerm();
          left = op === '+' ? left + right : left - right;
        }
        return left;
      }
    
      function parseTerm() {
        let left = parseUnary();
        while (isOp('*') || isOp('/')) {
          const op = tokens[pos++].value;
          const right = parseUnary();
          if (op === '*') {
            left = left * right;
          } else {
            if (right === 0) throw new Error('Division by zero');
            left = Math.trunc(left / right);
          }
        }
        return left;
      }
    
      function parseUnary() {
        if (isOp('-')) { pos++; return -parseUnary(); }
        if (isOp('+')) { pos++; return parseUnary(); }
        return parsePrimary();
      }
    
      function parsePrimary() {
        const t = peek();
        if (!t) throw new Error('Unexpected end of expression');
        if (t.type === 'num') { pos++; return t.value; }
        if (t.value === '(') {
          pos++;
          const v = parseExpr();
          if (!isOp(')')) throw new Error('Missing )');
          pos++;
          return v;
        }
        throw new Error('Unexpected token: ' + t.value);
      }
    
      const result = parseExpr();
      if (pos !== tokens.length) throw new Error('Unexpected token: ' + tokens[pos].value);
      return result === 0 ? 0 : result;
    }
    ```
Fixing code 2 of 2
  • Fix the bookings modulePassed
    This JavaScript module has one bug. The occupancy report sometimes counts one booked night more than there is in the range it was asked about.
    
    Find it and fix it without changing anything else.
    
    ```js
    // Bookings for one holiday flat. A booking is { guest, checkIn, checkOut } with dates as "YYYY-MM-DD".
    // A guest sleeps the nights from checkIn up to, but not including, checkOut: checkOut is the day they leave,
    // and another guest may check in that same day.
    
    function dayNumber(date) {
      const [y, m, d] = date.split('-').map(Number);
      return Date.UTC(y, m - 1, d) / 86400000;
    }
    
    function toDate(day) {
      return new Date(day * 86400000).toISOString().slice(0, 10);
    }
    
    function nights(booking) {
      return dayNumber(booking.checkOut) - dayNumber(booking.checkIn);
    }
    
    function overlaps(a, b) {
      return dayNumber(a.checkIn) < dayNumber(b.checkOut) && dayNumber(b.checkIn) < dayNumber(a.checkOut);
    }
    
    function canBook(bookings, request) {
      if (nights(request) < 1) return false;
      for (const booking of bookings) {
        if (overlaps(booking, request)) return false;
      }
      return true;
    }
    
    function isBooked(bookings, day) {
      return bookings.some((b) => dayNumber(b.checkIn) <= day && day < dayNumber(b.checkOut));
    }
    
    // The nights from `from` up to, but not including, `to` that someone has booked.
    function bookedNights(bookings, from, to) {
      let count = 0;
      for (let day = dayNumber(from); day <= dayNumber(to); day++) {
        if (isBooked(bookings, day)) count++;
      }
      return count;
    }
    
    // The first night on or after `from` that nobody has booked, as "YYYY-MM-DD".
    function firstFreeNight(bookings, from) {
      let day = dayNumber(from);
      while (isBooked(bookings, day)) day++;
      return toDate(day);
    }
    
    // The price in cents: Friday and Saturday nights at rates.weekend, every other night at rates.weekday.
    function price(booking, rates) {
      let total = 0;
      for (let day = dayNumber(booking.checkIn); day < dayNumber(booking.checkOut); day++) {
        const weekday = new Date(day * 86400000).getUTCDay();
        total += weekday === 5 || weekday === 6 ? rates.weekend : rates.weekday;
      }
      return total;
    }
    ```
    
    Reply with the whole corrected module in one ```js code block, with the same function names.
    ```js
    // Bookings for one holiday flat. A booking is { guest, checkIn, checkOut } with dates as "YYYY-MM-DD".
    // A guest sleeps the nights from checkIn up to, but not including, checkOut: checkOut is the day they leave,
    // and another guest may check in that same day.
    
    function dayNumber(date) {
      const [y, m, d] = date.split('-').map(Number);
      return Date.UTC(y, m - 1, d) / 86400000;
    }
    
    function toDate(day) {
      return new Date(day * 86400000).toISOString().slice(0, 10);
    }
    
    function nights(booking) {
      return dayNumber(booking.checkOut) - dayNumber(booking.checkIn);
    }
    
    function overlaps(a, b) {
      return dayNumber(a.checkIn) < dayNumber(b.checkOut) && dayNumber(b.checkIn) < dayNumber(a.checkOut);
    }
    
    function canBook(bookings, request) {
      if (nights(request) < 1) return false;
      for (const booking of bookings) {
        if (overlaps(booking, request)) return false;
      }
      return true;
    }
    
    function isBooked(bookings, day) {
      return bookings.some((b) => dayNumber(b.checkIn) <= day && day < dayNumber(b.checkOut));
    }
    
    // The nights from `from` up to, but not including, `to` that someone has booked.
    function bookedNights(bookings, from, to) {
      let count = 0;
      for (let day = dayNumber(from); day < dayNumber(to); day++) {
        if (isBooked(bookings, day)) count++;
      }
      return count;
    }
    
    // The first night on or after `from` that nobody has booked, as "YYYY-MM-DD".
    function firstFreeNight(bookings, from) {
      let day = dayNumber(from);
      while (isBooked(bookings, day)) day++;
      return toDate(day);
    }
    
    // The price in cents: Friday and Saturday nights at rates.weekend, every other night at rates.weekday.
    function price(booking, rates) {
      let total = 0;
      for (let day = dayNumber(booking.checkIn); day < dayNumber(booking.checkOut); day++) {
        const weekday = new Date(day * 86400000).getUTCDay();
        total += weekday === 5 || weekday === 6 ? rates.weekend : rates.weekday;
      }
      return total;
    }
    ```
  • Fix the CSV readerPassed
    This JavaScript module has one bug. A doubled quote inside a quoted field is read wrongly: the line "a""b",c comes back as one field, a"b,c, instead of two fields, a"b and c.
    
    Find it and fix it without changing anything else.
    
    ```js
    // Reads CSV the way spreadsheets write it: fields are separated by commas, a field may be wrapped in
    // double quotes so it can hold commas, and "" inside a quoted field stands for one double quote.
    // Fields are not trimmed. Empty lines are skipped.
    
    function parseLine(line) {
      const fields = [];
      let field = '';
      let quoted = false;
      for (let i = 0; i < line.length; i++) {
        const ch = line[i];
        if (quoted) {
          if (ch === '"') {
            if (line[i + 1] === '"') {
              field += '"';
            } else {
              quoted = false;
            }
          } else {
            field += ch;
          }
        } else if (ch === '"') {
          quoted = true;
        } else if (ch === ',') {
          fields.push(field);
          field = '';
        } else {
          field += ch;
        }
      }
      fields.push(field);
      return fields;
    }
    
    function parseCSV(text) {
      return text.split(/\r?\n/).filter((line) => line !== '').map(parseLine);
    }
    
    // Each row after the header as an object keyed by the header's names; a missing field is ''.
    function toObjects(text) {
      const [header, ...rows] = parseCSV(text);
      return rows.map((row) => {
        const record = {};
        header.forEach((name, i) => {
          record[name] = i < row.length ? row[i] : '';
        });
        return record;
      });
    }
    
    // The sum of a column's numbers; fields that are not numbers count as 0.
    function sumColumn(text, name) {
      return toObjects(text).reduce((total, record) => total + (Number(record[name]) || 0), 0);
    }
    ```
    
    Reply with the whole corrected module in one ```js code block, with the same function names.
    ```js
    // Reads CSV the way spreadsheets write it: fields are separated by commas, a field may be wrapped in
    // double quotes so it can hold commas, and "" inside a quoted field stands for one double quote.
    // Fields are not trimmed. Empty lines are skipped.
    
    function parseLine(line) {
      const fields = [];
      let field = '';
      let quoted = false;
      for (let i = 0; i < line.length; i++) {
        const ch = line[i];
        if (quoted) {
          if (ch === '"') {
            if (line[i + 1] === '"') {
              field += '"';
              i++;
            } else {
              quoted = false;
            }
          } else {
            field += ch;
          }
        } else if (ch === '"') {
          quoted = true;
        } else if (ch === ',') {
          fields.push(field);
          field = '';
        } else {
          field += ch;
        }
      }
      fields.push(field);
      return fields;
    }
    
    function parseCSV(text) {
      return text.split(/\r?\n/).filter((line) => line !== '').map(parseLine);
    }
    
    // Each row after the header as an object keyed by the header's names; a missing field is ''.
    function toObjects(text) {
      const [header, ...rows] = parseCSV(text);
      return rows.map((row) => {
        const record = {};
        header.forEach((name, i) => {
          record[name] = i < row.length ? row[i] : '';
        });
        return record;
      });
    }
    
    // The sum of a column's numbers; fields that are not numbers count as 0.
    function sumColumn(text, name) {
      return toObjects(text).reduce((total, record) => total + (Number(record[name]) || 0), 0);
    }
    ```
Planning and data 3 of 3
  • A query over hidden dataPassed
    Write one SQLite query that answers the question below. The site runs it on its own copy of these tables, filled with rows you have not seen.
    
    ```sql
    CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL);
    CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers(id),
                         placed TEXT NOT NULL,  -- 'YYYY-MM-DD'
                         status TEXT NOT NULL); -- 'delivered', 'cancelled' or 'pending'
    CREATE TABLE items (order_id INTEGER NOT NULL REFERENCES orders(id), product TEXT NOT NULL,
                        quantity INTEGER NOT NULL, price_cents INTEGER NOT NULL);  -- price_cents: for one unit
    ```
    
    Question: For each product, how many different customers bought it in a delivered order. Columns: product, customers. Only products with at least 2 such customers. Most customers first, then product name A to Z.
    
    Reply with only the query, in one ```sql code block: one SELECT statement (WITH is fine), nothing that changes the database.
    ```sql
    SELECT i.product AS product,
           COUNT(DISTINCT o.customer_id) AS customers
    FROM items AS i
    JOIN orders AS o ON o.id = i.order_id
    WHERE o.status = 'delivered'
    GROUP BY i.product
    HAVING COUNT(DISTINCT o.customer_id) >= 2
    ORDER BY customers DESC, product ASC;
    ```
  • Schedule five meetingsPassed
    Five people each have one meeting today: Dev, Fay, Jon, Max, Noa. The five meetings are at different times, 09:00, 10:00, 11:00, 13:00, 14:00 (in that order: 10:00 is right after 09:00, 13:00 right after 11:00), and in different rooms. The list of rooms, in order: Birch, Maple, Oak, Rowan, Willow.
    
    1. Max is not in Rowan.
    2. Dev's and Jon's rooms are not next to each other on the list of rooms.
    3. Dev is not in Maple.
    4. Jon's and Noa's rooms are not next to each other on the list of rooms.
    5. Whoever is in Oak meets earlier than Jon.
    6. Fay's and Noa's rooms are next to each other on the list of rooms.
    7. Dev meets earlier than Max.
    8. Jon meets earlier than Fay.
    9. Jon is not in Birch.
    10. Noa's meeting is in the slot right after Max's.
    
    Exactly one schedule fits every clue. Work it out, then end with exactly five lines, one per person, in this form:
    Ana: 09:00, Oak
    Jon is not in Birch, and not in Oak (the Oak person meets earlier than Jon), so Jon is in Maple, Rowan or Willow.
    - Jon in Maple: Birch and Oak cannot be Dev or Noa, so Dev and Noa take Rowan and Willow; Noa must be next to Fay, so Fay is in Oak and Noa in Rowan. But then Fay (Oak) meets earlier than Jon, against clue 8.
    - Jon in Rowan: Oak and Willow are Fay and Max; Dev (not Maple) is in Birch, Noa in Maple; Fay next to Noa means Fay in Oak. Again Fay in Oak meets before Jon, a contradiction.
    - Jon in Willow: Rowan cannot be Dev or Noa, and Max is not in Rowan, so Fay is in Rowan. Noa is next to Fay, so Noa is in Oak. Dev (not Maple) is in Birch, Max in Maple.
    Times: Noa (Oak) is earlier than Jon, Jon earlier than Fay, Max right before Noa, Dev earlier than Max. So Dev < Max < Noa < Jon < Fay, which fills the five slots in order.
    Dev: 09:00, Birch
    Max: 10:00, Maple
    Noa: 11:00, Oak
    Jon: 13:00, Willow
    Fay: 14:00, Rowan
  • A replacement in ten calls or fewerPassed
    Hi, it's cal.reyes@example.com. My kettle arrived with a cracked lid. Can you sort it out?
    1. system
      You are the support agent of Tidewell Home, working through its tools, and you may make at most 10 tool calls for one request. When an item arrives damaged: confirm which order it came in, send a replacement from the north warehouse if it has the item, else from south, else from east (check each in that order, and only as far as needed), and take the damaged item back with a return. If the return is refused, open a damage claim for the order with open_claim. Then reply to the customer with what you did, giving any reference numbers and the date the replacement ships.
    2. user
      Hi, it's cal.reyes@example.com. My kettle arrived with a cracked lid. Can you sort it out?
    3. assistant
      lookup_account({"email": "cal.reyes@example.com"})
    4. tool
      {"account_id": "AC-457", "name": "Cal Reyes"}
    5. assistant
      list_orders({"account_id": "AC-457"})
    6. tool
      {"orders": [{"order_id": "R-5219", "placed": "2026-10-13", "status": "delivered"}, {"order_id": "R-5185", "placed": "2026-10-02", "status": "delivered"}, {"order_id": "R-5754", "placed": "2026-10-24", "status": "in transit"}]}
    7. assistant
      get_order({"order_id": "R-5219"})
      get_order({"order_id": "R-5185"})
    8. tool
      {"items": [{"name": "Oak table lamp", "quantity": 1, "sku": "lamp-oak"}], "order_id": "R-5219"}
    9. tool
      {"items": [{"name": "Steel kettle", "quantity": 1, "sku": "kettle-steel"}, {"name": "Grey mug", "quantity": 2, "sku": "mug-grey"}], "order_id": "R-5185"}
    10. assistant
      check_stock({"sku": "kettle-steel", "warehouse": "north"})
    11. tool
      {"available": 0, "sku": "kettle-steel", "warehouse": "north"}
    12. assistant
      check_stock({"sku": "kettle-steel", "warehouse": "south"})
    13. tool
      {"available": 2, "sku": "kettle-steel", "warehouse": "south"}
    14. assistant
      reserve_item({"order_id": "R-5185", "sku": "kettle-steel", "warehouse": "south"})
    15. tool
      {"reservation_id": "RS-4436", "ships_on": "2026-11-14"}
    16. assistant
      create_return({"order_id": "R-5185", "reason": "Steel kettle arrived damaged (cracked lid)"})
    17. tool
      {"error": "damaged items are not returned: open a damage claim with open_claim instead"}
    18. assistant
      open_claim({"order_id": "R-5185", "reason": "Steel kettle arrived damaged (cracked lid)"})
    19. tool
      {"claim_id": "CL-5686", "order_id": "R-5185", "status": "open"}
    20. assistant
      Hi Cal, sorry your kettle arrived with a cracked lid. I've sorted it out:
      
      - I found the Steel kettle in your order R-5185.
      - A replacement Steel kettle is reserved from our south warehouse (reservation RS-4436) and ships on 2026-11-14 to your order's address. The north warehouse had none in stock.
      - Our system doesn't take damaged items back as returns, so instead I've opened a damage claim for order R-5185: claim CL-5686 (status: open). You don't need to send the damaged kettle back.
      
      Let me know if there's anything else I can help with.

Comments

Sign in or create an account to comment.