Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
<html>
<head lang="zh-en">
    <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> 2048</title>

    <link rel="stylesheet" type="text/css" href="2048.css"/>
    <script src="https://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
    <script src="support2048.js"></script>
    <script src="showanimation2048.js"></script>
    <script src="main2048.js"></script>

</head>
<body>
    <header>
        <h1>2048</h1>
        <a href="javascript:newgame();" id="newgamebutton">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 class="over" >
               <div class="over-frame">GAMEOVER!</div>
             <a href="javascript:newgame();" id="newgamebutton">New Game</a>
          </div>
    </div>


</body>
</html>
              
            
!

CSS

              
                header{
    display: block;
    margin: 0 auto;
    width: 100%;
    text-align: center;
}
header h1{
    font-family: Arial;
    font-size: 40px;
    font-weight: bold;
}
header #newgamebutton {
    display: block;
    margin: 20px auto;
    width: 100px;
    padding: 10px 10px;
    background-color: #8f7a66;

    font-family: Arial;
    color: white;
    border-radius: 10px;
    text-decoration: none;
}
header #newgamebutton:hover{
    background-color: #9f8b77;
}
header p{
    font-family: Arial;
    font-size: 20px;
    margin: 20px auto;
}
#grid-container{
    width: 460px;
    height: 460px;

    padding: 20px;
    margin: 20px  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-size: 60px;
    font-weight: bold;
    line-height: 100px;
    text-align: center;

    position: absolute;
}
.over {
    width: 100%;
    height: 100%;
    background: rgba(204,204,204,0.5);
    position: absolute;
    top: 0;
    left: 0;
    display: none;
}
.over-frame {
    margin: 0 auto;
    margin-top: 40%;
    font-size: 30px;
    text-align: center;
    cursor: pointer;
}
              
            
!

JS

              
                /**
 * Created by Administrator on 2014/10/31.
 */
documentWidth =window.screen.availWidth;
griContainerWidth = 0.92 * documentWidth;
cellSideLength = 0.18 * documentWidth;
cellSpace = 0.04 * documentWidth;

function getPosTop(i,j){
    return cellSpace + i*(cellSideLength +cellSpace);
}
function getPosLeft(i,j){
    return cellSpace + j*(cellSideLength +cellSpace);;
}
function getNumberBackgroundColor(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 getNumberFontSize(number) {
    switch (number){
        case 2:
        case 4:
        case 8:
        case 16:
        case 32:
        case 64:
        case 128:
        case 256:
        case 512: return 0.6*cellSideLength;break;
        case 1024:
        case 2048:
        case 4096:
        case 8192:return 0.4*cellSideLength;break;
    }
    return "black";
}
function getNumberColor(number){
    if(number<=4){
        return "#776e65";
    }
    return "white";
}
function nospace(board) {
    for(var i=0;i<4;i++){
       // board[i] = new Array();
        for(var j=0;j<4;j++){
            if(board[i][j]==0){
                    return false;
            }
        }
    }
    return true;
}
function canMoveLeft(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-1] ==board[i][j]){
                    return true;
                }
            }
        }
    }
    return false;
}
function canMoveRight(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+1] ==board[i][j]){
                    return true;
                }
            }
        }
    }
    return false;
}
function canMoveUp(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 canMoveDown(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 noBlockHorizontal(row,col1,col2,board){
    for(var i= col1+1;i< col2;i++){
            if(board[row][i]!=0){
                    return false;
            }

    }
    return true;
}

function noBlockVertical( 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(canMoveLeft(board) || canMoveRight(board) || canMoveUp(board) || canMoveDown(board))
       return false;
    return true;
}
/*************************/
/**
 * Created by Administrator on 2014/10/31.
 */
function showNumberWidthAnimation(i,j,randNumber){
//i,j坐标(x,y)
    var numberCell = $("#number-cell-"+i+'-'+j);
    numberCell.css('background-color',getNumberBackgroundColor(board[i][j]));
    numberCell.css('color',getNumberColor(board[i][j]));
    numberCell.text(board[i][j]);
    numberCell.animate({
        width:cellSideLength+"px",
        height:cellSideLength+"px",
        top:getPosTop(i,j),
        left:getPosLeft(i,j)
    },100);
}
function showMoveAnimation(fromx,fromy,tox,toy){
    var numberCell = $("#number-cell-"+fromx+'-'+fromy);
    numberCell.animate({
        top:getPosTop(tox,toy),
        left:getPosLeft(tox,toy)
    },200);
}
function updateScore(score){
    $("#score").text(score);
}
/********main2048***********/
/**
 * Created by Administrator on 2014/10/31.
 */
var board = new Array();
var score = 0;
var hasConficted=new Array();
var startx= 0;
var starty= 0;
var endx= 0;
var endy= 0;
$(function(){
    prepareForMobile();
    newgame();
});
function prepareForMobile(){
    if(documentWidth >500){
        griContainerWidth = 500;
        cellSpace= 20;
        cellSideLength = 100 ;
    }
    $("#grid-container").css({
        width: griContainerWidth -2*cellSpace,
        height: griContainerWidth -2*cellSpace,
        padding: cellSpace

    });
    $(".grid-cell").css({
        width: cellSideLength,
        height: cellSideLength,
        borderRadius: 0.02*cellSideLength
    })
}
function newgame(){
    //初始化棋盘格
    init();
    //在两个格子中生成数字
    generateOneNumber();
    generateOneNumber();
}
function init(){
    for(var i=0;i<4;i++){
        for(var j=0;j<4;j++){
            var gridCell = $("#grid-cell-"+i+"-"+j);
            gridCell.css("top",getPosTop(i,j));
            gridCell.css("left",getPosLeft(i,j));
        }
    }
    for(var i=0;i<4;i++){
        board[i] = new Array();
        hasConficted[i] = new Array();
        for(var j=0;j<4;j++){
            board[i][j]=0;
            hasConficted[i][j]=false;
        }
    }
    $(".over").hide();
    updateBoardView();
    score=0;
    updateScore(score);
};
function updateBoardView(){
    $(".number-cell").remove();
    for(var i=0;i<4;i++){
       // board[i] = new Array();
        for(var j=0;j<4;j++){
         //   board[i][j]=0;
            $("#grid-container").append('<div class="number-cell" id="number-cell-'+i+'-'+j+'"></div>');
            var theNumberCell = $("#number-cell-"+i+'-'+j);

            if(board[i][j]==0){
                theNumberCell.css({
                    width:"0px",
                    height:"0px",
                    top:getPosTop(i,j)+cellSideLength /2,
                    left:getPosLeft(i,j)+cellSideLength /2
                });
            }else{
                theNumberCell.css({
                    width:cellSideLength+"px",
                    height: cellSideLength+"px",
                    top:getPosTop(i,j),
                    left:getPosLeft(i,j)

                });
                theNumberCell.css('background-color',getNumberBackgroundColor(board[i][j]));
                theNumberCell.css('color',getNumberColor(board[i][j]));
                theNumberCell.css('font-size',getNumberFontSize(board[i][j]));

                theNumberCell.text(board[i][j]);
            }
            hasConficted[i][j]=false;

        }
    }
    $(".number-cell").css({
        lineHeight:cellSideLength+"px",
        fontSize:0.6*cellSideLength+"px"
    })
};
function generateOneNumber() {

    if(nospace(board)){//判断是否有空格位置存放
        return false;
    }
    var times=0;
    //随机一个位置
    var randx = parseInt(Math.floor(Math.random() * 4));
    var randy = parseInt(Math.floor(Math.random() * 4));
    var temp = [];
    for(var i=0; i<4; i++)
    {
        for(var j=0; j<4; j++)
        {
            if(board[i][j] == 0)
                temp.push({x:i,y:j});
        }
    }
    if(temp.length)
    {
        var randoms= Math.random();
        var ran = parseInt(Math.random() * temp.length);
       // tempemp[ran]
        randx = temp[ran].x;
        randy = temp[ran].y;
       // console.log( ,randoms,randoms*temp.length)
//temp[ran] 就是你需要的...
    }
//    while(times < 50){
//        if(board[randx][randy]==0){
//            break;
//        }
//        randx = parseInt(Math.floor(Math.random() * 4));
//        randy = parseInt(Math.floor(Math.random() * 4));
//        times ++;
//    }
//    if(times==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 randNumber = Math.random() <0.5 ? 2:4;
    //在随机位置显示随机数字

    board[randx][randy] =randNumber;
    showNumberWidthAnimation(randx,randy,randNumber);
    return true;
};

$(document).keydown(function(event){

    switch (event.keyCode){
        case 37://left
            event.preventDefault();
            if(moveLeft()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            break;
        case 38://up
            event.preventDefault();
            if(moveUp()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }

            break;
        case 39://right
            event.preventDefault();
            if(moveRight()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
            event.preventDefault();
            break;
        case 40://down
            event.preventDefault();
            if(moveDown()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }

            break;
        default:  break;
    }
});
document.addEventListener('touchstart',function(event){

    startx = event.touches[0].pageX;
    starty = event.touches[0].pageY;
    var containerY = $('#grid-container').offset().top;
    if(containerY>=starty)
        return true;
});
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 *documentWidth && Math.abs(deltay) < 0.3 *documentWidth){
        return ;
    }
    //x
    if(Math.abs(deltax) >= Math.abs(deltay)){
        if(deltax>0){

            if(moveRight()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
        }else{

            if(moveLeft()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
        }
    }//y
    else{

        if(deltay>0){
            if(moveDown()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
        }else{
            if(moveUp()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
        }
    }

});
function isgameover(){
    if(nospace(board) && nomove(board)){
        gameover();
    }
};
function gameover(){
   // alert("gameover");
    $(".over").show();
};
function moveLeft(){
    if(!canMoveLeft(board)){
        return false;
    }
    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 && noBlockHorizontal(i,k,j,board) ){
                        //move
                        showMoveAnimation(i,j,i,k);
                        board[i][k]=board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if(board[i][k]==board[i][j] && noBlockHorizontal(i,k,j,board) && !hasConficted[i][k]){
                        //move
                        showMoveAnimation(i,j,i,k);

                        //add
                        board[i][k] +=board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[i][k];
                        updateScore(score);

                        hasConficted[i][k] = true;
                        continue;
                    }
                }
            }
        }
    }
    setTimeout("updateBoardView()",200);
   // updateBoardView();
    return true;
}
function moveRight(){
    if(!canMoveRight(board)){
        return false;
    }
    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 && noBlockHorizontal(i,j,k,board)){
                        //move
                        showMoveAnimation(i,j,i,k);
                        board[i][k]=board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if(board[i][k]==board[i][j] && noBlockHorizontal(i,j,k,board) && !hasConficted[i][k]){
                        //move
                        showMoveAnimation(i,j,i,k);

                        //add
                        board[i][k] +=board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[i][k];
                        updateScore(score);
                        hasConficted[i][k]= true;

                        continue;
                    }
                }
            }
        }
    }
    setTimeout("updateBoardView()",200);
    // updateBoardView();
    return true;
}
function moveUp(){
    if(!canMoveUp(board)){
        return false;
    }
    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 && noBlockVertical(j,k,i,board)){
                        //move
                        showMoveAnimation(i,j,k,j);
                        board[k][j]=board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if(board[k][j]==board[i][j] && noBlockVertical(j,k,i,board) && !hasConficted[k][j]){
                        //move
                        showMoveAnimation(i,j,k,j);

                        //add
                        board[k][j] +=board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[k][j];
                        updateScore(score);

                        hasConficted[k][j]= true;
                        continue;
                    }
                }
            }
        }
    }
    setTimeout("updateBoardView()",200);
    // updateBoardView();
    return true;
}
function moveDown(){
    if(!canMoveDown(board)){
        return false;
    }
    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 && noBlockVertical(j,i,k,board)){
                        //move
                        showMoveAnimation(i , j , k , j);
                        board[k][j]=board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if(board[k][j]==board[i][j] && noBlockVertical(j,i,k,board) && !hasConficted[k][j]){
                        //move
                        showMoveAnimation(i , j , k , j);

                        //add
                        board[k][j] +=board[i][j];
                        board[i][j] = 0;
                        //add score
                        score += board[k][j];
                        updateScore(score);

                        hasConficted[k][j]= true;
                        continue;
                    }
                }
            }
        }
    }
    setTimeout("updateBoardView()",200);
    // updateBoardView();
    return true;
}

              
            
!
999px

Console