search
HomeWeb Front-endH5 TutorialMaking a Snake Game with HTML5
Making a Snake Game with HTML5Aug 07, 2017 pm 03:03 PM
h5html5game

This article mainly introduces the H5 canvas to implement the Snake game. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

This article introduces the implementation of the Snake game on H5 canvas 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 see the code comments for details

1. First draw the 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 (direction) to save the direction

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

  4. Change the direction according to the keys

3. Randomly place food

  1. Need the location of random food

  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



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #canvas{
            box-shadow: 0 5px 40px black;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="800" height="500"></canvas>
</body>
<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>
</html>

The above is the detailed content of Making a Snake Game with HTML5. 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
html5的div一行可以放两个吗html5的div一行可以放两个吗Apr 25, 2022 pm 05:32 PM

html5的div元素默认一行不可以放两个。div是一个块级元素,一个元素会独占一行,两个div默认无法在同一行显示;但可以通过给div元素添加“display:inline;”样式,将其转为行内元素,就可以实现多个div在同一行显示了。

html5中列表和表格的区别是什么html5中列表和表格的区别是什么Apr 28, 2022 pm 01:58 PM

html5中列表和表格的区别:1、表格主要是用于显示数据的,而列表主要是用于给数据进行布局;2、表格是使用table标签配合tr、td、th等标签进行定义的,列表是利用li标签配合ol、ul等标签进行定义的。

html5怎么让头和尾固定不动html5怎么让头和尾固定不动Apr 25, 2022 pm 02:30 PM

固定方法:1、使用header标签定义文档头部内容,并添加“position:fixed;top:0;”样式让其固定不动;2、使用footer标签定义尾部内容,并添加“position: fixed;bottom: 0;”样式让其固定不动。

HTML5中画布标签是什么HTML5中画布标签是什么May 18, 2022 pm 04:55 PM

HTML5中画布标签是“<canvas>”。canvas标签用于图形的绘制,它只是一个矩形的图形容器,绘制图形必须通过脚本(通常是JavaScript)来完成;开发者可利用多种js方法来在canvas中绘制路径、盒、圆、字符以及添加图像等。

html5中不支持的标签有哪些html5中不支持的标签有哪些Mar 17, 2022 pm 05:43 PM

html5中不支持的标签有:1、acronym,用于定义首字母缩写,可用abbr替代;2、basefont,可利用css样式替代;3、applet,可用object替代;4、dir,定义目录列表,可用ul替代;5、big,定义大号文本等等。

html5废弃了哪个列表标签html5废弃了哪个列表标签Jun 01, 2022 pm 06:32 PM

html5废弃了dir列表标签。dir标签被用来定义目录列表,一般和li标签配合使用,在dir标签对中通过li标签来设置列表项,语法“<dir><li>列表项值</li>...</dir>”。HTML5已经不支持dir,可使用ul标签取代。

html5是什么意思html5是什么意思Apr 26, 2021 pm 03:02 PM

html5是指超文本标记语言(HTML)的第五次重大修改,即第5代HTML。HTML5是Web中核心语言HTML的规范,用户使用任何手段进行网页浏览时看到的内容原本都是HTML格式的,在浏览器中通过一些技术处理将其转换成为了可识别的信息。HTML5由不同的技术构成,其在互联网中得到了非常广泛的应用,提供更多增强网络应用的标准机。

Html5怎么取消td边框Html5怎么取消td边框May 18, 2022 pm 06:57 PM

3种取消方法:1、给td元素添加“border:none”无边框样式即可,语法“td{border:none}”。2、给td元素添加“border:0”样式,语法“td{border:0;}”,将td边框的宽度设置为0即可。3、给td元素添加“border:transparent”样式,语法“td{border:transparent;}”,将td边框的颜色设置为透明即可。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)