我在使用Javascript的蛇游戏代码的一部分有麻烦。我无法理解它是如何工作的。我不明白的部分是这个:JavaScript贪吃蛇游戏ctx问题
ctx.fillStyle="black";
ctx.fillRect(0,0,canv.width,canv.height);
ctx.fillStyle="lime";
for(var i=0;i<trail.length;i++) {
ctx.fillRect(trail[i].x*gs,trail[i].y*gs,gs-2,gs-2);
if(trail[i].x==px && trail[i].y==py) {
tail = 5;
}
}
trail.push({x:px,y:py});
while(trail.length>tail) {
trail.shift();
}
if(ax==px && ay==py) {
tail++;
ax=Math.floor(Math.random()*tc);
ay=Math.floor(Math.random()*tc);
}
ctx.fillStyle="red";
ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2);
我不明白的东西是for
循环的一部分,特别是其采用了gs
变量ctx.fillRect
命令。他们为什么用-2写入?另外,Math.floor
和Math.random
函数,它们是如何工作的? 整个代码是这样的:
<canvas id="gc" width="400" height="400"> </canvas>
<script>
window.onload=function() {
canv=document.getElementById("gc");
ctx=canv.getContext("2d");
document.addEventListener("keydown",keyPush);
setInterval(game,1000/15);
}
px=py=10; //positionX ; positionY
gs=tc=20; // grid scale ; tile count
ax=ay=15; // appleX ; appleY - food for the snake
xv=yv=0; // velocityX ; velocityY
trail=[];
tail = 5;
function game() {
px+=xv;
py+=yv;
if(px<0) {
px= tc-1;
}
if(px>tc-1) {
px= 0;
}
if(py<0) {
py= tc-1;
}
if(py>tc-1) {
py= 0;
}
ctx.fillStyle="black";
ctx.fillRect(0,0,canv.width,canv.height);
ctx.fillStyle="lime";
for(var i=0;i<trail.length;i++) {
ctx.fillRect(trail[i].x*gs,trail[i].y*gs,gs-2,gs-2);
if(trail[i].x==px && trail[i].y==py) {
tail = 5;
}
}
trail.push({x:px,y:py});
while(trail.length>tail) {
trail.shift();
}
if(ax==px && ay==py) {
tail++;
ax=Math.floor(Math.random()*tc);
ay=Math.floor(Math.random()*tc);
}
ctx.fillStyle="red";
ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2);
}
function keyPush(evt) {
switch(evt.keyCode) {
case 37:
xv=-1;yv=0;
break;
case 38:
xv=0;yv=-1;
break;
case 39:
xv=1;yv=0;
break;
case 40:
xv=0;yv=1;
break;
}
}
</script>
术语'javascript'和'java'不可互换。 – khelwood
请删除'java'标签。 –
Javascript [数学文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math),您可以在其中找到所有答案。 –