loops - snake game move issue [javascript] -
i'm kind of new in javascript , i'm trying make snake game, make snake move automatically snake.push
, snake.shift(tail)
, tried few things , failed, foor loop
, add dy++ hy (but head moving).
with code, head move , tail shifted, move once. how smart way make keep moving desired direction by adding , removing item multidimensional array ?
var canvas = document.getelementbyid("mycanvas"); var ctx = canvas.getcontext("2d"); var snakesize=10; var snakelength = 5; var dist =2+snakesize; var dy=1; var direction = "up"; function game(){ ctx.clearrect(0,0,canvas.width,canvas.height); drawsnake() } function snakebody(x,y){ ctx.beginpath(); ctx.fillrect(x*(dist),y*(dist),snakesize,snakesize); ctx.fillstyle="red"; ctx.fill(); ctx.closepath();} function drawsnake(){ var snake = []; (var i=0;i<=snakelength;i++){ snake.push({x:i, y:canvas.height/dist/2}); } var hx = snake[snake.length-1].x var hy = snake[snake.length-1].y switch(direction){ case "down": hy++; break; case "up":{ hy--;} break; case "right": hx++ break; case "left": hx--; break; } var tail = snake.shift(); tail.x=hx; tail.y=hy; snake.push(tail); (var i=0;i<=snake.length;i++){ snakebody(snake[i].x,snake[i].y); } } setinterval(game,1000)
it turns out snake initialization code included @ beginning of drawsnake()
function.
but should processed once, when new game launched. problem snake[]
must exist in global scope of game persistent between 2 calls game()
.
you can have existing code working moving block:
var snake = []; (var i=0;i<=snakelength;i++){ snake.push({x:i, y:canvas.height/dist/2}); }
just before:
setinterval(game,1000)
there 3 other minor fixes in this jsfiddle:
- replaced
i<=snake.length
i<snake.length
(off 1 iteration) - replaced
i<=snakelength
i<snakelength
(off 1 iteration) - moved
ctx.fillstyle="red"
beforectx.fillrect()
(otherwise, 1st rectangle drawn in black)
hope helps.
Comments
Post a Comment