Chinaunix首页 | 论坛 | 博客
  • 博客访问: 113789
  • 博文数量: 40
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 423
  • 用 户 组: 普通用户
  • 注册时间: 2013-01-15 11:55
文章分类

全部博文(40)

文章存档

2016年(36)

2015年(2)

2013年(2)

我的朋友

分类: jQuery

2016-03-25 13:52:54

这是jquery写的一款找宝藏的游戏,主要是根据位置判断,event.offsetX,event.offsetY的应用,代码如下

点击(此处)折叠或打开

  1. <!DOCTYPE html >
  2. <html>
  3.  <head>
  4.     <title>find the buried treasure!>
  5.     <script src=""></script>
  6.  </head>
  7.  <body>
  8.    <h1 id="heading">find the buried treasure!>
  9.    <img id="map" width="400" height="400" src="https://www.nostarch.com/images/treasuremap.png"/>
  10.    <p id="distance"></p>
  11.    <script>
  12.    // Get a random number from 0 to size
  13.      var getRandomNumber = function(size){
  14.      return Math.floor(Math.random()*size);
  15.      }
  16. // Calculate distance between click event and target    
  17.      var getDistance = function(event,target){
  18.      var diffX = event.offsetX - target.x;
  19.      var diffY = event.offsetY -target.y;
  20.      //console.log(event.offsetX);
  21.      // console.log(target.x);
  22.      return Math.sqrt((diffX * diffX) + (diffY * diffY));
  23.      };
  24.      // Get a string representing the distance
  25.      var getDistanceHint = function(distance){
  26.      if(distance < 10){
  27.          return "Boiling hot!";
  28.         }else if(distance < 20){
  29.          return "Really hot";
  30.         }else if(distance < 40){
  31.          return "Hot";
  32.         }else if(distance < 80){
  33.          return "Warm";
  34.         }else if(distance < 160){
  35.          return "Cold";
  36.         }else if(distance <320){
  37.          return "Really cold";
  38.         }else{
  39.          return "Freezing!";
  40.         }
  41.      }
  42.      // Set up our variables
  43.      var width = 400;
  44.      var height = 400;
  45.      var clicks = 0;
  46.      // Create a random target location
  47.      var target = {
  48.      x:getRandomNumber(width),
  49.      y:getRandomNumber(height)
  50.      }
  51.      // Add a click handler to the img element
  52.      $("#map").click(function(event){
  53.      clicks++;
  54.      // Get distance between click event and target
  55.      var distance = getDistance(event,target);
  56.      // Convert distance to a hint
  57.      var distanceHint = getDistanceHint(distance);
  58.      // Update the #distance element with the new hint
  59.      $("#distance").text(distanceHint);
  60.      // If the click was close enough, tell them they won
  61.      if(distance < 8){
  62.      alert("Found the treasure in " + clicks + "clicks!");
  63.      }
  64.      });
  65.    </script>
  66.  </body>
  67. </html>

阅读(723) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~