js280行代碼寫2048

來源:互聯網
上載者:User

標籤:blog   class   code   c   ext   http   

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

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


思路:

1. 數組 ,2維數組4x4

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


移動前



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



移動演算法分2步:

第一步驟:移動

第二步驟:合并


行動程式碼參考:

    function left(t,i)    {      var j;      var len = t[i].length;      for (j=0;j<len-1;j++)        {          if (t[i][j] == 0 && t[i][j+1] != 0)          {            temp = t[i][j];            t[i][j] = t[i][j+1];            t[i][j+1] = temp;            left(t,i);                      }        }                }


合并代碼參考:

    function lcombine(a,i)    {      var len = a[i].length;            for(var j=0;j<len-2;j++)      {        if (a[i][j] == a[i][j+1])        {          a[i][j] *=2;          a[i][j+1] = 0;          left(a,i);          break;        }      }    }

3.顯示


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

顯示代碼:


    function display_div ()    {      var i,j;      var n = "#d";      for (i = 0 ;i < 4 ;i++)      {        for(j=0;j<4;j++)        {          if (a[i][j] !=0)            $(n+(i*4+j)).html("<div class=‘tile tile-"+a[i][j]+"‘><div class=‘tile-inner‘>"+a[i][j]+"</div></div>");          else            $(n+(i*4+j)).html("");                            }      }    }

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



全部代碼:http://jsbin.com/biximuho/6/edit


280多行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.