-
Notifications
You must be signed in to change notification settings - Fork 7
/
shorter.html
22 lines (22 loc) · 932 Bytes
/
shorter.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<canvas id="canvas" width="256" height="256" style="background: black;">
<script>
let ctx = canvas.getContext("2d");
let snake = [[8,8]], apple = [4,4], [dx,dy] = [0,0];
onkeydown = ({key}) => [dx,dy] =
{ [key]: [dx,dy], ArrowRight:[dx||1, 0], ArrowLeft:[dx||-1, 0] ,
ArrowDown: [0, dy||1], ArrowUp: [0, dy||-1] }[key];
setInterval(() => {
snake.unshift([ (snake[0][0] + dx) & 15, (snake[0][1] + dy) & 15 ]);
if(""+snake[0] == apple)
with(Math) do apple = [ floor(random()*16), floor(random()*16) ];
while(snake.some(seg => ""+seg == apple));
else if(snake.slice(1).some(seg => ""+seg == snake[0]))
snake.splice(1);
else snake.pop();
ctx.clearRect(0, 0, 256, 256);
ctx.fillStyle = "red";
ctx.fillRect(apple[0]*16, apple[1]*16, 16, 16);
ctx.fillStyle = "lime";
snake.forEach(([x,y]) => ctx.fillRect(x*16, y*16, 16, 16));
}, 125);
</script>