3 ms·
Nice code! There are 4 functions that can be collapsed to save some space, since they're only called once. Also assigned document.body & setTimeout to vars. B
by bkrausz 15y ago
Nice code! There are 4 functions that can be collapsed to save some space, since they're only called once. Also assigned document.body & setTimeout to vars. Brings the size from 1090 to 966...nice to be less than 1kb!
data:text/html,<script>S=setTimeout;function f(){do z={x:Math.floor(16*Math.random()),y:Math.floor(16*Math.random())};while(g(z));return z}function h(b,e){return b.x==e.x&&b.y==e.y}function g(b){return s.filter(h.bind(this,b)).length}function i(){s.map(function(b){c.fillRect(b.x<<3,b.y<<3,8,8)})}function j(){d=m;var b={x:s[0].x+d.x,y:s[0].y+d.y},e;if(e=0>b.x||15<b.x||0>b.y||15<b.y||g(b))c.fillStyle="red",i(),S(k,5E3),e=1;e||S(j,350-5*s.length);s.unshift(b);h(s[0],a)&&(a=f())||s.pop();c.clearRect(0,0,128,128);i();c.beginPath();c.arc((a.x<<3)+4,(a.y<<3)+4,4,0,7);c.fill()}window.addEventListener("keydown",function(b){b={37:{x:-1,y:0},38:{x:0,y:-1},39:{x:1,y:0},40:{x:0,y:1}}[b.keyCode];b.x!=-d.x&&b.y!=-d.y&&(m=b)},!1);function k(){d=document.body;d.innerHTML='<canvas width=128 height=128 style="width:256px;height:256px;border:8px solid black"></canvas>';c=d.firstChild.getContext("2d");s=[{x:8,y:8},{x:7,y:8},{x:6,y:8}];a=f();m={x:1,y:0};j()}S(k,0);</script>
- SoldierB 15y agoYou can save 6 bytes by switching up the bounds checking. From "0>b.x||15<b.x||0>b.y||15<b.y" to "(b.x^16)<1||(b.y^16)<1". data:text/html,<script>S=setTimeout;function f(){do z={x:Math.floor(16*Math.random()),y:Math.floor(16*Math.random())};while(g(z));return z}function h(b,e){return b.x==e.x&&b.y==e.y}function g(b){return s.filter(h.bind(this,b)).length}function i(){s.map(function(b){c.fillRect(b.x<<3,b.y<<3,8,8)})}function j(){d=m;var b={x:s[0].x+d.x,y:s[0].y+d.y},e;if(e=(b.x^16)<1||(b.y^16)<1||g(b))c.fillStyle="red",i(),S(k,5E3),e=1;e||S(j,350-5*s.length);s.unshift(b);h(s[0],a)&&(a=f())||s.pop();c.clearRect(0,0,128,128);i();c.beginPath();c.arc((a.x<<3)+4,(a.y<<3)+4,4,0,7);c.fill()}window.addEventListener("keydown",function(b){b={37:{x:-1,y:0},38:{x:0,y:-1},39:{x:1,y:0},40:{x:0,y:1}}[b.keyCode];b.x!=-d.x&&b.y!=-d.y&&(m=b)},!1);function k(){d=document.body;d.innerHTML='<canvas width=128 height=128 style="width:256px;height:256px;border:8px solid black"></canvas>';c=d.firstChild.getContext("2d");s=[{x:8,y:8},{x:7,y:8},{x:6,y:8}];a=f();m={x:1,y:0};j()}S(k,0);</script>