JavaScript实现 贪吃蛇

我们做一个贪吃蛇的游戏。
现在我们开始实现这个游戏

首先分析贪吃蛇这个游戏里的对象
一、找对象
属性 方法
场景、食物、蛇 开始、结束

二、实现对象
定义场景(游戏引擎)

在页面上创建出游戏场景
创建元素:createElement
追加元素:appendChild

CSS样式


  • 场景的JS代码
var gGameBox = {
    rows: 20,  // 行数    
    cols: 20,  // 列数
    allTds: [], // 存储所有的td元素对象
    food: null, // 食物对象
        snake: null, // 蛇对象
        timer: null, // 定时器

    // 方法: 清空环境
    clear: function() {
        for (var i = 0; i < gGameBox.allTds.length; i++) {
            for (var j = 0; j < gGameBox.allTds[i].length; j++) {
                gGameBox.allTds[i][j].className = "";
            }
        }
    },
// 方法:支持键盘控制
    keyControl: function() {
        // onkeydown 键盘按下事件
        window.onkeydown = function(e) {
            // 获取按键编码
            var c = e.keyCode;

            if (c == 37)
            {
                // 左

                if (gGameBox.snake.direct == "right")
                {
                    // 当前是往右走,不能掉头,终止函数
                    return ;
                }
                gGameBox.snake.direct = "left";
            }
            else if (c == 38)
            {
                // 上
                if (gGameBox.snake.direct == "down")
                {
                    return ;
                }
                gGameBox.snake.direct = "up";
            }
            else if (c == 39)
            {
                // 右
                if (gGameBox.snake.direct == "left")
                {
                    return ;
                }
                //  改变蛇的方向
                gGameBox.snake.direct = "right";
            }
            else if (c == 40)
            {
                if (gGameBox.snake.direct == "up")
                {
                    return ;
                }
                // 下
                gGameBox.snake.direct = "down";
            }
        }
    },
    
    // 方法: 游戏开始
    start: function() {
        gGameBox.init(); // 游戏初始化   
        this.food = new Food(); // 创建食物
                gGameBox.snake = new Snake(); // 创建蛇
                // 支持键盘控制
        gGameBox.keyControl();

        // 启动游戏时,定时移动蛇
        gGameBox.timer = setInterval(function() {

            // 1. 清空棋盘
            gGameBox.clear();
            
            // 2. 蛇移动
            gGameBox.snake.move();

            // 3. 显示食物
            gGameBox.food.show();
        }, 500);
    },

    // 初始化
    init: function() {
        // 场景布置好, 用表格来做
        var oTable = document.createElement("table");
    
        for (var i = 0; i < gGameBox.rows; i++)
        {
            // 创建tr
            var oTr = document.createElement("tr"); 

            // 每一行,定义1个空数组
            var arr = [];

            for (var j = 0; j < gGameBox.cols; j++) {
                // 创建td
                var oTd = document.createElement("td"); 

                oTr.appendChild(oTd);

                // 将td放到空数组中
                arr.push(oTd);
            }
            // 将当前行所有的td,压入到 allTds 属性中
            gGameBox.allTds.push(arr);

            oTable.appendChild(oTr);
        }

        // 添加到body
        document.body.appendChild(oTable);
    }
};

创建了20*20的表格添加到页面中,创建出我们的游戏场景

  • 食物的JS代码

方法:show(让食物出现在场景中)方法和change(一开始就出现在随机位置)方法

function Food() {

    // 坐标
    this.x = 0;
    this.y = 0;

    // 一开始就随机位置
    this.change();
}

// 方法1: 出现在环境中
Food.prototype.show = function() {
    gGameBox.allTds[this.y][this.x].className = "food";
}

// 方法2: 改变位置, 随机的
Food.prototype.change = function() {
    this.x = parseInt(Math.random() * gGameBox.cols);
    this.y = parseInt(Math.random() * gGameBox.rows);

    this.show();
}

用构造函数来创建食物
算法:随机显示食物坐标
横坐标:this.x = parseInt(Math.random() * gGameBox.cols);
纵坐标:this.y = parseInt(Math.random() * gGameBox.rows);

  • 蛇的JS代码

我们要用一串数组来储存蛇
this.arr.length 储存了蛇的长度

function Snake() {

    // 存储蛇 所有节点坐标, 同时也存储了蛇的长度  this.arr.length
    //  默认蛇头  this.arr[0]  节点
    this.arr = [
        {x: 5, y: 1},
        {x: 4, y: 1},
        {x: 3, y: 1},
        {x: 2, y: 1},
        {x: 1, y: 1}
    ];

    // 当前移动方向:   left, right, down, up
    this.direct = "down";

    // 创建完就刷新到页面上
    this.fresh();
}

// 方法1: 更新到页面上  fresh 刷新  
Snake.prototype.fresh = function() {
    // 给所有蛇节点,都添加样式
    for (var i = 0; i < this.arr.length; i++)
    {
        // this.arr[i] 是蛇节点对象
        var x = this.arr[i].x;
        var y = this.arr[i].y;

        gGameBox.allTds[y][x].className = "snake"
    }
}

// 方法2: 移动
Snake.prototype.move = function() {

    // 蛇头坐标
    var x = this.arr[0].x;
    var y = this.arr[0].y;

    // 思路: 根据当前蛇的方向,来分情况处理
    if (this.direct == "right")
    {
        //   4      3       2     1      0
        // (1,1) (2,1) (3,1) (4,1) (5,1)
        // (2,1) (3,1) (4,1) (5,1) (6,1)
        //       (2,1) (3,1) (4,1) (5,1) (6,1)
        //  在 蛇头 增加新点 (6,1), 删除蛇尾
        x++;

    }else if (this.direct == "down")
    {
        y++;
    } else if (this.direct == "left")
    {
        x--;
    } else if (this.direct == "up")
    {
        y--;
    }
    if (x >= gGameBox.cols || y >= gGameBox.rows || x < 0 || y < 0)
    {
        clearInterval(gGameBox.timer);
        alert("GG啦~");
        return ;
    }

    if (x == gGameBox.food.x && y == gGameBox.food.y)
    {
        // 吃到食物了,增加1个点
        this.arr.unshift({x: x, y: y});

        // 食物更改位置
        gGameBox.food.change();

               // 将新蛇刷新到页面上
        this.fresh();
        return ;
    }

    // 在蛇头增加新点
    this.arr.unshift({x: x, y: y});

    // 删除蛇尾
    this.arr.pop();

    // 将新蛇刷新到页面上
    this.fresh();
}

在场景的JS中添加键盘控制来改变蛇的方向
gGameBox.keyControl();

  • 开始游戏
    在HTML调用
gGamebox.start()

最终实现效果

image.png

你可能感兴趣的:(JavaScript实现 贪吃蛇)