280行代碼:Javascript 寫的2048遊戲

來源:互聯網
上載者:User

2048 原作者就是用Js寫的,一直想嘗試,但久久未動手。

昨天教學生學習JS代碼。不妨就做個有趣的遊戲好了。2048這麼火,是一個不錯的選擇。


思路:

1. 數組 ,2維數組4x4

2. 移動演算法,移動後有數位對齊,無數字(我用的0,但不顯示)補齊。


移動前



移動後(注意程式合并了第一行2個2,併產生了新的2)



移動演算法分2步:

第一步驟:移動

第二步驟:合并


行動程式碼參考:

[html] view plaincopy
  1. function left(t,i)  
  2. {  
  3.   var j;  
  4.   var len = t[i].length;  
  5.   for (j=0;j<len-1;j++)  
  6.     {  
  7.       if (t[i][j] == 0 && t[i][j+1] != 0)  
  8.       {  
  9.         temp = t[i][j];  
  10.         t[i][j] = t[i][j+1];  
  11.         t[i][j+1] = temp;  
  12.         left(t,i);  
  13.           
  14.       }  
  15.     }  
  16.           
  17. }  


合并代碼參考:

[html] view plaincopy
  1. function lcombine(a,i)  
  2. {  
  3.   var len = a[i].length;  
  4.     
  5.   for(var j=0;j<len-2;j++)  
  6.   {  
  7.     if (a[i][j] == a[i][j+1])  
  8.     {  
  9.       a[i][j] *=2;  
  10.       a[i][j+1] = 0;  
  11.       left(a,i);  
  12.       break;  
  13.     }  
  14.   }  
  15. }  

3.顯示


顯示部分CSS來源 2048源作者程式。

顯示代碼:


[html] view plaincopy
  1. function display_div ()  
  2. {  
  3.   var i,j;  
  4.   var n = "#d";  
  5.   for (i = 0 ;i < 4 ;i++)  
  6.   {  
  7.     for(j=0;j<4;j++)  
  8.     {  
  9.       if (a[i][j] !=0)  
  10.         $(n+(i*4+j)).html("<div class='tile tile-"+a[i][j]+"'><div class='tile-inner'>"+a[i][j]+"</div></div>");  
  11.       else  
  12.         $(n+(i*4+j)).html("");  
  13.         
  14.         
  15.     }  
  16.   }  
  17. }  

這段代碼是把數組內容顯示到  4x4表格內。


原始碼及線上示範:http://jsbin.com/biximuho/6/edit


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.