search
HomeWeb Front-endJS Tutorialjs snake game implementation ideas and source code_javascript skills

The example in this article shares the relevant code of the js Snake game for your reference. The specific content is as follows

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>贪吃蛇小游戏</title>
  <style>
*{margin:0; padding:0;}
header {
  display: block;
  margin: 0 auto;
  width: 500px;
  text-align: center;
}
header h1 {
  font-family: Arial;
  font-weight: bold;
}
header #newGameButton {
  display: block;
  margin: 20px auto;
  width: 100px;
  padding: 10px 10px;
  background-color: #8f7a66;
  font-family: Arial;
  color: white;
  border-radius: 10px;
  text-decoration: none;
}
header #newGameButton:hover {
  background-color: #9f8b77;
}
header p {
  font-family: Arial;
  font-size: 25px;
  margin: 20px auto;
}
canvas{
  display:block; 
  border:medium double black;
  margin:4px auto;
}
  </style>
</head>
<body>
  <header>
    <h1 id="贪吃蛇小游戏">贪吃蛇小游戏</h1>
    <a href="javascript:newgame();" id="newGameButton">New Game</a>
    <p>score:<span id="score">0</span></p>
  </header>
  <canvas id="canvas">
    Your browser doesn't support the <code>canvas</code> element.
  </canvas>
  <script>
  var CANVAS = document.getElementById("canvas");
var CTX = CANVAS.getContext("2d");
var SNAKE = new Array();  //用队列模拟蛇身
var DIR = "right";        //用来控制蛇头的方向
var SIZE = 20;        //蛇身的宽度
var FOODX = 0;      //食物的x坐标
var FOODY = 0;      //食物的y坐标
var HEADX = 0;    //蛇头的x坐标
var HEADY = 0;    //蛇头的y坐标
var MAXWIDTH = 200;    //画布的高度
var MAXHEIGHT = 200;  //画布的宽度
var TIME = 400;      //蛇的速度
var SCORE = 0;      //计算玩家分数
var interval = null;

CANVAS.width = MAXWIDTH;
CANVAS.height = MAXHEIGHT;

window.onload = function(){
  newgame();
};
document.getElementById("newGameButton").click(function(){
  newgame();
});
function newgame(){
  SNAKE = [];    //用队列模拟蛇身
  DIR = "right";  //用来控制蛇头的方向
  HEADX = 0;    //蛇头的x坐标
  HEADY = 0;    //蛇头的y坐标
  SCORE = 0;
  window.clearInterval(interval);
  interval = null;
  //初始化画布
  CTX.clearRect(0, 0, MAXWIDTH, MAXHEIGHT);
  //画一条蛇
  drawSnake();
  //放置食物
  setFood();
  //移动蛇
  interval = window.setInterval(move, TIME);

}
function move(){
  switch(DIR){
    case "up":HEADY = HEADY-SIZE;break;
    case "right":HEADX = HEADX+SIZE;break;
    case "down":HEADY = HEADY+SIZE;break;
    case "left":HEADX = HEADX-SIZE;break;
  }
  if(HEADX>MAXWIDTH-SIZE || HEADY>MAXHEIGHT-SIZE || HEADX<0 || HEADY<0){
    alert("你的分数为:"+SCORE+"分,继续努力吧!失败原因:碰壁了.....");
    window.location.reload();
  }
  for(var i=1;i<SNAKE.length;i++){
    if(SNAKE[i][0] == SNAKE[0][0] && SNAKE[i][1] == SNAKE[0][1]){
      alert("你的分数为:"+SCORE+"分,继续努力吧!失败原因:撞到自己了.....");
      window.location.reload();
    }
  }
  if(SNAKE.length == MAXWIDTH *MAXHEIGHT){
    alert("好厉害!么么哒~");
    window.location.reload();
  }
  moveIn(HEADX, HEADY);//移动一格
}
document.onkeydown = function(e) { //改变蛇方向
  var code = e.keyCode - 37;
  switch(code){
    case 1 : DIR = "up";break;//上
    case 2 : DIR = "right";break;//右
    case 3 : DIR = "down";break;//下
    case 0 : DIR = "left";break;//左
  }
}
//=============================画一条蛇=======================================================
function drawSnake(){
  CTX.fillStyle = "black";
  //画蛇头
  CTX.fillRect (HEADX, HEADY, SIZE, SIZE);
  SNAKE.push([HEADX, HEADY]);
  
  //画蛇身
  switch(DIR){
    case "up": 
      drawBody(HEADX, HEADY + SIZE, HEADX, HEADY + 2 * SIZE);
      break;
    case "right": 
      drawBody(HEADX - SIZE, HEADY, HEADX - 2 * SIZE, HEADY);
      break;
    case "down": 
      drawBody(HEADX, HEADY - SIZE, HEADX, HEADY - 2 * SIZE);
      break;
    case "left": 
      drawBody(HEADX + SIZE, HEADY, HEADX + 2 * SIZE, HEADY);
      break;
  }
}
function drawBody(x1, y1, x2, y2){
  CTX.fillRect (x1, y1, SIZE, SIZE); 
  CTX.fillRect (x2, y2, SIZE, SIZE); 
  SNAKE.push([x1, y1]);
  SNAKE.push([x2, y2]);
}
//===========================放置食物==============================
function setFood(){
  do{
    FOODX = SIZE * Math.floor(Math.random() * MAXWIDTH / SIZE);
    FOODY = SIZE * Math.floor(Math.random() * MAXHEIGHT / SIZE);
  }while(foodInSnake());
  CTX.fillStyle = "red";
  CTX.fillRect (FOODX, FOODY, SIZE, SIZE);
}
function foodInSnake(){
  for (var i = 0; i < SNAKE.length; i++) {
    if(FOODX == SNAKE[i][0] && FOODY == SNAKE[i][1]){
      return true;
    }
  }
  return false;
}
//========================================移动一格===========================
function moveIn(x, y){
  CTX.fillStyle = "black";
  CTX.fillRect(x, y, SIZE, SIZE);//重画蛇头  
  //把新蛇头添加到 SNAKE 数组
  var newSnake = [[x, y]];
  SNAKE = newSnake.concat(SNAKE);

  if(false == eatFood()){//如果没吃到食物,减少一格蛇尾  
    var snakeTail = SNAKE.pop();//获得蛇尾位置
    CTX.clearRect(snakeTail[0], snakeTail[1], SIZE, SIZE);//去掉蛇尾  
  }
}
function eatFood(){
  if(HEADX == FOODX && HEADY == FOODY){
    CTX.fillStyle = "block";
    CTX.fillRect (FOODX, FOODY, SIZE, SIZE);

    setFood();
    SCORE++;
    //$("#score").text(SCORE);
    document.getElementById("score").innerHTML = SCORE;
    return true;
  }
  return false;
}

  </script>
</html>

Rendering:

Things:

function newgame(){
  重置蛇和分数的数据;
  清除interval;
  初始化画布;
  画一条蛇;
  放置食物;
  使用定时器(setInterval)使蛇移动(move函数);
}
function move(){
  根据方向改变蛇头下一格将要到达的位置;
  判断游戏是否结束,以及显示结束的原因(包含输赢);
  蛇移动一格(moveIn函数);
}
对键盘的方向键作监控,当改变方向时,修改全局变量DIR的值(用于存储方向);
function moveIn(){
  在蛇头的前一格增加一格作为新的蛇头,并将蛇头的坐标作为第一个元素加入到代表蛇的数组中;
  if(没吃到食物){
    删除一格蛇尾,在画布中做相应改变;
  }
}

It should be noted that if you need to set the width and height of the canvas in JS, it is slightly different from setting other CSS properties.

CANVAS.width = MAXWIDTH;CANVAS.height = MAXHEIGHT;

The editor has also prepared exciting topics for you: A summary of classic JavaScript games

The above is the entire content of this article. I hope it will be helpful to everyone in learning javascript programming.

Statement
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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)