Guess the Number Game

This is a companion discussion topic for the original entry at https://www.kirupa.com/codingexercises/guess_the_number.htm

I saw the video of it yesterday again. It was fun to watch. I’m glad you used vanilla js! Kudos to you for this. The colors are good too.

2 Likes

Vanilla HTML/CSS/JS for life! :fire:

(Yes, this will make an upcoming revision of my Learning React book a bit inconsistent with what I’ve just said haha)

2 Likes

Point and click (Mouse for life!)

function rebuild(root, count) {
  const delay = 25
  const duration = 750
  let attempts = 0
  const target = Math.floor(Math.random() * count)
  const buttons = Array.from({ length: count }, (_, i) => {
    const button = document.createElement("button")
    button.textContent = i
    button.onclick = () => {
      attempts++
      if (i === target) {
        alert(`Correct! The number was ${target}! It took you ${attempts} attempt${attempts === 1 ? '!' : 's.'}`)
        rebuild(root, count)
        return
      }
      const [end, inc] = i < target ? [-1, -1] : [count, 1]
      for (let j = i; j !== end; j += inc) {
        Object.assign(buttons[j].style, {
          scale: 0,
          transition: `scale ${duration}ms cubic-bezier(0.3, -0.7, 1, 0.4) ${Math.abs(j - i)*delay}ms`,
          pointerEvents: "none"
        })
      }
    }
    return button
  })
  root.replaceChildren(...buttons)
  root.style.gridTemplateColumns = `repeat(${Math.round(Math.sqrt(count))}, 1fr)`
}

const root = document.body.appendChild(document.createElement("main"))
Object.assign(root.style, {
  display: "grid",
  overflow: "hidden",
  position: "absolute",
  top: 0,
  left: 0,
  width: "100vw",
  height: "100vh",
})
rebuild(root, 100)

The lack of semicolons at end of each statement scares me! :ghost:

Yeah I kinda go back and forth (don’t have them here, but did in the konami code exercise). I think I tend to default to not including them, especially on simpler things.

1 Like

Here’s what I got!

Invite link to Replit:
https://replit.com/join/snfretjvku-anaelirivera

And…the badge is yours congrats! There are a bunch more if you are up for trying them all :slight_smile: