280 lines of code: 2048 Games Written in Javascript

Source: Internet
Author: User

2048 the original author wrote it in Js and tried it for a long time.

I taught students to learn JS Code yesterday. Just make an interesting game. 2048 is a good choice.


Ideas:

1. array, 2-dimensional array 4x4

2. The mobile algorithm is aligned with the number after moving. No number (I used 0, but not displayed) is filled.


Before moving



After moving (note that the program merges 2 in the first line and generates a new 2)



The mobile algorithm consists of two steps:

Step 1: Move

Step 2: Merge


Mobile Code reference:

[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. }


For code merging, refer:

[Html]View plaincopy
  1. Function lcombine (a, I)
  2. {
  3. Var len = a [I]. length;
  4. For (var j = 0; j <len-2; j ++)
  5. {
  6. If (a [I] [j] = a [I] [j + 1])
  7. {
  8. A [I] [j] * = 2;
  9. A [I] [j + 1] = 0;
  10. Left (a, I );
  11. Break;
  12. }
  13. }
  14. }

3. Display


Display part of the CSS source 2048 source author program.

Show Code:


[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> ");
  11. Else
  12. $ (N + (I * 4+j1_0000.html ("");
  13. }
  14. }
  15. }

This code displays the array content in a 4x4 table.


Source code and Online Demo: http://jsbin.com/biximuho/6/edit


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.