search
HomeWeb Front-endHTML Tutorialcanvas 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>

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

 

上面的核心代码:

//如果有食物,则根据蛇前进的方向判断是否吃到了食物,并且将蛇数组中最后一个元素换到首部
    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);

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

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
HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools