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>
請告訴我什麼是錯我的代碼。另外一個語法檢查器告訴我它在語法上是正確的。
請格式化您的代碼,因此它實際上是人類可讀的。那麼我們可能會幫助你。 – MarthyM