2017-08-06 49 views
0

爲什麼按下箭頭鍵時第二個正方形會消失? 而不是消失第二個廣場應該是第一個廣場。我檢查了每行代碼,沒有發現任何錯誤,我使用的瀏覽器是Google Chrome。爲什麼第二個正方形消失

這裏是我的代碼:

<!doctype html> 
    <html> 
    <head> 
    <title></title> 
    </head> 
    <body> 
    <canvas id="canvas" style="border:1px solid #000;"></canvas> 
    <script> 
    var canvas = document.getElementById("canvas"); 
    var ctx = canvas.getContext("2d"); 
    var width = 500; 
    var height = 500; 
    var win = false; 
    var player = { 
     x:250, 
     y:250, 
     speed:5, 
     width:100, 
     height:100 
    }; 
    var ai = { 
     x:150, 
     y:150, 
     mox:0, 
     moy:0, 
     speed:1, 
     width:50, 
     height:50 
    }; 
    canvas.width = width; 
    canvas.height = height; 
    ctx.fillRect(player.x, player.y, player.width, player.height); 
    ctx.stroke(); 
    ctx.fillRect(ai.x, ai.y, ai.width, ai.height); 
    ctx.stroke(); 
    function a() { 
     if(player.x < ai.x && win==false) { 
      ai.mox-=ai.speed; 
     } 
     if(player.x > ai.x && win==false) { 
      ai.mox = ai.speed; 
     } 
     if(player.y < ai.y && win==false) { 
      ai.moy -= ai.speed; 
     } 
     if(player.y > ai.y && win==false) { 
      ai.moy = ai.speed; 
     } 
     canvas.width = canvas.width; 
     var ctx = canvas.getContext("2d"); 
     ctx.fillRect(ai.x, ai.y, ai.width, ai.height); 
     ctx.stroke(); 
    } 
function move(e) { 
    // alert(e.keyCode); 
    if(e.keyCode==37) { 
     player.x -= player.speed; 
    } 
    if(e.keyCode==39) { 
     player.x += player.speed; 
    } 
    if(e.keyCode==38) { 
     player.y -= player.speed; 
    } 
    if(e.keyCode==40) { 
     player.y+=player.speed; 
    } 
    ai.x += ai.mox; 
    ai.y += ai.moy; 
    a(); 
    canvas.width = canvas.width; 
    var ctx = canvas.getContext("2d"); 
    ctx.fillRect(player.x, player.y, player.width, player.height); 
    ctx.stroke(); 
} 
document.onkeydown = move; 
</script> 
</body> 
</html> 

請告訴我什麼是錯我的代碼。另外一個語法檢查器告訴我它在語法上是正確的。

+0

請格式化您的代碼,因此它實際上是人類可讀的。那麼我們可能會幫助你。 – MarthyM

回答

0

這有一些問題,我會在稍後討論。 要立即解決您的問題,您需要添加

ctx.fillRect(ai.x, ai.y, ai.width, ai.height);

後,立即

ctx.fillRect(player.x, player.y, player.width, player.height);


好了,回到問題。大多數HTML5畫布遊戲都有一個tick函數,這個函數被稱爲每個x MS,但您似乎完全沒有。代碼中還有其他一些小問題,但我認爲當你瞭解更多信息時,你將能夠弄清楚這些問題。祝你好運:)

相關問題