网页版2048-编译属于你的2048
发布在网页版20482015年1月31日view:3469HTML5前端开发
在文章任何区域双击击即可给文章添加【评注】!浮到评注点上可以查看详情。

网页版2048

一、实验说明

1. 环境介绍

本实验环境采用带桌面的Ubuntu Linux环境,实验中会用到的程序

LX终端(LXTerminal): Linux命令行终端,打开后会进入Bash环境,可以使用Linux命令

Firefox:浏览器,可以用在需要前端界面的课程里,只需要打开环境里写的HTML/JS页面即可

GVim:非常好用的编辑器,最简单的用法可以参考课程Vim编辑器

二、项目介绍

相信大家都玩过手机上的2048,既然手机上已经有了,那么今天我们来做一个网页版的2048,先上一张截图

大家看了截图,是不是马上就想动手完成它,下面我们就来开始。

三、项目实战

1. 页面布局

首先我们需要有一张4X4的表格:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <title>ShiYanLou-2048</title>
    <link rel="stylesheet" href="style.css"/>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
    <script type="text/javascript" src="showanimation.js"></script>
    <script type="text/javascript" src="support.js"></script>
</head>
<body>
    <header>
        <h1>ShiYanLou-2048</h1>
        <a href="javascript:new_game();" id="new_game_button">New Game</a>
        <p>score: <span id="score">0</span></p>
    </header>
    <div id="grid_container">
        <div class="grid_cell" id="grid_cell_0_0"></div>
        <div class="grid_cell" id="grid_cell_0_1"></div>
        <div class="grid_cell" id="grid_cell_0_2"></div>
        <div class="grid_cell" id="grid_cell_0_3"></div>

        <div class="grid_cell" id="grid_cell_1_0"></div>
        <div class="grid_cell" id="grid_cell_1_1"></div>
        <div class="grid_cell" id="grid_cell_1_2"></div>
        <div class="grid_cell" id="grid_cell_1_3"></div>

        <div class="grid_cell" id="grid_cell_2_0"></div>
        <div class="grid_cell" id="grid_cell_2_1"></div>
        <div class="grid_cell" id="grid_cell_2_2"></div>
        <div class="grid_cell" id="grid_cell_2_3"></div>

        <div class="grid_cell" id="grid_cell_3_0"></div>
        <div class="grid_cell" id="grid_cell_3_1"></div>
        <div class="grid_cell" id="grid_cell_3_2"></div>
        <div class="grid_cell" id="grid_cell_3_3"></div>
    </div>
</body>
</html>

然后需要给页面和每个格子,加上样式:

header {
    display: block;
    margin: 0 auto;
    width: 100%;
    text-align: center;
}

header h1 {
    font-family: Arial;
    font-size: 60px;
    font-weight: bold;
    margin: 0 auto;
}

header #new_game_button {
    display: block;
    margin: 0px auto;
    width: 100px;
    padding: 10px 10px;
    background-color: #8f7a66;
    font-family: Arial;
    color: white;
    border-radius: 10px;
    text-decoration: none;
}

header #new_game_button:hover {
    background-color: #9f8b77;
}

header p {
    font-family: Arial;
    font-size: 25px;
    margin: 5px auto;
}

#grid_container {
    width: 460px;
    height: 460px;
    padding: 20px;
    margin: 0px auto;
    background-color: #bbada0;
    border-radius: 10px;
    position: relative;
}

.grid_cell {
    width: 100px;
    height: 100px;
    border-radius: 6px;
    background-color: #ccc0b3;
    position: absolute;
}

.number_cell {
    border-radius: 6px;
    font-family: Arial;
    font-weight: bold;
    font-size: 60px;
    line-height: 100px;
    text-align: center;
    position: absolute;
}

完成这步后:

2. 初始化棋局

现在移动端设备越来越流行,所以我们需要做自适应处理以应对各种大小的屏幕,游戏开始的时候,我们需要在期盘上随机生成两个数字,这里通过JavaScript代码来实现:

//在main.js中
var board = new Array();    //每个格子的数字
var score = 0;  //分数
var has_conflicted = new Array();   //解决连续消除的标记
var startx = 0; //移动端触摸屏幕时开始点的x坐标
var starty = 0; //移动端触摸屏幕时开始点的y坐标
var endx = 0;   //移动端触摸屏幕时结束点的x坐标
var endy = 0;   //移动端触摸屏幕时结束点的y坐标
var success_string = 'Success';
var gameover_string = 'GameOver';

//HTML文档加载完成后,初始化棋局
$(document).ready(function() {
    //做自适应处理
    prepare_for_mobile();
    new_game();
});

//开始新游戏
function new_game() {
    //初始化棋盘
    init();
    //在随机两个格子生成数字
    generate_one_number();
    generate_one_number();
}

//初始化
function init() {
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            var grid_cell = $('#grid_cell_' + i + '_' + j);
            grid_cell.css('top', get_pos_top(i, j));
            grid_cell.css('left', get_pos_left(i, j));
        }
    }
    for (var i = 0; i < 4; i++) {
        board[i] = new Array();
        has_conflicted[i] = new Array();
        for (var j =0; j < 4; j++) {
            board[i][j] = 0;
            has_conflicted[i][j] = false;
        }
    }
    update_board_view();
    score = 0;
    update_score(score);
}

//更新棋局
function update_board_view() {
    $('.number_cell').remove();
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            $('#grid_container').append('<div class="number_cell" id="number_cell_' + i + '_' + j + '"></div>');
            var number_cell = $('#number_cell_' + i + '_' + j);
            if (board[i][j] == 0) {
                number_cell.css('width', '0px');
                number_cell.css('height', '0px');
                number_cell.css('top', get_pos_top(i, j) + cell_side_length / 2);
                number_cell.css('left', get_pos_left(i, j) + cell_side_length / 2);
            } else {
                number_cell.css('width', cell_side_length);
                number_cell.css('height', cell_side_length);
                number_cell.css('top', get_pos_top(i, j));
                number_cell.css('left', get_pos_left(i, j));
                number_cell.css('background-color', get_number_background_color(board[i][j]));
                number_cell.css('color', get_number_color(board[i][j]));
                number_cell.text(board[i][j]);
            }
            has_conflicted[i][j] = false;
        }
    }
    $('.number_cell').css('line-height', cell_side_length + 'px');
    $('.number_cell').css('font-size', 0.6 * cell_side_length + 'px');
}

//随机在一个格子生成数字
function generate_one_number() {
    if (nospace(board)) {
        return false;
    }
    //随机一个位置
    var randx = parseInt(Math.floor(Math.random() * 4));
    var randy = parseInt(Math.floor(Math.random() * 4));
    var time = 0;
    while (time < 50) {
        if (board[randx][randy] == 0) {
            break;
        }
        randx = parseInt(Math.floor(Math.random() * 4));
        randy = parseInt(Math.floor(Math.random() * 4));
        time++;
    }
    if (time == 50) {
        for (var i = 0; i < 4; i++) {
            for (var j = 0; j < 4; j++) {
                if (board[i][j] == 0) {
                    randx = i;
                    randy = j;
                }
            }
        }
    }
    //随机一个数字
    var rand_number = Math.random() < 0.5 ? 2 : 4;
    //在随机位置显示随机数字
    board[randx][randy] = rand_number;
    show_number_with_animation(randx, randy, rand_number);
    return true;
}

//自适应处理
function prepare_for_mobile() {
    if (document_width > 500) {
        grid_container_width = 500;
        cell_side_length = 100;
        cell_space = 20;
    }
    $('#grid_container').css('width', grid_container_width - 2 * cell_space);
    $('#grid_container').css('height', grid_container_width - 2 * cell_space);
    $('#grid_container').css('padding', cell_space);
    $('#grid_container').css('border-radius', 0.02 * grid_container_width);
    $('.grid_cell').css('width', cell_side_length);
    $('.grid_cell').css('height', cell_side_length);
    $('.grid_cell').css('border-radius', 0.02 * grid_container_width);
}
//在support.js中
document_width = window.screen.availWidth;  //屏幕宽度
grid_container_width = 0.92 * document_width;   //期盘宽度
cell_side_length = 0.18 * document_width;   //格子的大小
cell_space = 0.04 * document_width; //格子之间的间隔

//获得相应格子距离期盘顶部的距离
function get_pos_top(i, j) {
    return cell_space + i * (cell_space + cell_side_length);
}

//获得相应格子距离棋盘左边的距离
function get_pos_left(i, j) {
    return cell_space + j * (cell_space + cell_side_length);
}

//获得相应数字的背景色
function get_number_background_color(number) {
    switch (number) {
        case 2: return '#eee4da'; break;
        case 4: return '#ede0c8'; break;
        case 8: return '#f2b179'; break;
        case 16: return '#f59563'; break;
        case 32: return '#f67c5f'; break;
        case 64: return '#f65e3b'; break;
        case 128: return '#edcf72'; break;
        case 256: return '#edcc61'; break;
        case 512: return '#9c0'; break;
        case 1024: return '#33b5e5'; break;
        case 2048: return '#09c'; break;
        case 4096: return '#a6c'; break;
        case 8192: return '#93c'; break;
    }
    return 'black';
}

//获得相应数字的颜色
function get_number_color(number) {
    if (number <= 4)
        return '#776e65';
    return 'white';
}

//判断棋盘上是否还有空格子
function nospace(board) {
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (board[i][j] == 0) {
                return false;
            }
        }
    }
    return true;
}
//在showanimation.js中
//动画显示数字格子
function show_number_with_animation(i, j, rand_number) {
    var number_cell = $('#number_cell_' + i + '_' + j);
    number_cell.css('background-color', get_number_background_color(rand_number));
    number_cell.css('color', get_number_color(rand_number));
    number_cell.text(rand_number);
    number_cell.animate({
        width: cell_side_length,
        height: cell_side_length,
        top: get_pos_top(i, j),
        left: get_pos_left(i, j)
    }, 50);
}

//更新分数
function update_score(score) {
    $('#score').text(score);
}

完成这步后:

3. 动起来

上面我们完成了布局和初始化,最后我们就要实现让它能移动,并能够消除,直至游戏成功或失败:

//在main.js中加入
//监听键盘的上下左右移动
$(document).keydown(function(event) {
    if ($('#score').text() == success_string) {
        new_game();
        return;
    }
    switch (event.keyCode) {
        case 37: //left
            event.preventDefault();
            if (move_left()) {
                setTimeout('generate_one_number()', 210);
                setTimeout('is_gameover()', 300);
            }
            break;
        case 38: //up
            event.preventDefault();
            if (move_up()) {
                setTimeout('generate_one_number()', 210);
                setTimeout('is_gameover()', 300);
            }
            break;
        case 39: //right
            event.preventDefault();
            if (move_right()) {
                setTimeout('generate_one_number()', 210);
                setTimeout('is_gameover()', 300);
            }
            break;
        case 40: //down
            event.preventDefault();
            if (move_down()) {
                setTimeout('generate_one_number()', 210);
                setTimeout('is_gameover()', 300);
            }
            break;
        default:
            break;
    }
});

//监听移动设备的触摸开始
document.addEventListener('touchstart', function(event) {
    startx = event.touches[0].pageX;
    starty = event.touches[0].pageY;
});

//监听移动设备的触摸移动
document.addEventListener('touchmove', function(event) {
    event.preventDefault();
});

//监听移动设备的触摸结束
document.addEventListener('touchend', function(event) {
    endx = event.changedTouches[0].pageX;
    endy = event.changedTouches[0].pageY;

    var deltax = endx - startx;
    var deltay = endy - starty;
    if (Math.abs(deltax) < 0.3 * document_width && Math.abs(deltay) < 0.3 * document_width) {
        return;
    }
    if ($('#score').text() == success_string) {
        new_game();
        return;
    }
    //x
    if (Math.abs(deltax) >= Math.abs(deltay)) {
        if (deltax > 0) {
            //move right
            if (move_right()) {
                setTimeout('generate_one_number()', 210);
                setTimeout('is_gameover()', 300);
            }
        } else {
            //move left
            if (move_left()) {
                setTimeout('generate_one_number()', 210);
                setTimeout('is_gameover()', 300);
            }
        }
    } else {    //y
        if (deltay > 0) {
            //move down
            if (move_down()) {
                setTimeout('generate_one_number()', 210);
                setTimeout('is_gameover()', 300);
            }
        } else {
            //move up
            if (move_up()) {
                setTimeout('generate_one_number()', 210);
                setTimeout('is_gameover()', 300);
            }
        }
    }
});

//向左移动
function move_left() {
    if (!can_move_left(board)) {
        return false;
    }
    //move left
    for (var i = 0; i < 4; i++) {
        for (var j = 1; j < 4; j++) {
            if (board[i][j] != 0) {
                for (var k = 0; k < j; k++) {
                    if (board[i][k] == 0 && no_block_horizontal(i, k, j, board)) {
                        show_move_animation(i, j, i, k);
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        break;
                    } else if (board[i][k] == board[i][j] && no_block_horizontal(i, k, j, board) && !has_conflicted[i][k]) {
                        show_move_animation(i, j, i, k);
                        board[i][k] += board[i][j]
                        board[i][j] = 0;
                        //add score
                        score += board[i][k];
                        update_score(score);
                        has_conflicted[i][k] = true;
                        break;
                    }
                }
            }
        }
    }
    setTimeout('update_board_view()', 200);
    return true;
}

//向右移动
function move_right() {
    if (!can_move_right(board)) {
        return false;
    }
    //move right
    for (var i = 0; i < 4; i++) {
        for (var j = 2; j >= 0; j--) {
            if (board[i][j] != 0) {
                for (var k = 3; k > j; k--) {
                    if (board[i][k] == 0 && no_block_horizontal(i, j, k, board)) {
                        show_move_animation(i, j, i, k);
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        break;
                    } else if (board[i][k] == board[i][j] && no_block_horizontal(i, j, k, board) && !has_conflicted[i][k]) {
                        show_move_animation(i, j, i, k);
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[i][k];
                        update_score(score);
                        has_conflicted[i][k] = true;
                        break;
                    }
                }
            }
        }
    }
    setTimeout('update_board_view()', 200);
    return true;
}

//向上移动
function move_up() {
    if (!can_move_up(board)) {
        return false;
    }
    //move up
    for (var j = 0; j < 4; j++) {
        for (var i = 1; i < 4; i++) {
            if (board[i][j] != 0) {
                for (var k = 0; k < i; k++) {
                    if (board[k][j] == 0 && no_block_vertical(j, k, i, board)) {
                        show_move_animation(i, j, k, j);
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        break;
                    } else if (board[k][j] == board[i][j] && no_block_vertical(j, k, i, board) && !has_conflicted[k][j]) {
                        show_move_animation(i, j, k, j);
                        board[k][j] += board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[k][j];
                        update_score(score);
                        has_conflicted[k][j] = true;
                        break;
                    }
                }
            }
        }
    }
    setTimeout('update_board_view()', 200);
    return true;
}

//向下移动
function move_down() {
    if (!can_move_down(board)) {
        return false;
    }
    //move down
    for (var j = 0; j < 4; j++) {
        for (var i = 2; i >= 0; i--) {
            if (board[i][j] != 0) {
                for (var k = 3; k > i; k--) {
                    if (board[k][j] == 0 && no_block_vertical(j, i, k, board)) {
                        show_move_animation(i, j, k, j);
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        break;
                    } else if (board[k][j] == board[i][j] && no_block_vertical(j, i, k, board) && !has_conflicted[k][j]) {
                        show_move_animation(i, j, k, j);
                        board[k][j] += board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[k][j];
                        update_score(score);
                        has_conflicted[k][j] = true;
                        break;
                    }
                }
            }
        }
    }
    setTimeout('update_board_view()', 200);
    return true;    
}

//判断游戏成功或失败
function is_gameover() {
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (board[i][j] == 2048) {
                update_score(success_string);
                return;
            }
        }
    }
    if (nospace(board) && nomove(board)) {
        gameover();
    }
}

//游戏结束时更新游戏失败的文字
function gameover() {
    update_score(gameover_string);
}
//在support.js中加入
//判断是否能向左移动
function can_move_left(board) {
    for (var i = 0; i < 4; i++) {
        for (var j = 1; j < 4; j++) {
            if (board[i][j] != 0) {
                if (board[i][j - 1] == 0 || board[i][j] == board[i][j - 1]) {
                    return true;
                }
            }
        }
    }
    return false;
}

//判断是否能向右移动
function can_move_right(board) {
    for (var i = 0; i < 4; i++) {
        for (var j = 2; j >= 0; j--) {
            if (board[i][j] != 0) {
                if (board[i][j + 1] == 0 || board[i][j] == board[i][j + 1]) {
                    return true;
                }
            }
        }
    }
    return false;
}

//判断是否能向上移动
function can_move_up(board) {
    for (var j = 0; j < 4; j++) {
        for (var i = 1; i < 4; i++) {
            if (board[i][j] != 0) {
                if (board[i - 1][j] == 0 || board[i - 1][j] == board[i][j]) {
                    return true;
                }
            }
        }
    }
    return false;
}

//判断是否能向下移动
function can_move_down(board) {
    for (var j = 0; j < 4; j++) {
        for (var i = 2; i >= 0; i--) {
            if (board[i][j] != 0) {
                if (board[i + 1][j] == 0 || board[i + 1][j] == board[i][j]) {
                    return true;
                }
            }
        }
    }
    return false;
}

//判断水平方向上时候是否有空格子
function no_block_horizontal(row, col1, col2, board) {
    for (var i = col1 + 1; i < col2; i++) {
        if (board[row][i] != 0) {
            return false;
        }
    }
    return true;
}

//判断垂直方向上时候是否有空格子
function no_block_vertical(col, row1, row2, board) {
    for (var i = row1 + 1; i < row2; i++) {
        if (board[i][col] != 0) {
            return false;
        }
    }
    return true;
}

//判断是否还能移动
function nomove(board) {
    if (can_move_down(board) || can_move_up(board) || can_move_right(board) || can_move_left(board)) {
        return false;
    }
    return true;
}
//在showanimation.js中加入
//格子移动时有动画效果
function show_move_animation(fromx, fromy, tox, toy) {
    var number_cell = $('#number_cell_' + fromx + '_' + fromy);
    number_cell.animate({
        top: get_pos_top(tox, toy),
        left: get_pos_left(tox, toy)
    }, 200);
}

到此我们的网页版2048就完成了。

大部分看到这里的男神&女神们会猛戳这里去实践—–为你提供在线编译环境

评论
发表评论
2年前
赞了此文章!
2年前
赞了此文章!
WRITTEN BY
实验楼官方微博
“实验楼——www.shiyanlou.com",一个致力于通过动手实践方式提升IT人群(包括拟就业的大学生和从业者)在求职和职业规划中所必备的职业技能的网站!
TA的新浪微博
PUBLISHED IN
网页版2048

相信大家都玩过手机上的2048,既然手机上已经有了,那么今天我们来做一个网页版的2048~做出一个属于你自己的2048

我的收藏