JavaScript to achieve the idea of ​​​​snake game

JavaScript to achieve the idea of ​​​​snake game

The implementation idea of ​​the javascript game Snake is explained (complete code implementation) for your reference. The specific content is as follows

Effect Process

1. First, we need to operate the canvas

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Snake</title>
</head>
 
<body>
 <canvas id="canvas"></canvas> <!-- The canvas we want to operate -->
 <input type="button" value="Start Game" /><!-- Start Game Button-->
<script>
//Get the element var canvas = document.getElementById("canvas"); //Find the canvas we want to operate
var context = canvas.getContext("2d"); //Specify that the environment for operations on canvas is 2d
var but = document.getElementsByTagName("input")[0]; //Find the start button</script>

2. During initialization

canvas.width = 500; //Define canvas width canvas.height = 500; //Define canvas height canvas.style.border = "5px solid #000"; //Define canvas border var times = 100; //Default time 200 milliseconds var long = 10; //Number of snake bodies relative to step length var x = y =8; //Initial coordinates of the snake var direction = 3; // 1 up 2 right 3 down 0 left var size = 8; //Length of each movement of the snake (step length)
var map = []; //Used to record the coordinates of each movement of the snake var foodx = 0; //The initial X-axis coordinate of the food var foody = 0; //The initial Y-axis coordinate of the food var onOff = true; 
var foodT = true;
var timer = null;

3. Control the snake's coordinates according to the direction, determine whether the snake's coordinates exceed the canvas boundary, and determine whether the snake has touched itself

 //Control the snake's coordinates according to the direction switch(direction){
 
        case 1: y = y - size; break; //upper case 2: x = x + size; break; //right case 3: y = y + size; break; //lower case 0: x = x - size; break; //left}
 
    //Judge whether the snake's coordinates exceed the canvas boundary. If so, a wall collision prompt will appear and the game ends if(x>500 || x<0 || y>500 || y<0){
 
// alert("You hit a wall! Keep trying...");
        window.location.reload();   
    }
 
    //Judge whether the snake has touched you. If it has touched you, the game ends for(var i=0; i<map.length; i++){
        if(parseInt( map[i].x ) == x && parseInt( map[i].y ) == y){
// alert("You hit yourself and died! Keep trying...");
            window.location.reload(); //Reload}
    }

4. Then draw the snake

//Draw the snake if(map.length>long){ 
        var cl = map.shift();
        context.clearRect(cl['x'],cl['y'],size,size);
    }
    map.push({'x':x,'y':y}); 
    context.fillStyle = "#777"; //Fill the snake's color context.fillRect(x,y,size,size); //Draw the snake

5. When the coordinates of the food are equal to the coordinates of the snake (the snake eats the food)

//When judging that the coordinates of the food are equal to the coordinates of the snake (the snake eats the food)
    if(foodx*8 == x && foody*8 == y ){
        food(); //Draw food again long++; //The length of the snake increases times = times - 10; //Speed ​​up clearInterval(timer);
        onOff = true;
        setTimeout(goto,times); //Start a new round}

6. Determine the random display coordinates of food and draw the food

//Determine the random display coordinates of food and draw food function food(){
    foodx = Math.ceil(Math.random()*40); //Random coordinates of the food on the X axis foody = Math.ceil(Math.random()*40); //Random coordinates of the food on the Y axis context.fillStyle = "mediumvioletred"; //Fill color of the food context.fillRect(foodx*8,foody*8,8,8); //Draw food }

7. Listen for pressing the direction key to get the direction the snake is moving

//Listen to the direction key pressed to get the direction of the snake document.onkeydown = function(ev){
    var ev = ev || event;
    var cod = ev.keyCode - 37;
 
    switch(cod){
        case 1: direction = 1; break; //up case 2: direction = 2; break; //right case 3: direction = 3; break; //down case 0: direction = 0; break; //left }   
}

Complete code implementation

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Snake</title>
</head>
 
<body>
 <canvas id="canvas"></canvas> <!-- The canvas we want to operate -->
 <input type="button" value="Start Game" /><!-- Start Game Button-->
<script>
//Get the element var canvas = document.getElementById("canvas"); //Find the canvas we want to operate
var context = canvas.getContext("2d"); //Specify that the environment for operations on canvas is 2d
var but = document.getElementsByTagName("input")[0]; //Find the start button//Initialize canvas.width = 500; //Define canvas width canvas.height = 500; //Define canvas height canvas.style.border = "5px solid #000"; //Define canvas border var times = 100; //Default time 200 milliseconds var long = 10; //Number of snake bodies relative to step length var x = y =8; //Initial coordinates of the snake var direction = 3; // 1 up 2 right 3 down 0 left var size = 8; //Length of each movement of the snake (step length)
var map = []; //Used to record the coordinates of each movement of the snake var foodx = 0; //The initial X-axis coordinate of the food var foody = 0; //The initial Y-axis coordinate of the food var onOff = true; 
var foodT = true;
var timer = null;
function star(){
 
    //Control the snake's coordinates according to the direction switch(direction){
 
        case 1: y = y - size; break; //upper case 2: x = x + size; break; //right case 3: y = y + size; break; //lower case 0: x = x - size; break; //left}
 
    //Judge whether the snake's coordinates exceed the canvas boundary. If so, a wall collision prompt will appear and the game ends if(x>500 || x<0 || y>500 || y<0){
 
// alert("You hit a wall! Keep trying...");
        window.location.reload();   
    }
 
    //Judge whether the snake has touched you. If it has touched you, the game ends for(var i=0; i<map.length; i++){
        if(parseInt( map[i].x ) == x && parseInt( map[i].y ) == y){
// alert("You hit yourself and died! Keep trying...");
            window.location.reload(); //Reload}
    }
 
    //Draw the snake if(map.length>long){ 
        var cl = map.shift();
        context.clearRect(cl['x'],cl['y'],size,size);
    }
    map.push({'x':x,'y':y}); 
    context.fillStyle = "#777"; //Fill the snake's color context.fillRect(x,y,size,size); //Draw the snake //When the food coordinates are equal to the snake's coordinates (the snake eats the food)
    if(foodx*8 == x && foody*8 == y ){
        food(); //Draw food again long++; //The length of the snake increases times = times - 10; //Speed ​​up clearInterval(timer);
        onOff = true;
        setTimeout(goto,times); //Start a new round}
 
 
}
 
//Determine the random display coordinates of food and draw food function food(){
    foodx = Math.ceil(Math.random()*40); //Random coordinates of the food on the X axis foody = Math.ceil(Math.random()*40); //Random coordinates of the food on the Y axis context.fillStyle = "mediumvioletred"; //Fill color of the food context.fillRect(foodx*8,foody*8,8,8); //Draw food }
//Start the game function goto(){
    if(onOff){
        timer = setInterval(star,times);
        onOff = false;
    }
    if(foodT){
        food();
        foodT = false;
    }   
}
//Click the button to start the gamebut.onclick = goto;//Click the button to start the game//Listen to the direction the direction key is pressed to get the direction the snake is movingdocument.onkeydown = function(ev){
    var ev = ev || event;
    var cod = ev.keyCode - 37;
 
    switch(cod){
        case 1: direction = 1; break; //up case 2: direction = 2; break; //right case 3: direction = 3; break; //down case 0: direction = 0; break; //left }   
}
</script>
</body>
</html>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JavaScript exquisite snake implementation process
  • JS implements the snake game
  • JavaScript implementation of classic snake game
  • JS practical object-oriented snake game example

<<:  Detailed explanation of the principle of creating tomcat in Eclipse

>>:  How to check if a table exists in MySQL and then delete it in batches

Recommend

How to develop uniapp using vscode

Because I have always used vscode to develop fron...

Detailed explanation of the data responsiveness principle of Vue

This article is mainly for those who do not under...

Play and save WeChat public account recording files (convert amr files to mp3)

Table of contents Audio transcoding tools princip...

Using CSS to implement loading animation of Android system

There are two common loading icons on the web, on...

How to implement Vue binding class and binding inline style

Table of contents Binding Class Binding inline st...

I have compiled a few cool design sites that I think are good.

You must have inspiration to design a website. Goo...

HTML form submission method case study

To summarize the form submission method: 1. Use t...

MySQL Database Indexes and Transactions

Table of contents 1. Index 1.1 Concept 1.2 Functi...

Mysql5.7.14 Linux version password forgotten perfect solution

In the /etc/my.conf file, add the following line ...

Knowledge about MySQL Memory storage engine

Knowledge points about Memory storage engine The ...

Implementation and usage scenarios of JS anti-shake throttling function

Table of contents 1. What is Function Anti-shake?...

Use of Linux passwd command

1. Command Introduction The passwd command is use...

Several ways to schedule backup of MySQL database (comprehensive)

Table of contents 1. mysqldump command to back up...

Detailed explanation of JSON.parse and JSON.stringify usage

Table of contents JSON.parse JSON.parse Syntax re...

Vue Element UI custom description list component

This article example shares the specific code of ...