Skip to content

Instantly share code, notes, and snippets.

@u5n
Last active January 8, 2020 07:04
Show Gist options
  • Save u5n/af948545560805eb7771231eb7f446c0 to your computer and use it in GitHub Desktop.
Save u5n/af948545560805eb7771231eb7f446c0 to your computer and use it in GitHub Desktop.
JavaScript very short snake game

This is a Classic Snake-Game with no logic error;

  1. Use arrowkeys to control it.
  2. index.html aimed to find how short it could be.
    • the parameter l is the size of the map
    • without para l, the code can be shorten to 429bytes
  3. short_snake_game.html aimed to give a intuitive effect of code.
  4. I know it worthless, but I find someone write an even worse code and paste on their blog
  5. the normal version for education
<canvas><script>z=document,l=13,n=l*l,d=1,f=3,s=[1],h=150,w=300,c=z.querySelector("canvas").getContext("2d"),z.onkeydown=e=>{d=s[1]-s[0]==(t=[-1,-l,1,l][e.which-37]||d)?d:t},setInterval(_=>{s.unshift(H=s[0]+d);if(H!=f)s.pop();else while(s.includes(f=0|Math.random()*n));if(-1!=s.indexOf(H,1)||1==d&&0==H%l||-1==d&&l==H%l+1||H<0||H>n)l=0;for(i=0;i<n;i++)c.fillStyle='#0'+(f==i)*9+s.includes(i)*9,c.fillRect(i%l*w/l,(i-i%l)*h/n,w/l,h/l)},1000/l)</script>
<canvas>
<script>
z=document,h=150,w=300,l=13,n=l*l,d=1,f=3,s=[1]
c=z.querySelector("canvas").getContext("2d")
z.onkeydown=e=>{d=s[1]-s[0]==(t=[-1,-l,1,l][e.which-37]||d)?d:t}
setInterval(_=>{
s.unshift(H=s[0]+d)
if(H!=f) s.pop()
else while(s.includes(f=0|Math.random()*n));
if(-1!=s.indexOf(H,1)||1==d&&0==H%l||-1==d&&l==H%l+1||H<0||H>n) l=0
for(i=0;i<n;i++){
c.fillStyle='#0'+(f==i)*9+s.includes(i)*9
c.fillRect(i%l*w/l,(i-i%l)*h/n,w/l,h/l)
}
},1000/l)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment