Hacker News new | ask | show | jobs
by Wingy 1571 days ago
I find it fun to write scripts to play games like this, here's my solution:

    setInterval(() => {
      function jump() {
        function fireSpaceBarToDocumentElement(eventName) {
          const SPACE_BAR = 32
          const ev = new KeyboardEvent(eventName, { bubbles: true, keyCode: SPACE_BAR })
          document.documentElement.dispatchEvent(ev)
        }

        fireSpaceBarToDocumentElement('keydown')
        fireSpaceBarToDocumentElement('keyup')
      }

      function shouldJump() {
        function goingLeft() { return ball.speedX < 0 }
        function goingRight() { return ball.speedX > 0 }
        function leftPaddleAboveBall() { return ball.y < paddle1.y }
        function rightPaddleAboveBall() { return ball.y < paddle2.y }
        if (goingLeft() && leftPaddleAboveBall()) return true
        if (goingRight() && rightPaddleAboveBall()) return true
        return false
      }

      if (shouldJump()) jump()
    }, 1)