2015-12-24 76 views
1

點擊時嘿,這是我第一次#2!的JavaScript結束遊戲圖像

我正在構建一個小型的javascript html5遊戲,您可以在其中點擊對象,類似捶打一個鼴鼠..目標是在10秒內儘可能多地殺死「寶石綠色」和「寶石藍色」,並且當你點擊「寶石紅」時,遊戲結束並播放聲音。

我得到了大多數事情工作,除了我不能找到一種方法,使對「寶石紅」,當點擊遊戲結束。我已經試過很多的功能和聽衆..但無濟於事。可任何人都能幫我弄清楚這一點?

下面是代碼:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
    <title>HTML 5 Gem Game</title> 
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1"> 

    <style> 
     section#game { 
      width: 480px; 
      height: 800px; 
      max-width: 100%; 
      max-height: 100%; 
      overflow: hidden; 
      position: relative; 
      background-image: url('img/Splash.png'); 
      position: relative; 
      color: #ffffff; 
      font-size: 30px; 
      font-family: "arial,sans-serif"; 
     } 

     section#game .score{ 
      display: block; 
      position: absolute; 
      top: 10px; 
      left: 10px; 
     } 

     section#game .time{ 
      display: block; 
      position: absolute; 
      top: 10px; 
      right: 10px; 
     } 

     section#game .start{ 
      display: block; 
      padding-top: 40%; 
      margin: 0 auto 0 auto; 
      text-align: center; 
      width: 70%; 
      cursor: pointer; 
     } 

     section#game .start .high-scores{ 
      text-align: left; 
     } 

     section#game .gem{ 
      display: block; 
      position: absolute; 
      width: 40px; 
      height: 44px; 
      cursor: pointer; 
     } 

     section#game .gem.green{ 
      background: url('img/Gem Green.png') no-repeat top left; 
     } 

     section#game .gem.blue{ 
      background: url('img/Gem Blue.png') no-repeat top left; 
     } 

     section#game .gem.red{ 
      background: url('img/Gem Red.png') no-repeat top left; 
     } 
    </style> 
    <script> 
     function addEvent(element, event, delegate) { 
      if (typeof (window.event) != 'undefined' && element.attachEvent) 
       element.attachEvent('on' + event, delegate); 
      else 
       element.addEventListener(event, delegate, false); 
     } 

     function Game(){ 
      var game = document.querySelector("section#game"); 
      var score = game.querySelector("section#game span.score"); 
      var high_scores = game.querySelector("section#game ol.high-scores"); 
      var time = game.querySelector("section#game span.time"); 
      var start = game.querySelector("section#game span.start"); 

      function Gem(Class, Value, MaxTTL) { 
       this.Class = Class; 
       this.Value = Value; 
       this.MaxTTL = MaxTTL; 
      }; 

      var gems = new Array(); 
      gems[0] = new Gem('green', 10, 1.2); 
      gems[1] = new Gem('blue', 20, 1); 
      gems[2] = new Gem('red', 50, 0.75); 

      function Click(event) 
      { 
       if(event.preventDefault) event.preventDefault(); 
       if (event.stopPropagation) event.stopPropagation(); 
       else event.cancelBubble = true; 

       var target = event.target || event.srcElement; 

       if(target.className.indexOf('gem') > -1){ 
        var value = parseInt(target.getAttribute('data-value')); 
        var current = parseInt(score.innerHTML); 
        var audio = new Audio('music/blaster.mp3'); 
        audio.play(); 
        score.innerHTML = current + value; 
        target.parentNode.removeChild(target); 
       } 

       return false; 
      } 

      function Remove(id) { 
       var gem = game.querySelector("#" + id); 

       if(typeof(gem) != 'undefined') 
        gem.parentNode.removeChild(gem); 
      } 

      function Spawn() { 
       var index = Math.floor((Math.random() * 3)); 
       var gem = gems[index]; 

       var id = Math.floor((Math.random() * 1000) + 1); 
       var ttl = Math.floor((Math.random() * parseInt(gem.MaxTTL) * 1000) + 1000); //between 1s and MaxTTL 
       var x = Math.floor((Math.random() * (game.offsetWidth - 40))); 
       var y = Math.floor((Math.random() * (game.offsetHeight - 44))); 

       var fragment = document.createElement('span'); 
       fragment.id = "gem-" + id; 
       fragment.setAttribute('class', "gem " + gem.Class); 
       fragment.setAttribute('data-value', gem.Value); 

       game.appendChild(fragment); 

       fragment.style.left = x + "px"; 
       fragment.style.top = y + "px"; 

       setTimeout(function(){ 
        Remove(fragment.id); 
       }, ttl) 
      } 

      <!-- parse high score keeper --> 
      function HighScores() { 
       if(typeof(Storage)!=="undefined"){ 
        var scores = false; 
        if(localStorage["high-scores"]) { 
         high_scores.style.display = "block"; 
         high_scores.innerHTML = ''; 
         scores = JSON.parse(localStorage["high-scores"]); 
         scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)}); 

         for(var i = 0; i < 10; i++){ 
          var s = scores[i]; 
          var fragment = document.createElement('li'); 
          fragment.innerHTML = (typeof(s) != "undefined" ? s : ""); 
          high_scores.appendChild(fragment); 
         } 
        } 
       } else { 
        high_scores.style.display = "none"; 
       } 
      } 

      function UpdateScore() { 
       if(typeof(Storage)!=="undefined"){ 
        var current = parseInt(score.innerHTML); 
        var scores = false; 
        if(localStorage["high-scores"]) { 

         scores = JSON.parse(localStorage["high-scores"]); 
         scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)}); 

         for(var i = 0; i < 10; i++){ 
          var s = parseInt(scores[i]); 

          var val = (!isNaN(s) ? s : 0); 
          if(current > val) 
          { 
           val = current; 
           scores.splice(i, 0, parseInt(current)); 
           break; 
          } 
         } 

         scores.length = 10; 
         localStorage["high-scores"] = JSON.stringify(scores); 

        } else { 
         var scores = new Array(); 
         scores[0] = current; 
         localStorage["high-scores"] = JSON.stringify(scores); 
        } 

        HighScores(); 
       } 
      } 

      function Stop(interval) { 
       clearInterval(interval); 
      } 

      this.Start = function() { 
       score.innerHTML = "0"; 
       start.style.display = "none"; 
       var interval = setInterval(Spawn, 750); 

       var count = 10; 
       var counter = null; 

       function timer() 
       { 
        count = count-1; 
        if (count <= 0) 
        { 
         var left = document.querySelectorAll("section#game .gem"); 

         for (var i = 0; i < left.length; i++) { 
          if(left[i] && left[i].parentNode) { 
           left[i].parentNode.removeChild(left[i]); 
          } 
         } 
         Stop(interval); 
         Stop(counter); 
         time.innerHTML = "Game Over!"; 
         start.style.display = "block"; 

         UpdateScore(); 

         return; 
        } else { 
         time.innerHTML = count + "s left"; 
        } 
       } 

       counter = setInterval(timer, 1000); 

       setTimeout(function(){ 
        Stop(interval); 
       }, count * 1000) 
      }; 

      addEvent(game, 'click', Click); 
      addEvent(start, 'click', this.Start); 
      HighScores(); 
     } 

     addEvent(document, 'readystatechange', function() { 
      if (document.readyState !== "complete") 
       return true; 

      var game = new Game(); 
     }); 
    </script> 
</head> 
<body> 
    <div id="page"> 
     <section id="game"> 
      <span class="score">0</span> 
      <span class="time">0</span> 
      <span class="start">START! 
      <ol class="high-scores"></ol> 
      </span> 
     </section> 
    </div> 
</body> 
</html> 
+0

最簡單的方法可能是設置數= 10單擊寶石紅的時候。這將重複10秒的超時。 – Roberto

+0

並且我會把這個功能點擊(事件)? –

回答

0

阿萊西奧 -

你只需要你的代碼進行一些小的改動,使其工作。下面的例子可以幫助你開始正確的方向。祝你好運。

的變化:

  1. 添加ENDGAME()函數和來自計時器()函數移動停止遊戲邏輯進去。

  2. 添加一行到click()函數檢查紅寶石的點擊次數。

    if (target.className.indexOf('red') > 0) endGame("Red Gem - You win!"); 
    
  3. 聲明計數,計數器,間隔變量在你的遊戲對象的頂部。

下面的代碼還有一些小的CSS更改,用於調試,您可以刪除。

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
 
    <title>HTML 5 Gem Game</title> 
 
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1"> 
 

 
    <style> 
 

 
     section#game { 
 
      width: 480px; 
 
      height: 800px; 
 
      max-width: 100%; 
 
      max-height: 100%; 
 
      overflow: hidden; 
 
      position: relative; 
 
      background-image: url('img/Splash.png'); 
 
\t \t \t border: 1px red dotted; 
 
      position: relative; 
 
      color: red; 
 
      font-size: 30px; 
 
      font-family: "arial,sans-serif"; 
 
     } 
 

 
     section#game .score{ 
 
      display: block; 
 
      position: absolute; 
 
      top: 10px; 
 
      left: 10px; 
 
     } 
 

 
     section#game .time{ 
 
      display: block; 
 
      position: absolute; 
 
      top: 10px; 
 
      right: 10px; 
 
     } 
 

 
     section#game .start{ 
 
      display: block; 
 
      padding-top: 40%; 
 
      margin: 0 auto 0 auto; 
 
      text-align: center; 
 
      width: 70%; 
 
      cursor: pointer; 
 
     } 
 

 
     section#game .start .high-scores{ 
 
      text-align: left; 
 
     } 
 

 
     section#game .gem{ 
 
      display: block; 
 
      position: absolute; 
 
      width: 40px; 
 
      height: 44px; 
 
      cursor: pointer; 
 
     } 
 

 
     section#game .gem.green{ 
 
      background: url('img/Gem Green.png') no-repeat top left; 
 
\t \t \t background-color: green; 
 
     } 
 

 
     section#game .gem.blue{ 
 
      background: url('img/Gem Blue.png') no-repeat top left; 
 
\t \t \t background-color: blue; 
 
     } 
 

 
     section#game .gem.red{ 
 
      background: url('img/Gem Red.png') no-repeat top left; 
 
\t \t \t background-color: red; 
 
     } 
 
    </style> 
 
    <script> 
 
     function addEvent(element, event, delegate) { 
 
      if (typeof (window.event) != 'undefined' && element.attachEvent) 
 
       element.attachEvent('on' + event, delegate); 
 
      else 
 
       element.addEventListener(event, delegate, false); 
 
     } 
 

 
     function Game(){ 
 
      var game = document.querySelector("section#game"); 
 
      var score = game.querySelector("section#game span.score"); 
 
      var high_scores = game.querySelector("section#game ol.high-scores"); 
 
      var time = game.querySelector("section#game span.time"); 
 
      var start = game.querySelector("section#game span.start"); 
 
\t \t \t var interval, counter, count; 
 

 
      function Gem(Class, Value, MaxTTL) { 
 
       this.Class = Class; 
 
       this.Value = Value; 
 
       this.MaxTTL = MaxTTL; 
 
      }; 
 

 
      var gems = new Array(); 
 
      gems[0] = new Gem('green', 10, 1.2); 
 
      gems[1] = new Gem('blue', 20, 1); 
 
      gems[2] = new Gem('red', 50, 0.75); 
 

 
      function Click(event) 
 
      { 
 
       if(event.preventDefault) event.preventDefault(); 
 
       if (event.stopPropagation) event.stopPropagation(); 
 
       else event.cancelBubble = true; 
 

 
       var target = event.target || event.srcElement; 
 

 
       if(target.className.indexOf('gem') > -1){ 
 
        var value = parseInt(target.getAttribute('data-value')); 
 
        var current = parseInt(score.innerHTML); 
 
        var audio = new Audio('music/blaster.mp3'); 
 
        audio.play(); 
 
        score.innerHTML = current + value; 
 
        target.parentNode.removeChild(target); 
 
\t \t \t \t \t 
 
\t \t \t \t \t if (target.className.indexOf('red') > 0) endGame("Red Gem - You win!"); 
 
\t \t \t \t \t 
 
       } 
 

 
       return false; 
 
      } 
 

 
      function Remove(id) { 
 
       var gem = game.querySelector("#" + id); 
 

 
       if(typeof(gem) != 'undefined') 
 
        gem.parentNode.removeChild(gem); 
 
      } 
 

 
      function Spawn() { 
 
       var index = Math.floor((Math.random() * 3)); 
 
       var gem = gems[index]; 
 

 
       var id = Math.floor((Math.random() * 1000) + 1); 
 
       var ttl = Math.floor((Math.random() * parseInt(gem.MaxTTL) * 1000) + 1000); //between 1s and MaxTTL 
 
       var x = Math.floor((Math.random() * (game.offsetWidth - 40))); 
 
       var y = Math.floor((Math.random() * (game.offsetHeight - 44))); 
 

 
       var fragment = document.createElement('span'); 
 
       fragment.id = "gem-" + id; 
 
       fragment.setAttribute('class', "gem " + gem.Class); 
 
       fragment.setAttribute('data-value', gem.Value); 
 

 
       game.appendChild(fragment); 
 

 
       fragment.style.left = x + "px"; 
 
       fragment.style.top = y + "px"; 
 

 
       setTimeout(function(){ 
 
        Remove(fragment.id); 
 
       }, ttl) 
 
      } 
 

 
      <!-- parse high score keeper --> 
 
      function HighScores() { 
 
       if(typeof(Storage)!=="undefined"){ 
 
        var scores = false; 
 
        if(localStorage["high-scores"]) { 
 
         high_scores.style.display = "block"; 
 
         high_scores.innerHTML = ''; 
 
         scores = JSON.parse(localStorage["high-scores"]); 
 
         scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)}); 
 

 
         for(var i = 0; i < 10; i++){ 
 
          var s = scores[i]; 
 
          var fragment = document.createElement('li'); 
 
          fragment.innerHTML = (typeof(s) != "undefined" ? s : ""); 
 
          high_scores.appendChild(fragment); 
 
         } 
 
        } 
 
       } else { 
 
        high_scores.style.display = "none"; 
 
       } 
 
      } 
 

 
      function UpdateScore() { 
 
       if(typeof(Storage)!=="undefined"){ 
 
        var current = parseInt(score.innerHTML); 
 
        var scores = false; 
 
        if(localStorage["high-scores"]) { 
 

 
         scores = JSON.parse(localStorage["high-scores"]); 
 
         scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)}); 
 

 
         for(var i = 0; i < 10; i++){ 
 
          var s = parseInt(scores[i]); 
 

 
          var val = (!isNaN(s) ? s : 0); 
 
          if(current > val) 
 
          { 
 
           val = current; 
 
           scores.splice(i, 0, parseInt(current)); 
 
           break; 
 
          } 
 
         } 
 

 
         scores.length = 10; 
 
         localStorage["high-scores"] = JSON.stringify(scores); 
 

 
        } else { 
 
         var scores = new Array(); 
 
         scores[0] = current; 
 
         localStorage["high-scores"] = JSON.stringify(scores); 
 
        } 
 

 
        HighScores(); 
 
       } 
 
      } 
 

 
      function Stop(interval) { 
 
       clearInterval(interval); 
 
      } 
 
\t \t \t 
 
      function endGame(msg) { 
 
\t \t \t \t count = 0; 
 
\t \t \t \t Stop(interval); 
 
       Stop(counter); 
 
\t \t \t  var left = document.querySelectorAll("section#game .gem"); 
 
       for (var i = 0; i < left.length; i++) { 
 
\t \t \t \t \t if(left[i] && left[i].parentNode) { 
 
\t \t \t \t \t \t left[i].parentNode.removeChild(left[i]); 
 
        } 
 
       } 
 
       time.innerHTML = msg || "Game Over!"; 
 
       start.style.display = "block"; 
 
       UpdateScore(); 
 
\t \t \t } 
 
\t \t \t 
 
      this.Start = function() { 
 
       score.innerHTML = "0"; 
 
       start.style.display = "none"; 
 
       interval = setInterval(Spawn, 750); 
 

 
       count = 10; 
 
       counter = null; 
 

 
       function timer() 
 
       { 
 
        count = count-1; 
 
        if (count <= 0) 
 
        { 
 
         endGame(); 
 

 
         return; 
 
        } else { 
 
         time.innerHTML = count + "s left"; 
 
        } 
 
       } 
 

 
       counter = setInterval(timer, 1000); 
 

 
       setTimeout(function(){ 
 
        Stop(interval); 
 
       }, count * 1000) 
 
      }; 
 

 
      addEvent(game, 'click', Click); 
 
      addEvent(start, 'click', this.Start); 
 
      HighScores(); 
 
     } 
 

 
     addEvent(document, 'readystatechange', function() { 
 
      if (document.readyState !== "complete") 
 
       return true; 
 

 
      var game = new Game(); 
 
     }); 
 
    </script> 
 
</head> 
 
<body> 
 
    <div id="page"> 
 
     <section id="game"> 
 
      <span class="score">0</span> 
 
      <span class="time">0</span> 
 
      <span class="start">START! 
 
      <ol class="high-scores"></ol> 
 
      </span> 
 
     </section> 
 
    </div> 
 
</body> 
 
</html>

+0

Grazie mille!我無法相信所有這些簡單的修復令人頭痛的問題。謝謝! –

1

對於初學者來說,你不應該包括樣式表和整個HTML文件,因爲無論是相關的,你應該使用這種混亂的使用CSS的canvas元素和html元素,這將允許您的代碼的大小減半。此外,你應該能夠通過僅改變一些全局布爾變量設置爲false來解決這個點擊紅色寶石和當布爾變量是假的(這個if語句是屬於你的遊戲循環結束),當你調用停止(ARG)/clearInterval(ARG)。鑑於當前的代碼似乎並不有一個全局布爾變量,指示遊戲狀態(使用一個枚舉通常會是一個更清潔的解決方案,但一個簡單的布爾似乎以適應這種情況下雙關語意

+0

所以我創建一個布爾值你說的?或者改變一個現有的? –