Home > Web Front-end > JS Tutorial > body text

How to write a snake game using JS code (detailed tutorial)

亚连
Release: 2018-06-12 14:41:15
Original
1737 people have browsed it

This article shares with you all the content of the classic Snake game using simple JS code. Friends who are interested can refer to it.

In the past, Nokia's Snake was all the rage. In an era when games were scarce, it was too difficult to implement using Java. Now, you can create a simple demo with just 20 lines of code to create a web page. Times are progressing

Full script code:

<!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>
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement click-to-load loading of five-level regions across the country in the zTree tree plug-in

How to implement node express personalization chatroom?

How to create an automatic website building project with vue (detailed tutorial)

The above is the detailed content of How to write a snake game using JS code (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!