首页 > 代码库 > 重写2048游戏

重写2048游戏

在慕客网上看到一个叫2048的游戏,作者讲的不错。听听很激动,看着很多网友留言,遇到各种问题,于是打算自己写一遍。试玩了一遍别人写好的2048.感觉逻辑还算容易理解。一种写下来,还是遇到了不少问题,但是冷静的想想,很快就找出问题,并解决了。最后,终于完成了自己的2048私人定制版。

下面是最终成果:

写完之后,其实代码一点都不难,会用jquery就可以了。

下面我自己的代码贴一下:

index.html

<!DOCTYPE html><html><head>    <meta charset="UTF-8" />        <title>2048 私人定制</title>    <link rel="stylesheet" type="text/css" href="2048.css" />    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script>    <script type="text/javascript" src="support2048.js"></script>    <script type="text/javascript" src="showanimation2048.js"></script>    <script type="text/javascript" src="main2048.js"></script></head><body>    <header>        <h1>2048 升官版</h1>        <a href="javascript:newgame();" id="newgamebutton">New Game</a>        <p>贡献值 : <span id="score">0</span></p>    </header>    <div id="grid-container"></div>        <div style="width:500px;margin:10px auto;text-align:center;">请使用键盘上的上、下、左、右的按键进行游戏。</div></body></html>

support2048.js

/** * Created by *** on 14-4-11. * modify by ouyangli on 14-8-15. * @author <278500368@qq.com> * my site: http://www.imooc.com/ */function getPosTop( i ,j, size){    var top = size.paddingTop;    var height = size.cellHeight + top;    return top + i*height;}function getPosLeft( i , j,size ){    var left = size.paddingLeft;    var width = size.cellWidth + left;    return left + j*width;}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 getNumberColor( number ){    if( number <= 4 )        return "#776e65";    return "white";}//生成单元格function setGridCell(i,j){    return $(‘<div class="grid-cell" id="grid-cell-‘+i+‘-‘+j+‘"></div>‘);}//获取单元格function getGridCell(i,j){    return $(‘#grid-cell-‘+i+"-"+j);}//生成数字块function setNumberCell(i,j){    return $(‘<div class="number-cell" id="number-cell-‘+i+‘-‘+j+‘"></div>‘ );}//获取数字块function getNumberCell(i,j){    return $(‘#number-cell-‘ + i + "-" + j );}function getNumberText( number ){    switch( number ){        case 2:return "学生";break;        case 4:return "工人";break;        case 8:return "企业家";break;        case 16:return "人大代表";break;        case 32:return "市长";break;        case 64:return "省长";break;        case 128:return "部长";break;        case 256:return "副总理";break;        case 512:return "总理";break;        case 1024:return "副主席";break;        case 2048:return "国家主席";break;        case 4096:return "#a6c";break;        case 8192:return "#93c";break;    }    return "black";}//修正字号function getNumberTextSize(number){    var str = getNumberText(number);    switch(str.length){        case 2 : return ‘1.5em‘;        case 3 : return ‘1em‘;        case 4 : return ‘0.25em‘;        default: return ‘0.2em‘;    }}//生成一个0到4之间的随机数function getRandomNum () {    return Math.floor( Math.random()  * 4 )}//手动找出空闲位置function setPosition (board) {    for( var i = 0 ; i < 4 ; i ++ )        for( var j = 0 ; j < 4 ; j ++ ){            if( board[i][j] == 0 ){                return [i,j];            }        }}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;}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;}

showanimation.js

/** * Created by *** on 14-4-11. * modify by ouyangli on 14-8-15. * @author <278500368@qq.com> * my site: http://www.imooc.com/ */function showNumberWithAnimation( i , j , randNumber ,size){    getNumberCell(i,j).css({        backgroundColor : getNumberBackgroundColor( randNumber ),        color : getNumberColor( randNumber ),        fontSize : getNumberTextSize(randNumber)     }).text( getNumberText( randNumber ) ).animate({        width : size.cellWidth,        height : size.cellWidth    },200);}function showMoveAnimation( fromx , fromy , tox, toy ,size){    getNumberCell(fromx,fromy).animate({        top:getPosTop( tox,toy ,size),        left:getPosLeft( tox ,toy, size )    },200);     }function updateScore( score ){    $(‘#score‘).text( score );}

main.js
/** * Created by *** on 14-4-11. * modify by ouyangli on 14-8-15. * @author <278500368@qq.com> * my site: http://www.imooc.com/ */var board = new Array();var score = 0;var hasConflicted = new Array();var size = {};$(document).ready(function(){    newgame();});function newgame(){    //初始化棋盘格    init();    //在随机两个格子生成数字    generateOneNumber();    generateOneNumber();}function init(){    //获取棋盘尺寸    setWrapSize();    setFontSize();    //创建格子    createBoardView();    //初始化数据    for( var i = 0 ; i < 4 ; i ++ ){        board[i] = new Array();        hasConflicted[i] = new Array();        for( var j = 0 ; j < 4 ; j ++ ){            board[i][j] = 0;            hasConflicted[i][j] = false;        }    }    //更新视图    updateBoardView();    score = 0;    $(‘#score‘).text( score );}//设置棋盘的宽高信息function setWrapSize(){    // 这里有一个等宽分布格子的公式    // 棋盘宽度 = 格子宽 * 4 + 间距 * 5    // 在没有提供棋盘尺寸时,取屏幕最小长度的60%,    var boardWidth = size.boardWidth || function(Width){            return Math.round(Width * 0.6);        }(Math.min(window.innerWidth,window.innerHeight)),        boardHeight = size.boardHeight || boardWidth,        maxCellWidth = Math.floor(boardWidth / 4),        maxCellHeight = Math.floor(boardHeight / 4),        paddingLeft = Math.ceil(maxCellWidth * 0.2),        paddingTop = Math.ceil(maxCellHeight * 0.2),        cellWidth = Math.floor((boardWidth - 5 * paddingLeft) / 4),        cellHeight = Math.floor((boardHeight - 5 * paddingTop) / 4);    size = {        boardWidth : boardWidth,        boardHeight : boardHeight,        paddingLeft : paddingLeft,        paddingTop : paddingTop,        cellWidth : cellWidth,        cellHeight: cellWidth    };}//设置字体大体function setFontSize(){    var width = size.boardWidth;    if(width < 320){        size.fontSize = ‘12px‘;    }else if(width > 320 && width < 800){        size.fontSize = ‘16px‘;    }else{        size.fontSize = ‘22px‘;    }}//创建棋盘function createBoardView(){    var cell = ‘‘;    var frame = $(‘<div></div>‘);    for( var i = 0 ; i < 4 ; i ++ ){        for( var j = 0 ; j < 4 ; j ++ ){            cell  = setGridCell(i,j);            cell.css({                width : size.cellWidth,                height : size.cellHeight,                left : getPosLeft(i,j,size),                top : getPosTop(i,j,size)            })            frame.append(cell);        }    }    $(‘#grid-container‘).html(frame.html()).css({        width : size.boardWidth,        height: size.boardHeight,        fontSize : size.fontSize,        margin : ‘0 auto‘    });}function updateBoardView(){    $(".number-cell").remove();    for( var i = 0 ; i < 4 ; i ++ )        for( var j = 0 ; j < 4 ; j ++ ){                        var theNumberCell = setNumberCell(i,j);            var tag = getNumberText( board[i][j] );                        if( board[i][j] == 0 ){                theNumberCell.css({                    width : 0,                    height : 0,                    top : getPosTop(i,j,size),                    left : getPosLeft(i,j,size),                    lineHeight : size.cellHeight+‘px‘                })            }else{                theNumberCell.css({                    width : size.cellWidth,                    height: size.cellHeight,                    lineHeight : size.cellHeight+‘px‘,                    top : getPosTop(i,j,size),                    left : getPosLeft(i,j,size),                    color : getNumberColor( board[i][j] ),                    backgroundColor : getNumberBackgroundColor(board[i][j]),                    fontSize : getNumberTextSize(board[i][j])                }).text( tag );            }            $("#grid-container").append(theNumberCell);            hasConflicted[i][j] = false;        }}function generateOneNumber(){    var randx,randy,times=0,pos,randNumber;    if( nospace( board ) )        return false;    //随机一个位置    randx = getRandomNum();    randy = getRandomNum();    while( times < 50 ){        if( board[randx][randy] == 0 )            break;        randx = getRandomNum();        randy = getRandomNum();        times ++;    }    if( times == 50 ){        pos = setPosition(board);        randx = pos[0];        randy = pos[1];    }    //随机一个数字    randNumber = Math.random() < 0.5 ? 2 : 4;    //在随机位置显示随机数字    board[randx][randy] = randNumber;    showNumberWithAnimation( randx , randy , randNumber ,size);}$(document).keydown( function( event ){    switch( event.keyCode ){        case 37: //left            moveLeft();            break;        case 38: //up            moveUp();            break;        case 39: //right            moveRight();            break;        case 40: //down            moveDown();            break;        default: //default            break;    }});function isgameover(){    if( nospace( board ) && nomove( board ) ){        gameover();    }}function gameover(){    alert(‘gameover!‘);}function next () {    setTimeout(function() {        generateOneNumber();    },210);    setTimeout(function(){        isgameover();    },300);}function moveLeft(){    if( !canMoveLeft( board ) )        return false;    //moveLeft    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 ,size);                        board[i][k] = board[i][j];                        board[i][j] = 0;                        continue;                    }                    else if( board[i][k] == board[i][j] && noBlockHorizontal( i , k , j , board ) && !hasConflicted[i][k] ){                        //move                        showMoveAnimation( i , j , i , k ,size);                        //add                        board[i][k] += board[i][j];                        board[i][j] = 0;                        //add score                        score += board[i][k];                        updateScore( score );                        hasConflicted[i][k] = true;                        continue;                    }                }            }        }        setTimeout(function(){            updateBoardView();        },200);    }    next();}function moveRight(){    if( !canMoveRight( board ) )        return false;    //moveRight    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 ,size);                        board[i][k] = board[i][j];                        board[i][j] = 0;                        continue;                    }                    else if( board[i][k] == board[i][j] && noBlockHorizontal( i , j , k , board ) && !hasConflicted[i][k] ){                        //move                        showMoveAnimation( i , j , i , k,size);                        //add                        board[i][k] += board[i][j];                        board[i][j] = 0;                        //add score                        score += board[i][k];                        updateScore( score );                        hasConflicted[i][k] = true;                        continue;                    }                }            }        }        setTimeout(function(){            updateBoardView();        },200);    }    next();}function moveUp(){    if( !canMoveUp( board ) )        return false;    //moveUp    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 ,size);                        board[k][j] = board[i][j];                        board[i][j] = 0;                        continue;                    }                    else if( board[k][j] == board[i][j] && noBlockVertical( j , k , i , board ) && !hasConflicted[k][j] ){                        //move                        showMoveAnimation( i , j , k , j ,size);                        //add                        board[k][j] += board[i][j];                        board[i][j] = 0;                        //add score                        score += board[k][j];                        updateScore( score );                        hasConflicted[k][j] = true;                        continue;                    }                }            }        }        setTimeout(function(){            updateBoardView();        },200);    }    next();}function moveDown(){    if( !canMoveDown( board ) )        return false;    //moveDown    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,size );                        board[k][j] = board[i][j];                        board[i][j] = 0;                        continue;                    }                    else if( board[k][j] == board[i][j] && noBlockVertical( j , i , k , board ) && !hasConflicted[k][j] ){                        //move                        showMoveAnimation( i , j , k , j ,size);                        //add                        board[k][j] += board[i][j];                        board[i][j] = 0;                        //add score                        score += board[k][j];                        updateScore( score );                        hasConflicted[k][j] = true;                        continue;                    }                }            }        }        setTimeout(function(){            updateBoardView();        },200);    }    next();}

2048.css

 

/** * Created by *** on 14-4-11. * modify by ouyangli on 14-8-15. * @author <278500368@qq.com> * my site: http://www.imooc.com/ */body {    font-family:Arial;}header{    display:block;    margin:0 auto;    width:500px;    text-align:center;}header h1{    font-size:1.25em;    font-weight:bold;}#newgamebutton{    display:block;    margin:10px auto;    width:100px;    padding:10px;    background-color:#8f7a66;    color:white;    border-radius:10px;    text-decoration:none;}#newgamebutton:hover{    background-color:#9f8b77;}header p{    font-size:1em;    margin:20px auto;}#grid-container{    background-color:#007aff;    border-radius: 10px;    position: relative;}.grid-cell {    background-color: #ccc0b3;}.grid-cell,.number-cell{    border-radius: 6px;    position: absolute;}.number-cell{    overflow: hidden;    font-weight:bold;    text-align:center;}