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
- 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 );
- }
- }
- }
For code merging, refer:
[Html]View plaincopy
- 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. Display
Display part of the CSS source 2048 source author program.
Show Code:
[Html]View plaincopy
- 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> ");
- Else
- $ (N + (I * 4+j1_0000.html ("");
- }
- }
- }
This code displays the array content in a 4x4 table.
Source code and Online Demo: http://jsbin.com/biximuho/6/edit