search
HomeWeb Front-endH5 TutorialH5 canvas implements the Snake game

This time I will bring you the H5 canvas to implement the Snake game, and the H5 canvas to implement the Snake game. Notes What are the following, the following is a practical case, let’s take a look.

This article introduces the H5 canvas implementation of the Snake game and shares it with everyone. The details are as follows:

The implementation effect is as follows

Implementation ideas:

ps: This is just an idea, please refer to the code comments for details

First, first Draw a snake

  1. # Define the structure of the snake and use an array to save a bunch of rectangles, including the snake head (red) and the snake body (gray).

  2. Drawing a snake (initial state)

2. The snake can move (key points)

  1. Snake movement method: only the snake head is moving from beginning to end

    1. Draw a gray square, the position overlaps with the snake head

    2. Insert this block into the array at a position behind the snake head arrar.splice(0,1,rect)

    3. Cut off the last block array.pop()

    4. Move the snake head one space to the set direction

  2. Requires a variable to save the direction (direction)

  3. Move according to the direction, move one frame at a time

  4. Change the direction according to the keys

Three , Randomly put food

  1. Need random food location

  2. Need to determine whether the food is on the snake.

##4. Eat food

  1. Determine whether the food overlaps with the snake head

  2. Add an element to the array (removing one element means adding one element)

  3. Generate new food

5. gameover

  1. Judgment of hitting the wall

  2. Pretend to make your own judgment

  3. nbsp;html>
    
    
        <meta>
        <title>Document</title>
        <style>
            #canvas{
                box-shadow: 0 5px 40px black;
            }
        </style>
    
    
        <canvas></canvas>
    
    <script>
        var canvas = document.getElementById(&#39;canvas&#39;);
        var context = canvas.getContext(&#39;2d&#39;);
        //构造对象方块
        function Rect (x,y,w,h,color) {
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
            this.color = color;
        }
        //画方块的方法
        Rect.prototype.draw = function () {
            context.beginPath();
            context.fillStyle = this.color;
            context.rect(this.x,this.y,this.w,this.h);
            context.fill();
            context.stroke();
        }
        //构造对象蛇
        function Snake () {
            //定义一个空数组存放组成整蛇的方块对象
            var snakeArray = [];
            //画出4个方块,设置成灰色
            for (var i = 0; i < 4; i++) {
                var rect = new Rect(i*20,0,20,20,"gray");
                //之所以用splice(往前加)而不是用push(往后加),是为了让蛇头出现在数组第一个位置
                snakeArray.splice(0,0,rect);     
            }
            //把数组第一个作为蛇头,蛇头设成红色
            var head = snakeArray[0];
            head.color = "red";
            //此处将两个后面常用的东西定为属性,方便后面调用
            this.head = snakeArray[0];  //蛇头
            this.snakeArray = snakeArray;  //整蛇数组
            //给定初始位置向右(同keyCode右箭头)
            this.direction = 39;
        }
        //画蛇的方法
        Snake.prototype.draw = function () {
            for (var i = 0; i < this.snakeArray.length; i++) {
                this.snakeArray[i].draw();
            } 
        }
        //蛇移动的方法
        Snake.prototype.move = function () {
            //此处是核心部分,蛇的 移动方式
            //1、画一个灰色的方块,位置与蛇头重叠
            //2、将这个方块插到数组中蛇头后面一个的位置
            //3、砍去末尾的方块
            //4、将蛇头向设定方向移动一格
            var rect = new Rect(this.head.x,this.head.y,this.head.w,this.head.h,"gray");
            this.snakeArray.splice(1,0,rect);
            //判断是否吃到食物,isEat判定函数写在最后了
            //吃到则食物重新给位置,不砍去最后一节,即蛇变长
            //没吃到则末尾砍掉一节,即蛇长度不变
            if (isEat()){
                food = new getRandomFood();
            }else{
                this.snakeArray.pop();
            }
            //设置蛇头的运动方向,37 左,38 上,39 右,40 下
            switch (this.direction) {
                case 37:
                    this.head.x -= this.head.w
                    break;
                case 38:
                    this.head.y -= this.head.h
                    break;
                case 39:
                    this.head.x += this.head.w
                    break;
                case 40:
                    this.head.y += this.head.h
                    break;
                default:    
                    break;
            }
            // gameover判定
            // 撞墙
            if (this.head.x > canvas.width || this.head.x < 0 || this.head.y > canvas.height || this.head.y < 0){
                clearInterval(timer);
            }
            // 撞自己,循环从1开始,避开蛇头与蛇头比较的情况
            for (var i = 1; i < this.snakeArray.length; i++) {
                if (this.snakeArray[i].x == this.head.x && this.snakeArray[i].y == this.head.y){
                    clearInterval(timer);
                }
            }
        }
        //画出初始的蛇
        var snake = new Snake()
        snake.draw();
        //画出初始的食物
        var food = new getRandomFood()
        //定时器
        var timer = setInterval(function () {
            context.clearRect(0,0,canvas.width,canvas.height);
            food.draw();
            snake.move();
            snake.draw();
        }, 100)
        //键盘事件,其中的if判定是为了让蛇不能直接掉头
        document.onkeydown = function (e) {
            var ev = e||window.event;
            switch(ev.keyCode){
                case 37:{
                    if (snake.direction !== 39){
                        snake.direction = 37;
                    }
                    break;
                }
                case 38:{
                    if (snake.direction !== 40){
                        snake.direction = 38;
                    }
                    break;
                }
                case 39:{
                    if (snake.direction !== 37){
                        snake.direction = 39;
                    }
                    break;
                }
                case 40:{
                    if (snake.direction !== 38){
                        snake.direction = 40;
                    }
                    break;
                }    
            }
            ev.preventDefault();
        }
        //随机函数,获得[min,max]范围的值
        function getNumberInRange (min,max) {
            var range = max-min; 
            var r = Math.random();
            return Math.round(r*range+min)
        }
        //构建食物对象
        function getRandomFood () {
            //判定食物是否出现在蛇身上,如果是重合,则重新生成一遍
            var isOnSnake = true;
            //设置食物出现的随机位置
            while(isOnSnake){
                //执行后先将判定条件设置为false,如果判定不重合,则不会再执行下列语句
                isOnSnake = false;
                var indexX = getNumberInRange(0,canvas.width/20-1);
                var indexY = getNumberInRange(0,canvas.height/20-1);
                var rect = new Rect(indexX*20, indexY*20, 20, 20, "green");
                for (var i = 0; i < snake.snakeArray.length; i++) {
                    if(snake.snakeArray[i].x == rect.x && snake.snakeArray[i].y == rect.y){
                        //如果判定重合,将其设置为true,使随机数重给
                        isOnSnake = true;
                        break;
                    }
                }
            }
            //返回rect,使得实例化对象food有draw的方法
            return rect;
        }
        //判定吃到食物,即蛇头坐标与食物坐标重合
        function isEat () {
            if (snake.head.x == food.x && snake.head.y == food.y){
                return true;
            } else {
                return false;
            }
        }
    </script>
    
I believe I read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

H5 drag-and-drop API for drag-and-drop sorting

What are the newly added tags in html5

The above is the detailed content of H5 canvas implements the Snake game. For more information, please follow other related articles on the PHP Chinese website!

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
Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!