原生Js做個(gè)貪吃蛇

<!doctype html>?

<html>?

<body>?

? ? <canvas id="can" width="400" height="400" style="background: Black"></canvas>?

? ? <script>?

? ? ? ? var sn = [ 42, 41 ], dz = 43, fx = 1, n, ctx = document.getElementById("can").getContext("2d");?

? ? ? ? function draw(t, c) {?

? ? ? ? ? ? ctx.fillStyle = c;?

? ? ? ? ? ? ctx.fillRect(t % 20 * 20 + 1, ~~(t / 20) * 20 + 1, 18, 18);?

? ? ? ? }?

? ? ? ? document.onkeydown = function(e) {?

? ? ? ? ? ? fx = sn[1] - sn[0] == (n = [ -1, -20, 1, 20 ][(e || event).keyCode - 37] || fx) ? fx : n?

? ? ? ? };?

? ? ? ? !function() {?

? ? ? ? ? ? sn.unshift(n = sn[0] + fx);?

? ? ? ? ? ? if (sn.indexOf(n, 1) > 0 || n<0||n>399 || fx == 1 && n % 20 == 0 || fx == -1 && n % 20 == 19)?

? ? ? ? ? ? ? ? return alert("GAME OVER");?

? ? ? ? ? ? draw(n, "Lime");?

? ? ? ? ? ? if (n == dz) {?

? ? ? ? ? ? ? ? while (sn.indexOf(dz = ~~(Math.random() * 400)) >= 0);?

? ? ? ? ? ? ? ? draw(dz, "Yellow");?

? ? ? ? ? ? } else?

? ? ? ? ? ? ? ? draw(sn.pop(), "Black");?

? ? ? ? ? ? ? ? setTimeout(arguments.callee, 130);?

? ? ? ? }();?

? ? </script>?

</body>?

</html>?

效果圖

圖片發(fā)自簡書App
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容