Just adding a couple of things to what has already been said:
You may have already noticed that the key presses in the snippet actually make the window scroll. That's because you haven't prevented the default behavior, which can easily do if you add a
preventDefault()for the keys that you handle:onkeydown=e=>{ //... the switch code if (e.keyCode >= 37 && e.keyCode <= 40){ e.preventDefault(); } }The
arrayMatchfunction:let arrayMatch=(array,item)=>{ for(let x of array) if(x.x==item.x&&x.y==item.y) return true; }Can be simplified using
Array.prototype.some():const arrayMatch=(array,item)=> array.some(x => x.x==item.x&&x.y==item.y);Which has a subtle benefit of returning
falsewhen it doesn't matching anything instead of returningundefined.The
moveswitchhas an assignment that you can simplify for all cases, this one:switch(snake.dir.current){ case "up": ... snake.dir.pre="up"; // <-- break; case "down": ... snake.dir.pre="down"; // <-- break; case "left": ... snake.dir.pre="left"; // <-- break; case "right": ... snake.dir.pre="right"; // <-- break; }Since the new value is always equal to the switched value, you can take the assignment off the
switchand do it afterwards:snake.dir.pre = snake.dir.current;Also note that while your indentation is mostly consistent, the closing
bracefor this switch is mispositioned.getBetweenInttreats bothminandmaxas floats by ceiling and flooring them:min = Math.ceil(min); max = Math.floor(max);But the values you pass in come from
canvas.offset.x,canvas.offset.y,canvas.widthandcanvas.heightwhich are always integer values. So there is no need to do that, you can simply use them directly.Also the name is a bit odd for me, and i would rename it to
getIntBetween.