这是jquery写的一款找宝藏的游戏,主要是根据位置判断,event.offsetX,event.offsetY的应用,代码如下
-
<!DOCTYPE html >
-
<html>
-
<head>
-
<title>find the buried treasure!>
-
<script src=""></script>
-
</head>
-
<body>
-
<h1 id="heading">find the buried treasure!>
-
<img id="map" width="400" height="400" src="https://www.nostarch.com/images/treasuremap.png"/>
-
<p id="distance"></p>
-
<script>
-
// Get a random number from 0 to size
-
var getRandomNumber = function(size){
-
return Math.floor(Math.random()*size);
-
}
-
// Calculate distance between click event and target
-
var getDistance = function(event,target){
-
var diffX = event.offsetX - target.x;
-
var diffY = event.offsetY -target.y;
-
//console.log(event.offsetX);
-
// console.log(target.x);
-
return Math.sqrt((diffX * diffX) + (diffY * diffY));
-
};
-
// Get a string representing the distance
-
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 < 160){
-
return "Cold";
-
}else if(distance <320){
-
return "Really cold";
-
}else{
-
return "Freezing!";
-
}
-
}
-
// Set up our variables
-
var width = 400;
-
var height = 400;
-
var clicks = 0;
-
// Create a random target location
-
var target = {
-
x:getRandomNumber(width),
-
y:getRandomNumber(height)
-
}
-
// Add a click handler to the img element
-
$("#map").click(function(event){
-
clicks++;
-
// Get distance between click event and target
-
var distance = getDistance(event,target);
-
// Convert distance to a hint
-
var distanceHint = getDistanceHint(distance);
-
// Update the #distance element with the new hint
-
$("#distance").text(distanceHint);
-
// If the click was close enough, tell them they won
-
if(distance < 8){
-
alert("Found the treasure in " + clicks + "clicks!");
-
}
-
});
-
</script>
-
</body>
-
</html>
阅读(723) | 评论(0) | 转发(0) |