qq_35866052 2016-08-17 19:57 采纳率: 0%
浏览 1494

新人问个超简单的问题。。HTML5做的贪吃蛇怎样让它动起来?

    var canvas = document.getElementById ("snakeCanvas");
    var ctx = canvas.getContext("2d");  //理解成画笔
    var width = 15; //每一个小方格的宽度
    //指定初始长度为6
    var snakeLen = 6;
    var snake = [];     //蛇的身体
    for (var i = 0; i < snakeLen; i++)
    {
        snake[i] = new Cell(i, 0, -1);
    }
    //初始食物的x,y
    var foodX = 0;
    var foodY = 0;
    //定义食物对象
    var food;

    //蛇的身体构成的元素 x坐标 y坐标 d (1:左边, -1:右边, 2:上, -2:下)
    function Cell(x, y, d){
        this.x = x;
        this.y = y;
        this.d = d;
        return this;
    }

    //定义一个食物对象
    function Food(x, y){
        this.x = x;
        this.y = y;
        return this;
    }

    //绘制游戏基本元素
    function draw () {
        //清空整个画布
        ctx.clearRect(0, 0, 600, 525);

        //绘制网格
        for (var i = 0; i < 40; i ++)
        {
            ctx.strokeStyle="#ccc";     //线条
            ctx.beginPath();
            //绘制横线
            ctx.moveTo(0, i * width);
            ctx.lineTo(600, i * width);
            //绘制竖线
            ctx.moveTo(i * width, 0);
            ctx.lineTo(i * width, 525);

            ctx.closePath();
            ctx.stroke();


        }

        //绘制蛇的身体
        for (var i = 0; i < snake.length; i++)
        {
            ctx.fillStyle = "black";        //填充颜色
            //蛇的头部
            if (i == snake.length -1)
            {
                ctx.fillStyle="red";
            }
            ctx.beginPath ();
            ctx.rect(snake[i].x * width, snake[i].y * width, width, width);
            ctx.closePath();
            ctx.fill();
            ctx.stroke();
        }

            drawFood ();

    }
    //初始化食物的x,y坐标,随机产生
    function initFood (){
        // Math.random() 返回一个0~1之间的数
        // Math.ceil(0.1) 返回到1
        foodX = Math.ceil(Math.random() * 38 + 1);
        foodY = Math.ceil(Math.random() * 33 + 1);

        //判断是否跟蛇的身体有重叠
        for (var i = 0; i < snake.length; i++)
        {
            if (snake[i].x == foodX && snake[i].y == foodY)
            {
                initFood ();    //递归产生食物坐标
            }
        }
    }

    //绘制食物
    function drawFood () {
        initFood ();
        food = new Food (foodX, foodY);
        ctx.fillStyle = "green";
        ctx.beginPath ();
        ctx.rect(food.x * width, food.y * width, width, width);
        ctx.closePath();
        ctx.fill();


    }




    draw ();
</script>

  • 写回答

5条回答 默认 最新

  • qq_35866052 2016-08-17 20:00
    关注

    有人可以告诉我后面的要怎样继续做下去吗?

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器