📜 ⬆️ ⬇️

Tiny Snake in JavaScript (30 lines of code)

After reading the article about excel in 30 lines , I had a stupid idea - to write something in 30 lines. Without hesitation he stopped at the snake .

Features:




Here is a fiddle .
')
And the code itself:

Aesthetes and perfectionists better not to watch
(function(width, height, length, current, dx, dy, x, y, hasFood, newEl){ document.body.onkeydown = function(e){ dx = (e.keyCode - 38) % 2, dy = (e.keyCode - 39) % 2; }; var timer = setInterval(function () { x = (x + dx) < 0 ? width - 1 : (x + dx) % width; y = (y + dy) < 0 ? height - 1 : (y + dy) % height; newEl = document.getElementsByClassName(y + '_' + x)[0] if(newEl.className.indexOf('s') > 0) { clearInterval(timer), alert('Game Over! Score: ' + length) }; if(newEl.className.indexOf('f') > 0) { newEl.className = newEl.className.replace(' f', ''), length++, hasFood = false; } newEl.className += ' s', newEl.setAttribute('data-n', current++); for(var i = 0, min = Infinity, item, items = document.getElementsByClassName('s'), len = items.length; i < len && len > length; i++) if(+items[i].getAttribute('data-n') < min) min = +items[i].getAttribute('data-n'), item = items[i]; if(!!item) item.className = item.className.replace(' s', ''); for(var fItem, fX, fY; !hasFood; fX = Math.round(Math.random() * 10 % width), fY = Math.round(Math.random() * 10 % height)) if(!!fX && !!fY && document.getElementsByClassName(fY + '_' + fX)[0].className.indexOf('s') < 0) hasFood = true, document.getElementsByClassName(fY + '_' + fX)[0].className += ' f'; }, 1000); })(10, 10, 5, 1, 1, 0, 0, 0, false, null); 



I admit, I saved a little by dropping the code with which I generated the markup. And the approach itself is very, very bad, but nevertheless I did it in 30 lines.
A couple of words about the “algorithm” (I understand that nobody wants to read this “code” on Resurrection):


Do not judge the code strictly and have a good weekend!

Source: https://habr.com/ru/post/202476/


All Articles