Find The Treasure!

Click around the map!

by s3ntry

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Find the treasure!</title>
  </head>
  <body>
    <h1 id="heading">Find the treasure!</h1>
    
    <img id="map" width=400 height=400 src="http://nostarch.com/images/treasuremap.png">
    <script src="https://code.jquery.com/jquery-2.1.0.js"></script>
    
    <p id="distance">Click around to find the treasure!</p>
    
    <script>
      var getRandomNumber = function (size) {
        return Math.floor(Math.random() * size)
      };
      
      var getDistance = function (event, target) {
        var diffX = event.offsetX - target.x;
        var diffY = event.offsetY - target.y;
        return Math.sqrt((diffX * diffX) + (diffY * diffY));
      };
      
      var getDistanceHint = function (distance) {
        if (distance < 10) {
          return ("Boiling hot!")
        };
        if (distance < 20) {
          return ("Really hot!")
        };
        if (distance < 40) {
          return ("Hot")
        };
        if (distance < 80) {
          return ("Warm")
        };
        if (distance < 160) {
          return ("Cold")
        };
        if (distance < 320) {
          return ("Really cold!")
        } else {
          return("Freezing!")
        }
      };
      
      var width = 400;
      var height = 400;
      var clicks = 0;
      
      var target = {
        x: getRandomNumber(width),
        y: getRandomNumber(height)
      };
      
      $("#map").click(function (event) {
        clicks++;
        
        var distance = getDistance(event, target);
        var distanceHint = getDistanceHint(distance);
        
        $("#distance").text(distanceHint);
        
        if (distance < 8) {
          alert("You found the treasure in " + clicks + " clicks!");
        }
      });
    </script>
  </body>
</html>