源代码及图片: jsforkidsch11.zip
主要逻辑:
显示一张地图,随机生成x,y两个数,做为宝藏在图上的坐标。玩家在图上点击,根据点击坐标与宝藏坐标的距离,给出相应的提示,以帮助玩家最终点到宝藏。
功能分解:
1. 显示地图;
2. 生成宝藏坐标;
3. 计算玩家点击坐标与宝藏坐标的距离;
4. 根据距离显示提示文字;
5. 把所有功能集成到地图的 click 事件中。
1. 显示地图
<img id="map" width=400 height=400 src="img/treasuremap.png">
2. 生成宝藏坐标
var getRandomNumber = function (size) { // 给定最大值,生成随机数
return Math.floor(Math.random() * size);
};
var target = { // 创建一个object,保存宝藏坐标
x: getRandomNumber(width),
y: getRandomNumber(height)
};
3. 计算玩家点击坐标与宝藏坐标的距离
var getDistance = function (event, target) { // 用勾股定理计算距离
var diffX = event.offsetX - target.x;
var diffY = event.offsetY - target.y;
return Math.sqrt((diffX * diffX) + (diffY * diffY));
};
4. 根据距离显示提示文字
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!";
}
};
5. click 事件
// Set up our variables
var width = 400;
var height = 400;
var clicks = 0;
// 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!");
}
});