跳转到内容
aswind7
GitHub
Blog

game2048

原生dom实现的2048小游戏

鼠标操作上下左右箭头,支持移动端 利用dom来演示, 点击查看效果: demo

核心算法

// 二维数组维护面板数据
Game.prototype.init = function() {
    matrix = [
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
    ];
    this.generateANumber();
    this.generateANumber();
    score = 0;
    gameOverState = false;
    this.saveProgress();
    this.resetRender();
    this.render();
    // 监听
    this.watchDirection();
};

// 在随机的数据空白格增加一个2或者4
Game.prototype.generateANumber = function() {
    var number = Math.random() > 0.25 ? 2 : 4;
    // 存储每个空白格的坐标
    var storeCoord = [];
    var len;

    for (var i = 0; i < matrix.length; i++) {
        for (var j = 0; j < matrix[i].length; j++) {
            matrix[i][j] === 0 ? storeCoord.push({
                x: i,
                y: j
            }) : false;
        }
    }
    len = storeCoord.length;
    var tmp = Math.floor(Math.random() * len),
        x = storeCoord[tmp].x;
    y = storeCoord[tmp].y;
    matrix[x][y] = number;
}

// pc键盘监听
document.body.addEventListener("keydown", function(e) {
    var keyCode = e.keyCode;
    switch (keyCode) {
        case 37:
            self.move("left");
            break;
        case 38:
            self.move("up");
            break;
        case 39:
            self.move("right");
            break;
        case 40:
            self.move("down");
            break;
    }
    if (keyCode >= 37 && keyCode <= 40) {
        e.preventDefault();
    }
}, false);
// 移动端touch监听
matrixPanel.addEventListener("touchstart", function(e) {
    touchX = e.touches[0].pageX;
    touchY = e.touches[0].pageY;
    e.preventDefault();
}, false);
matrixPanel.addEventListener("touchend", function(e) {
    var offsetX = e.changedTouches[0].pageX - touchX;
    var offsetY = e.changedTouches[0].pageY - touchY;
    var towards;

    if (Math.abs(offsetX) < 3 || Math.abs(offsetY) < 3) {
        return;
    }
    // 获取手指移动的方向  根据偏移量来计算
    if (offsetX > 0 && Math.abs(offsetX) > Math.abs(offsetY)) {
        towards = "right";
    } else if (offsetX < 0 && Math.abs(offsetX) > Math.abs(offsetY)) {
        towards = "left";
    } else if (offsetY > 0 && Math.abs(offsetY) > Math.abs(offsetX)) {
        towards = "down";
    } else {
        towards = "up";
    }
    self.move(towards);
    e.preventDefault();
}, false);

// 撤销
Game.prototype.undo = function() {
    if (progressList.length <= 1) {
        return;
    }
    progressList.pop();
    var obj = progressList.slice(-1);
    matrix = Utils.deepClone(obj[0].matrix);
    score = obj[0].score;
    // 变为未结束
    gameOverState = false;
}