javascript寫的2048遊戲

原生JS寫的2048遊戲,後又對js代碼進行瞭精簡,寫瞭左移邏輯,其他方向采用轉置矩陣後左移代碼復用。代碼如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>2048小遊戲</title>
    <link rel="stylesheet" href="2048.css">
 
</head>
<body>
<p>
    <!--TOP:<span id="top">0</span><br>-->
    SCORE:<span id="score">0</span>
</p>
<p id="playground">
    <p id="c00" class="cell"></p>
    <p id="c01" class="cell"></p>
    <p id="c02" class="cell"></p>
    <p id="c03" class="cell"></p>
    <p id="c10" class="cell"></p>
    <p id="c11" class="cell"></p>
    <p id="c12" class="cell"></p>
    <p id="c13" class="cell"></p>
    <p id="c20" class="cell"></p>
    <p id="c21" class="cell"></p>
    <p id="c22" class="cell"></p>
    <p id="c23" class="cell"></p>
    <p id="c30" class="cell"></p>
    <p id="c31" class="cell"></p>
    <p id="c32" class="cell"></p>
    <p id="c33" class="cell"></p>
</p>
<p id="gameOver"><!-- 半透明遮罩 -->
    <p>
        GAME OVER!<br>
        SCORE: <span id="final"></span><br>
        <a class="btn" onclick="game.start()">Try again!</a>
    </p>
</p>
 
<script src = "2048.js">
 
 
</script>
</body>
</html>

CSS:

#playground{
    width: 480px; height:480px;
    margin:0 auto;
    background:#bbada0;
    border-radius:10px;
    position:relative;
}
.cell{
    width:100px;
    height:100px;
    border-radius:6px;
    background: #ccc0b3;
    position:absolute;
    line-height:100px;
    font-size:60px;
    text-align:center;
    color:#fff;
}
[id^="c0"]{top:16px;}
[id^="c1"]{top:132px;}
[id^="c2"]{top:248px;}
[id^="c3"]{top:364px;}

[id$="0"]{left:16px;}
[id$="1"]{left:132px;}
[id$="2"]{left:248px;}
[id$="3"]{left:364px;}

.n2{background-color:#eee3da}
.n4{background-color:#ede0c8}
.n8{background-color:#f2b179}
.n16{background-color:#f59563}
.n32{background-color:#f67c5f}
.n64{background-color:#f65e3b}
.n128{background-color:#edcf72}
.n256{background-color:#edcc61}
.n512{background-color:#9c0}
.n1024{background-color:#33b5e5}
.n2048{background-color:#09c}
.n4096{background-color:#a6c}
.n8192{background-color:#93c}
.n2,.n4{color:#776e65}
.n1024,.n2048,.n4096,.n8192{font-size:40px}

p{
    width:480px;
    margin:0 auto;
    font-size:40px;
    font-family:Arial;
    font-weight:bold;
    padding-top:15px;
}
#gameOver{
    position:absolute;
    left:0;right:0;top:0;bottom:0;
    background:rgba(55,55,55,.5);
}
#gameOver>p{
    width:300px;
    height:200px;
    background:#fff;
    position:absolute;
    top:50%;left:50%;
    margin-top:-100px;
    margin-left:-150px;
    text-align:center;
    line-height:1.5em;
    border-radius:10px;
    border:1px solid #edcf72;
}
#gameOver .btn{
    padding:10px;
    color:#fff;
    background-color:#9f8d77;
    border-radius:6px;
    cursor:pointer;
}
/** * Created by viyo on 2016/12/7. */ var game={ RN:4,CN:4, data:null, score:0, state:1, GAMEOVER:0, RUNNING:1, start:function(){ this.state=this.RUNNING; this.score=0; this.data=[]; for(var r=0;r

發佈留言