<!DOCTYPE html>
<html>
<head>
<title>Find the buried treasure</title>
</head>
<body>
<h1 id="heading">Find the buried treasure in the below map</h1>
<!-- importing the treasure image from nostarch website -->
<img id="map" width="400" height="400" src="http://nostarch.com/images/treasuremap.png">
<!-- element to display the message to user -->
<p id="distance"></p>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<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!";
} else if (distance < 20) {
return "Really hot";
} else if (distance < 40) {
return "Hot";
} else if (distance < 80) {
return "Warm";
} else if (distance < 120) {
return "Luke Warm";
} else if (distance < 160) {
return "Cold";
} else if (distance < 200) {
return "Colder";
} else if (distance < 320) {
return "Really cold";
} else {
return "Freezing!";
}
};
// variables to find random numbers
var width = 400;
var height = 400;
// clicks variable is to track the no. of clicks the user will take to find treasure.
var clicks = 0;
// target is the location where the treasure was buried
var target = {
x: getRandomNumber(width),
y: getRandomNumber(height)
};
// on every click the below function calls
$("#map").click(function (event) {
clicks++;
// Finds the distance between the treasure and clicked position
var distance = getDistance(event, target);
// Responding to the user with status
var distanceHint = getDistanceHint(distance);
// Update the #distance element with the new status
$("#distance").text(distanceHint);
// If the...
JavaScript
var clickCount = 0;
var clickCountMax = 20;
document.getElementById("myGame").onclick = function(event) {
event.stopPropagation();
clickCount ++;
document.getElementById("clickCount").innerHTML = clickCount;
if(clickCount > clickCountMax) {
// game over; code to handle that
document.getElementById("clickCount").innerHTML = "Game Over";
return;
}
// game code;
};
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.