2012-10-10 42 views
0

我只是編程的初學者。在生命遊戲的執行過程中,只有最初的模式出現。我沒有在這裏使用網格。但爲此調整了矩形的大小。代碼不整齊。請提出建議讓我的代碼正常工作。生活中的遊戲代碼在javascript中的錯誤

<!DOCTYPE html> 
<html> 
    <body> 
    <canvas id="myCanvas" width="500" height="500" > 
    </canvas> 
    <script type="text/javascript"> 
    <!-- 
        var canvas = document.getElementById("myCanvas"); 
        var ctx = canvas.getContext("2d"); 
     var width= canvas.width; 
     var height = canvas.height; 

     function initial(){ 
        var ctx = canvas.getContext("2d"); 
     for(var i=0;i<width;i+=10){ 
      for(var j=0;j<height;j+=10){ 
      ctx.fillStyle="white"; 
      if(Math.random()<0.05){ 
       ctx.fillStyle="black"; 
      } 
      ctx.fillRect(i,j,9,9); 
      } 
     } 
     } 

     function fut(){ 
     var imageData = ctx.getImageData(0,0,width, height); 
     var data = imageData.data; 
     var future = []; 
     for(var y=0;y<height;y+=10){ 
      for(var x=0;x<width;x+=10){ 
      var dead = data[((width/10*y)+x)*4]; 
      var numb=0; 
      numb = life_around(x,y); 
      check_life(numb, dead,future); 
      } 
     } 

      ctx.clearRect(0, 0, width, height); 
      //ctx.putImageData(imageData, 0, 0); 
     for(var i=0;i<width;i+=10){ 
      for(var j=0;j<height;j+=10){ 
      var black =future[(width/10*y)+x)*4]; 
      ctx.fillStyle="white"; 
      if(black == 0){ 
       ctx.fillStyle="black"; 
      } 
      ctx.fillRect(i,j,9,9); 
      } 
     } 

     setTimeout(fut,1000); 
     function check_life(numb, dead,future){ 
      if (dead == 0){ 
      if((numb ==2) || (numb == 3)){ 
       future.push(0); 
       future.push(0); 
       future.push(0); 
       future.push(255); 
      } 
      } 
      if ((dead!=0)&&(numb == 3)){ 
      future.push(0); 
         future.push(0); 
         future.push(0); 
         future.push(255); 
      } 
      if((dead!=0)&&(numb!=3)){ 
         future.push(255); 
         future.push(255); 
         future.push(255); 
         future.push(255); 
      } 
     } 

     function life_around(x,y){ 
      for(var i=-10;i<20;i+=10){ 
      for(var j=-10;j<20;j+=10){ 
       if((i!=0) || (j!=0)){ 
       var data_index=((width/10*(y+i))+(x+j))*4; 
       if((data_index >= 0) && (data[data_index]==0)){ 
        numb++; 
       } 
       } 
      } 
      } 
      return numb; 
     } 
     } 

    function run(){ 
     initial(); 
     fut(); 
    } 
    //--> 
    </script> 
    <p>Game of life</p> 

    <form action=""> 
    <input type="button" value="initial" onClick="initial()" > 
    <input type="button" value="run" onClick="run()" > 
    </form> 
    </body> 
</html> 
+0

請讓小提琴http://jsfiddle.net – XMen

+0

能否請您也發佈錯誤消息顯示 – Christoph

回答

0

43號線,增加了 「(」:

var black =future[((width/10*y)+x)*4]; 
+0

謝謝,我?糾正它。 – user1497756