Home Web Front-end HTML Tutorial canvas game greedy snake

canvas game greedy snake

Oct 12, 2016 pm 01:47 PM

直接上效果图:

canvas game greedy snake

这个贪食蛇关键地方在于数组,它的长度增加其实是数组的增长,就是数组的向前追加等操作,核心就是数组的操作。

 

完整代码:

<!DOCTYPE html>
<html>

    <body>
        <canvas id="myCanvas" width="240" height="240" style="border:1px solid #d3d3d3;">
            Your browser does not support the HTML5 canvas tag.
        </canvas>
        <script>
        //r数组表示蛇 ; co表示蛇前进的方向,默认向下 ; e表示食物
var ctx = document.getElementById("myCanvas").getContext("2d"),
    r = [{
        x: 10,
        y: 9
    }, {
        x: 10,
        y: 8
    }],
    co = 40,
    e = null;
    /*为了避免按键太快,使定时器没有反应过来,出现bug*/
    var offOn=true;
    /*这是关卡的开关*/
    var offOn01=true;
    /*关卡倒计开始值*/
    var num=3;
//循环,间隔为200毫秒
var timer=setInterval(doMove, 200);


function doMove() {

    //给蛇加上阴影效果
    ctx.shadowBlur = 20, ctx.shadowColor = "black";

    //游戏是否已经结束
    if (check(r[0], 0) || r[0].x < 0 || r[0].x >= 24 || r[0].y < 0 || r[0].y >= 24) return;

    //如果有食物,则根据蛇前进的方向判断是否吃到了食物,并且将蛇数组中最后一个元素换到首部
    e != null && ((co == 40 && r[0].x == e.x && r[0].y + 1 == e.y) || 
        (co == 38 && r[0].x == e.x && r[0].y - 1 == e.y) || 
        (co == 37 && r[0].x - 1 == e.x && r[0].y == e.y) || 
        (co == 39 && r[0].x + 1 == e.x && r[0].y == e.y)) ? 
    (r.unshift(e), e = null, r.unshift(r.pop())) : (r.unshift(r.pop()));

    //根据方向,重新设定蛇数组首元素的坐标,从而进行移动
    (co == 40 || co == 38) ? (r[0].x = r[1].x, r[0].y = r[1].y + (co == 40 ? 1 : -1)) : (r[0].x = r[1].x + (co == 39 ? 1 : -1), r[0].y = r[1].y);

    //清空屏幕
    ctx.clearRect(0, 0, 240, 240);

    //如果有食物,则绘制食物
    if (e) ctx.fillRect(e.x * 10, e.y * 10, 10, 10);

    //绘制蛇
    for (var i = 0; i < r.length; i++) ctx.fillRect(r[i].x * 10, r[i].y * 10, 10, 10);

    //如果没有食物,则在随机位置上加入一粒食物
    while (e == null || check(e)) e = {
        y: (Math.floor(Math.random() * 24)),
        x: (Math.floor(Math.random() * 24))
    };

    /*分数*/
    ctx.shadowBlur=0;
    ctx.font="12px Arial";
    ctx.fillText("分数:"+(r.length - 2),10,10);
    ctx.textBaseline="top";

    //判断游戏是否结束
    if (check(r[0], 0) || r[0].x < 0 || r[0].x >= 24 || r[0].y < 0 || r[0].y >= 24) 
        alert("game over\n你获得:" + (r.length - 2) + "分");
    
    /*设置一个关卡,就是分数到10分后进入下一关,只设置一个关卡*/
    if((r.length-2)==10){
    if(offOn01){
        clearInterval(timer);
        offOn01=false;
        var timer0=setInterval(function(){
            if(num<=0){
                clearInterval(timer0);
            }
            ctx.clearRect(0, 0, 240, 240);
            ctx.font="20px Arial";
            ctx.textBaseline="middle";
            ctx.textAlign="center";
            ctx.fillText("下一关:"+num,120,120);
            num=--num<0?0:num;    
        },1000);
            setTimeout(function(){
                timer=setInterval(doMove, 100);
            },4000);
        }
    }

    offOn=true;
}


//加入键盘事件,用方向键来控制蛇前进的方向
/*(Math.abs(event.keyCode - co) != 2判断不能向后走
left:37,top:38,right:39,bottom:40
反方向刚刚好是相差2
*/

document.onkeydown = function(event) {
    if(offOn){
        offOn=false;
        co = event.keyCode >= 37 && 
        event.keyCode <= 40 && 
        (Math.abs(event.keyCode - co) != 2) ? event.keyCode : co;
    }
    }
    //判断指定位置是否与蛇重叠
    /*这是为了检测自己撞到自己或检测食物在贪食蛇里面的*/
function check(e, j) {
    for (var i = 0; i < r.length; i++)
        if (j != i && r[i].x == e.x && r[i].y == e.y) return true;
    return false;
}</script>
    </body>

</html>
Copy after login

可以直接复制上面代码看效果;

上面的核心代码:

//如果有食物,则根据蛇前进的方向判断是否吃到了食物,并且将蛇数组中最后一个元素换到首部
    e != null && ((co == 40 && r[0].x == e.x && r[0].y + 1 == e.y) || 
        (co == 38 && r[0].x == e.x && r[0].y - 1 == e.y) || 
        (co == 37 && r[0].x - 1 == e.x && r[0].y == e.y) || 
        (co == 39 && r[0].x + 1 == e.x && r[0].y == e.y)) ? 
    (r.unshift(e), e = null, r.unshift(r.pop())) : (r.unshift(r.pop()));

    //根据方向,重新设定蛇数组首元素的坐标,从而进行移动
    (co == 40 || co == 38) ? (r[0].x = r[1].x, r[0].y = r[1].y + (co == 40 ? 1 : -1)) : (r[0].x = r[1].x + (co == 39 ? 1 : -1), r[0].y = r[1].y);
Copy after login

这是贪食蛇的核心代码,就是数组长度添加,和数组里的值怎么改变。

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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

What is the purpose of the <iframe> tag? What are the security considerations when using it? What is the purpose of the <iframe> tag? What are the security considerations when using it? Mar 20, 2025 pm 06:05 PM

The article discusses the &lt;iframe&gt; tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

What is the viewport meta tag? Why is it important for responsive design? What is the viewport meta tag? Why is it important for responsive design? Mar 20, 2025 pm 05:56 PM

The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

See all articles