首页 > 其他分享 >最近写贪吃蛇有些上瘾,canvas版本贪吃蛇,贪吃蛇是逻辑最简单的游戏了

最近写贪吃蛇有些上瘾,canvas版本贪吃蛇,贪吃蛇是逻辑最简单的游戏了

时间:2024-09-03 10:14:28浏览次数:10  
标签:canvas paint 上瘾 height width 贪吃蛇 var my points

代码:

<!Doctype html>
<html lang="zh_cn">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>贪吃蛇</title>
        <meta name="Keywords" content="">
        <meta name="Description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

    </head>
<body>

<canvas id="myCanvas" width="600" height="600" style="border:1px solid #FF0000;bgcolor:#FF0000;">
</canvas>

<script>
var margin = 10;
var pading = 3;
var maxLineNum = 25;
var maxFieldNum = 25;
var pointx = getRandomInt(0, maxFieldNum-1);
var pointy = getRandomInt(0, maxFieldNum-1);
var my_points = new Array();
var else_points = new Array();
var score = 0;

function getUnixTime(){
    return Math.floor(Date.now() / 1000);
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

//处理键盘事件
function doKeyDown(e){
    var keyID = e.keyCode ? e.keyCode :e.which;
    //console.log(keyID);
    
    //a
    if(keyID == 65){
        pointx--;
    }
    
    //d
    if(keyID == 68){
        pointx++;
    }
    
    //w
    if(keyID == 87){
        pointy--;
    }
    
    //s
    if(keyID == 83){
        pointy++;
    }
    
    if(pointx < 0){
        pointx = 0;
    }
    
    if(pointx > maxFieldNum-1){
        pointx = maxFieldNum-1;
    }
    
    if(pointy < 0){
        pointy = 0;
    }
    
    if(pointy > maxLineNum-1){
        pointy = maxLineNum-1;
    }
    
    //console.log("pointx:"+pointx+", pointy:"+pointy);
    
    //处理碰到的其他块
    var touchFlag = false;
    var my_points_old = JSON.parse(JSON.stringify(my_points));
    for(var i = 0; i < else_points.length; i++){
        if(else_points[i].x == pointx && else_points[i].y == pointy){
            touchFlag = true;
            my_points.unshift(else_points[i]);
            else_points.splice(i, 1);
            score++;
        }
    }
    
    if(touchFlag == false){
        for(var i = 0; i < my_points_old.length; i++){
            if(i == 0){
                my_points[i].x = pointx;
                my_points[i].y = pointy;
            } else{
                my_points[i].x = my_points_old[i-1].x;
                my_points[i].y = my_points_old[i-1].y;
            }
            //console.log("nopeng:i="+i+", x="+my_points[i].x+", y="+my_points[i].y);
        }
        //console.log("\n");
    }
    else{
        for(var i = 0; i < my_points.length; i++){
            //console.log("peng:i="+i+", x="+my_points[i].x+", y="+my_points[i].y);
        }
        //console.log("\n");
    }
    
    draw();
}
    
function draw(){
    var myCanvas = document.getElementById("myCanvas");

    var page_width = window.innerWidth;
    var page_height = window.innerHeight;
    //console.log("页面尺寸:宽:"+page_width+",高:"+page_height);

    var paint_width = page_width - 2 * margin - page_width / 4;
    var paint_height = page_height - 2 * margin;
    myCanvas.width = paint_width;
    myCanvas.height = paint_height;
    //console.log("画布尺寸:宽:"+paint_width+",高:"+paint_height);

    //清理画布
    var ctx = myCanvas.getContext("2d");
    ctx.beginPath();
    ctx.clearRect(0, 0, paint_width, paint_height);

    var left_width = paint_height - 2 * pading;
    var left_height = paint_height - 2 * pading;
    var right_width = paint_width - 2 * pading - left_width;
    var right_height = paint_height - 2 * pading;

    //画布背景
    var ctx = myCanvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = "rgb(147,112,219)";
    ctx.fillRect(0,0,paint_width,paint_height);
    //console.log("画布背景尺寸:宽:"+paint_width+",高:"+paint_height);

    //左侧背景
    var ctx = myCanvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = "rgb(255,250,240)";
    ctx.fillRect(pading,pading,left_width,left_height);
    //console.log("左侧背景尺寸:宽:"+left_width+",高:"+left_height);

    //右侧背景
    var ctx = myCanvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = "rgb(250,250,210)";
    ctx.fillRect(left_width+pading,pading,right_width,right_height);
    //console.log("右侧背景尺寸:宽:"+right_width+",高:"+right_height);

    var perWidth = left_width / maxFieldNum;
    var perHeight = left_height / maxLineNum;

    //横线
    for(var i = 0; i <= maxLineNum; i++){
        var ctx = myCanvas.getContext("2d");
        ctx.beginPath();
        ctx.moveTo(pading, pading+perHeight*i);
        ctx.lineTo(pading+left_width, pading+perHeight*i);
        ctx.strokeStyle = 'black';
        ctx.lineWidth = 1;
        ctx.stroke();
    }

    //竖线
    for(var i = 0; i <= maxFieldNum; i++){
        var ctx = myCanvas.getContext("2d");
        ctx.beginPath();
        ctx.moveTo(pading+perWidth*i, pading);
        ctx.lineTo(pading+perWidth*i, pading+left_height);
        ctx.strokeStyle = 'black';
        ctx.lineWidth = 1;
        ctx.stroke();
    }
    
    //第一个子
    if(my_points.length <= 0){
        var point = new Object();
        point.x = pointx;
        point.y = pointy;
        point.color = "rgb(255,0,0)";
        my_points.push(point);
    } else{
        my_points[0].x = pointx;
        my_points[0].y = pointy;
    }
    
    //其他随机子
    while(else_points.length < 3){
        var point = new Object();
        point.x = getRandomInt(0, maxFieldNum-1);
        point.y = getRandomInt(0, maxLineNum-1);
        point.color = "rgb("+getRandomInt(1, 255)+","+getRandomInt(1, 255)+","+getRandomInt(1, 255)+")";
        point.time = getUnixTime();
        else_points.push(point);
    }
    
    //显示第一个(蛇上的)棋子
    for(var i = 0; i < my_points.length; i++){
        var ctx = myCanvas.getContext("2d");
        ctx.beginPath();
        ctx.fillStyle = my_points[i].color;
        ctx.fillRect(my_points[i].x*perWidth+pading,my_points[i].y*perHeight+pading,perWidth,perHeight);
        
        //获取反色,展示文字序号
        var pattern = /[0-9]+/g;
        var matches = my_points[i].color.match(pattern);
        var r = 255-matches[0];
        var g = 255-matches[1];
        var b = 255-matches[2];
        
        ctx.beginPath();
        ctx.fillStyle="rgb("+r+","+g+","+b+")";
        ctx.font="12px Arial";
        ctx.fillText(i+1, my_points[i].x*perWidth+pading+perWidth/2.5, my_points[i].y*perHeight+pading+perHeight/1.5);
    }
    
    //过滤过期的其他棋子
    var tmp_points = new Array();
    for(var i = 0; i < else_points.length; i++){
        if(getUnixTime() - else_points[i].time < 60){
            tmp_points.push(else_points[i]);
        }
    }
    else_points = tmp_points;
    
    //显示其他棋子
    for(var i = 0; i < else_points.length; i++){
        var ctx = myCanvas.getContext("2d");
        ctx.beginPath();
        ctx.fillStyle = else_points[i].color;
        ctx.fillRect(else_points[i].x*perWidth+pading,else_points[i].y*perHeight+pading,perWidth,perHeight);
    }
    
    //显示得分按钮和文字
    var tmpcolor = "rgb(238,197,145)";
    var ctx = myCanvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = tmpcolor;
    ctx.fillRect(left_width+pading+right_width/3,perHeight/2,120,35);
    
    //获取反色,展示文字序号
    var pattern = /[0-9]+/g;
    var matches = tmpcolor.match(pattern);
    var r = 255-matches[0];
    var g = 255-matches[1];
    var b = 255-matches[2];
    ctx.beginPath();
    ctx.fillStyle="rgb("+r+","+g+","+b+")";
    ctx.font="14px Arial";
    ctx.fillText("得分:"+score, left_width+pading+right_width/3+35,perHeight/2+23);
    
    myCanvas.addEventListener('keydown', doKeyDown,true);
    myCanvas.focus();
    window.addEventListener('keydown', doKeyDown, true);
}

draw();
    
</script>

</body>
</html>

 

效果:

 

标签:canvas,paint,上瘾,height,width,贪吃蛇,var,my,points
From: https://www.cnblogs.com/xuxiaobo/p/18394047

相关文章

  • SDL贪吃蛇代码
    #include<stdio.h>#include<SDL.h>#include<stdlib.h>#include<SDL_image.h>#undefmain//定义屏幕宽度和高度及蛇的块大小#defineSCREEN_WIDTH800#defineSCREEN_HEIGHT600#defineSNAKE_BLOCK20//SDL窗口和渲染器全局变量SDL_Window*gWindow=NULL;SD......
  • 【Canvas与艺术】十边螺线动态顺时针扩大光阑
    【成图】【代码】<!DOCTYPEhtml><htmllang="utf-8"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><head><title>十边螺线动态扩大光阑</title><styletype="text/css&quo......
  • 【Canvas与艺术】十边螺线动态缩小光阑
    【成图】【代码】<!DOCTYPEhtml><htmllang="utf-8"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><head><title>十边螺线动态缩小光阑</title><styletype="text/css&quo......
  • java-swing贪吃蛇游戏
    MyRect.javapackageMain;publicclassMyRect{ publicintx=0; publicinty=0; publicMyRgbrgb=newMyRgb(); longcreatetime=0; publicMyRect(){ } publicMyRect(intmx,intmy,MyRgbmyrgb,longtime){ x=mx; y=my; rgb=......
  • 【Canvas与诗词】录王昌龄诗《从军行之五》红旗半卷出辕门...
    【成图】【代码】<!DOCTYPEhtml><htmllang="utf-8"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><head><title>已报生擒吐谷浑</title><styletype="text/css&......
  • vue使用html2canvas将页面dom生成图片,解决页面中带有图片导出
    安装npm installhtml2canvas引入importhtml2canvas from 'html2canvas'使用this.$refs.canvasToPic是div的dom,只要在这个div中的区域都可以生成图片1this.$nextTick(()=>{2html2canvas(this.$refs.canvasToPic,{useCORS:true,logging:true}).......
  • WPF mouse down on canvas and draw shapes which render with random colors
    //customcontrol//xaml<UserControlx:Class="WpfApp307.ElpTbk"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"......
  • 【Canvas与艺术】夏日绝句 李清照
    【成图】【代码】<!DOCTYPEhtml><htmllang="utf-8"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><head><title>夏日绝句</title><styletype="text/css">......
  • 【Canvas与艺术】六边形漩涡
    【成图】【代码】<!DOCTYPEhtml><htmllang="utf-8"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><head><title>六边形漩涡</title><styletype="text/cs......
  • Amazon Bedrock 实践:零基础创建贪吃蛇游戏
    本文探讨了如何利用AmazonBedrock和大型语言模型,快速创建经典的贪吃蛇游戏原型代码。重点展示了利用提示工程,将创新想法高效转化为可运行代码方面的过程。文章还介绍了评估和优化提示词质量的最佳实践。亚马逊云科技开发者社区为开发者们提供全球的开发技术资源。这里有技术......