DIV CSS 佈局教程網

用 JavaScript 從零實作 2048 小遊戲
編輯:關於JavaScript     

專案告一段落,正好來寫個小遊戲練練手。以下是用 JavaScript 實作的 2048,程式碼附了大量註解,應該還算容易讀懂,若有可以改進的地方也歡迎指教。

HTML 結構

整個棋盤由兩層組成:底層是 16 個 grid 背景格,上層是 16 個 cell 前景格用來顯示數字,兩者透過絕對定位精準對齊。另外還有一個預設隱藏的 #gameOver 遮罩層。

 <!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link rel="stylesheet" href="2048.css"/>
<script src="2048.js"></script>
<script>
</script>
</head>
<body>
<p>Score:<span id="score"></span></p>
<div id="gridPanel">
  <!--背景格-->
  <!--第1行-->
  <div id="g00" class="grid"></div>
  <div id="g01" class="grid"></div>
  <div id="g02" class="grid"></div>
  <div id="g03" class="grid"></div>
  <!--第2行-->
  <div id="g10" class="grid"></div>
  <div id="g11" class="grid"></div>
  <div id="g12" class="grid"></div>
  <div id="g13" class="grid"></div>
  <!--第3行-->
  <div id="g20" class="grid"></div>
  <div id="g21" class="grid"></div>
  <div id="g22" class="grid"></div>
  <div id="g23" class="grid"></div>
  <!--第4行-->
  <div id="g30" class="grid"></div>
  <div id="g31" class="grid"></div>
  <div id="g32" class="grid"></div>
  <div id="g33" class="grid"></div>
  <!--前景格-->
  <!--第1行-->
  <div id="c00" class="cell"></div>
  <div id="c01" class="cell"></div>
  <div id="c02" class="cell"></div>
  <div id="c03" class="cell"></div>
  <!--第2行-->
  <div id="c10" class="cell"></div>
  <div id="c11" class="cell"></div>
  <div id="c12" class="cell"></div>
  <div id="c13" class="cell"></div>
  <!--第3行-->
  <div id="c20" class="cell"></div>
  <div id="c21" class="cell"></div>
  <div id="c22" class="cell"></div>
  <div id="c23" class="cell"></div>
  <!--第4行-->
  <div id="c30" class="cell"></div>
  <div id="c31" class="cell"></div>
  <div id="c32" class="cell"></div>
  <div id="c33" class="cell"></div>
</div>
<div id="gameOver"><!--同時包含前景和背景的容器-->
  <div><!--半透明灰色背景--></div>
  <p><!--居中小窗口-->
    Game Over!<br>
    Score:<span id="finalScore"></span><br>
    <a class="button" onclick="game.start()">Try again!</a>
  </p>
</div>
</body>
</html>

CSS 樣式

前景格用絕對定位逐一對位,並依數字大小套用不同的背景色;位數多的格子則縮小字級避免溢出。

 @charset "utf-8";
#gridPanel{width:480px;height:480px; margin:0 auto; background-color:#bbada0; border-radius:10px; position:relative; }
.grid,.cell{width:100px; height:100px; border-radius:6px; }
.grid{background-color:#ccc0b3; margin:16px 0 0 16px; float:left; }
.cell{
  position:absolute;
  text-align:center;
  line-height:100px;
  font-size:60px;
}
#c00,#c01,#c02,#c03{top:16px;}
#c10,#c11,#c12,#c13{top:132px;}
#c20,#c21,#c22,#c23{top:248px;}
#c30,#c31,#c32,#c33{top:364px;}
#c00,#c10,#c20,#c30{left:16px;}
#c01,#c11,#c21,#c31{left:132px;}
#c02,#c12,#c22,#c32{left:248px;}
#c03,#c13,#c23,#c33{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}
.n8,.n16,.n32,.n64,
.n128,.n256,.n512,
.n1024,.n2048,.n4096,.n8192{color:#fff}
.n1024,.n2048,.n4096,.n8192{font-size:40px}
/*分數顯示*/
p{width:480px; margin:0 auto; font-family:Arial;font-weight:bold; font-size:40px; padding-top:15px; }
/*Game Over*/
#gameOver{width:100%; height:100%; position:absolute; top:0; left:0; display:none; }
#gameOver>div{width:100%; height:100%; background-color:#555; opacity:.5; }
#gameOver>p{width:300px; height:200px; border:1px solid #edcf72; line-height:1.6em; text-align:center; background-color:#fff; border-radius:10px; position:absolute; top:50%; left:50%; margin-top:-135px; margin-left:-150px; }
.button{padding:10px; border-radius:6px; background-color:#9f8b77; color:#fff; cursor:pointer; }

遊戲主邏輯

整個遊戲包在一個 game 物件裡,用二維陣列 data 保存棋盤狀態,再分成四組函式:狀態與初始化(start、isFull、isGameOver、randomNum)、畫面更新(updateView)、單一方向移動(moveLeftInRow、moveRightInRow、moveUpInCol、moveDownInCol)、以及四個方向的總入口(moveLeft、moveRight、moveUp、moveDown)。每個方向入口都會比對移動前後的陣列字串,只有真的發生變化時才補上新數字並重繪,這點設計能有效避免「按了沒動卻長出方塊」的 bug。

 var game={
  data:[],//保存所有數字的二維數組
  rn:4,   //總行數
  cn:4,   //總列數
  state: 0, //游戲當前狀態:Running|GameOver
  RUNNING:1,
  GAMEOVER:0,
  score:0, //分數
  isGameOver:function(){//判斷游戲狀態為結束
    //如果沒有滿,則返回false
    if(!this.isFull()){
      return false;
    }else{//否則
      //從左上角第一個元素開始,遍歷二維數組
      for(var row=0;row<this.rn;row++){
        for(var col=0;col<this.cn;col++){
          //如果當前元素不是最右側元素
          if(col<this.cn-1){
            // 如果當前元素==右側元素
            if(this.data[row][col]== this.data[row][col+1]){
              return false;
            }
          }
          //如果當前元素不是最下方元素
          if(row<this.rn-1){
            // 如果當前元素==下方元素
            if(this.data[row][col]== this.data[row+1][col]){
              return false;
            }
          }
        }
      }
      return true;
    }
  },
  start:function(){//游戲開始
    this.state=this.RUNNING;
    //找到游戲結束界面,隱藏
    var div=document.getElementById("gameOver");
    div.style.display="none";
    this.data=[//初始化二維數組
      [0,0,0,0],
      [0,0,0,0],
      [0,0,0,0],
      [0,0,0,0]
    ];
    this.score=0; //重置分數為0
    //在兩個隨機位置生成2或4
    this.randomNum();
    this.randomNum();
    //將數據更新到頁面
    this.updateView();
  },
  isFull:function(){//判斷當前數組是否已滿
    for(var row=0;row<this.rn;row++){//遍歷二維數組
      for(var col=0;col<this.cn;col++){
        // 只要發現當前元素==0
        if(this.data[row][col]==0){
          return false;
        }
      }
    }
    //(如果循環正常退出)
    return true;
  },
  randomNum:function(){//在隨機空位置生成一個數
    if(!this.isFull()){//如果*不*滿,才{
      while(true){//循環true
        //0-3隨機生成一個行號row
        var row=parseInt(Math.random()*this.rn);
        //0-3隨機生成一個列號col
        var col=parseInt(Math.random()*this.cn);
        //如果data[row][col]==0
        if(this.data[row][col]==0){
          // Math.random():<0.5 >=0.5
          // 2 4
          // 隨機生成一個數<0.5?2:4,
          // 放入data[row][col]
          this.data[row][col]= Math.random()<0.5?2:4;
          break;//退出循環
        }
      }
    }
  },
  updateView:function(){
    //將二維數組中每個格的數字放入前景格中
    //遍歷二維數組中每個元素,比如:row=2,col=3, 16
    for(var row=0;row<this.rn;row++){
      for(var col=0;col<this.cn;col++){
        /*網頁中一切元素,屬性,文字都是對象*/
        var div=document.getElementById("c"+row+col);
        //"c23"
        var curr=this.data[row][col]; //當前元素值
        //修改div開始標簽和結束標簽之間的內容
        div.innerHTML=curr!=0?curr:"";
        //修改div的class屬性
        div.className=curr!=0?"cell n"+curr:"cell" // class
      }
    }
    var span=document.getElementById("score");
    span.innerHTML=this.score;
    //判斷並修改游戲狀態為GAMEOVER
    if(this.isGameOver()){
      this.state=this.GAMEOVER;
      var div=document.getElementById("gameOver");
      var span=document.getElementById("finalScore");
      span.innerHTML=this.score;
      //修改div的style屬性下的display子屬性為"block"
      div.style.display="block";
    }
  },//updateView方法的結束

  /*實現左移*/
  /*找當前位置右側,*下一個*不為0的數*/
  getRightNext:function(row,col){
    //循環變量:nextc——>指下一個元素的列下標
    //從col+1開始,遍歷row行中剩余元素,<cn結束
    for(var nextc=col+1;nextc<this.cn;nextc++){
      // 如果遍歷到的元素!=0
      if(this.data[row][nextc]!=0){
        // 就返回nextc
        return nextc;
      }
    }
    return -1;//(循環正常退出,就)返回-1
  },
  /*判斷並左移*指定行*中的每個元素*/
  moveLeftInRow:function(row){
    //col從0開始,遍歷row行中的每個元素,<cn-1結束
    for(var col=0;col<this.cn-1;col++){
      // 獲得當前元素下一個不為0的元素的下標nextc
      var nextc=this.getRightNext(row,col);
      // 如果nextc==-1,(說明後邊沒有!=0的元素了)
      if(nextc==-1){
        break;
      }else{// 否則
        // 如果當前位置==0,
        if(this.data[row][col]==0){
          // 將下一個位置的值,當入當前位置
          this.data[row][col]= this.data[row][nextc];
          // 下一個位置設置為0
          this.data[row][nextc]=0;
          col--;//讓col退一格,重復檢查一次
        }else if(this.data[row][col]== this.data[row][nextc]){
          // 否則,如果當前位置==nextc的位置
          // 將當前位置*=2;
          this.data[row][col]*=2;
          // 下一個位置設置為0;
          this.data[row][nextc]=0;
          // 將當前位置的值,累加到score上
          this.score+=this.data[row][col];
        }
      }
    }
  },
  /*移動所有行*/
  moveLeft:function(){
    var oldStr=this.data.toString();
    //循環遍歷每一行
    for(var row=0;row<this.rn;row++){
      // 調用moveLeftInRow方法,傳入當前行號row
      this.moveLeftInRow(row);
    }//(循環結束後)
    var newStr=this.data.toString();
    if(oldStr!=newStr){
      //調用randomNum(),隨機生成一個數
      this.randomNum();
      //調用updateView(),更行頁面
      this.updateView();
    }
  },
  moveRight:function(){
    var oldStr=this.data.toString();
    for(var row=0;row<this.rn;row++){
      this.moveRightInRow(row);
    }
    var newStr=this.data.toString();
    if(oldStr!=newStr){
      this.randomNum();
      this.updateView();
    }
  },
  /*判斷並右移*指定行*中的每個元素*/
  moveRightInRow:function(row){
    //col從cn-1開始,到>0結束
    for(var col=this.cn-1;col>0;col--){
      var nextc=this.getLeftNext(row,col);
      if(nextc==-1){
        break;
      }else{
        if(this.data[row][col]==0){
          this.data[row][col]= this.data[row][nextc];
          this.data[row][nextc]=0;
          col++;
        }else if(this.data[row][col]== this.data[row][nextc]){
          this.data[row][col]*=2;
          this.data[row][nextc]=0;
          this.score+=this.data[row][col];
        }
      }
    }
  },
  /*找當前位置左側,下一個不為0的數*/
  getLeftNext:function(row,col){
    //nextc從col-1開始,遍歷row行中剩余元素,>=0結束
    for(var nextc=col-1;nextc>=0;nextc--){
      // 遍歷過程中,同getRightNext
      if(this.data[row][nextc]!=0){
        return nextc;
      }
    }
    return -1;
  },
  /*獲得任意位置下方不為0的位置*/
  getDownNext:function(row,col){
    //nextr從row+1開始,到<this.rn結束
    for(var nextr=row+1;nextr<this.rn;nextr++){
      if(this.data[nextr][col]!=0){
        return nextr;
      }
    }
    return -1;
  },
  /*判斷並上移*指定列*中的每個元素*/
  moveUpInCol:function(col){
    //row從0開始,到<rn-1,遍歷每行元素
    for(var row=0;row<this.rn-1;row++){
      // 先獲得當前位置下方不為0的行nextr
      var nextr=this.getDownNext(row,col);
      if(nextr==-1){
        break; // 如果nextr==-1
      }else{// 否則
        // 如果當前位置等於0
        if(this.data[row][col]==0){
          // 將當前位置替換為nextr位置的元素
          this.data[row][col]= this.data[nextr][col];
          // 將nextr位置設置為0
          this.data[nextr][col]=0;
          row--;//退一行,再循環時保持原位
        }else if(this.data[row][col]== this.data[nextr][col]){
          // 否則,如果當前位置等於nextr位置
          // 將當前位置*=2
          this.data[row][col]*=2;
          // 將nextr位置設置為0
          this.data[nextr][col]=0;
          // 將當前位置的值累加到score屬性上
          this.score+=this.data[row][col];
        }
      }
    }
  },
  /*上移所有列*/
  moveUp:function(){
    var oldStr=this.data.toString();
    //遍歷所有列
    for(var col=0;col<this.cn;this.moveUpInCol(col++));
    var newStr=this.data.toString();
    if(oldStr!=newStr){
      this.randomNum();
      this.updateView();
    }
  },
  /*下移所有列*/
  moveDown:function(){
    var oldStr=this.data.toString();
    for(var col=0;col<this.cn;this.moveDownInCol(col++));
    var newStr=this.data.toString();
    if(oldStr!=newStr){
      this.randomNum();
      this.updateView();
    }
  },
  moveDownInCol:function(col){
    //row從this.rn-1,到>0結束,row--
    for(var row=this.rn-1;row>0;row--){
      var nextr=this.getUpNext(row,col);
      if(nextr==-1){
        break;
      }else{
        if(this.data[row][col]==0){
          this.data[row][col]= this.data[nextr][col];
          this.data[nextr][col]=0;
          row++;
        }else if(this.data[row][col]== this.data[nextr][col]){
          this.data[row][col]*=2;
          this.data[nextr][col]=0;
          this.score+=this.data[row][col];
        }
      }
    }
  },
  /*獲得任意位置上方不為0的位置*/
  getUpNext:function(row,col){
    for(var nextr=row-1;nextr>=0;nextr--){
      if(this.data[nextr][col]!=0){
        return nextr;
      }
    }
    return -1;
  }
}
//onload事件:當頁面加載*後*自動執行
window.onload=function(){
  game.start();//頁面加載後,自動啟動游戲
  //當按鍵盤按鍵時,觸發移動:
  document.onkeydown=function(){
    //獲得事件對象中鍵盤號:2步
    //事件對象:在事件發生時自動創建
    // 封裝了事件的信息
    if(game.state==game.RUNNING){
      //Step1: 獲得事件對象
      var e=window.event||arguments[0];
      //IE DOM標准
      //Step2: 獲得鍵盤號:e.keyCode
      if(e.keyCode==37){
        game.moveLeft();
      }else if(e.keyCode==39){
        game.moveRight();
      }else if(e.keyCode==38){
        game.moveUp();
      }else if(e.keyCode==40){
        game.moveDown();
      }
      //如果按左鍵,調用moveLeft
      //否則如果按右鍵,調用moveRight
    }
  }
}

幾個可以優化的方向

目前版本每次移動都是瞬間跳位,若想加上滑移動畫,可以改用 CSS transition 搭配 transform 位移;棋盤大小寫死成 4×4,但其實把 rn、cn 參數化、前景格改用程式動態產生,就能輕鬆支援 5×5 或 3×3;另外最高分數目前沒有保存,加一個 localStorage 就能讓紀錄在重新整理後仍然存在。

以上就是這個 2048 小遊戲的完整實作,程式碼都已附上註解,希望大家喜歡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved