"2048 games"--traversal algorithm of native JS crawl show two-dimensional array contents

Source: Internet
Author: User

Introduction: do 2048 games will be the vertical direction of the digital content, stored in a two-dimensional array, in order to display the contents of this two-dimensional array on the page, you must use the traversal algorithm to achieve.

One or two-D array storage

    • First, the two-dimensional array is considered to store all the rows and the number of columns →var rn=4,cn=4;
    • Then define a variable data to hold this two-dimensional array →var data;
    • All main execution programs of the game are saved under the start () function → Start the game
    • save a two-dimensional array of rows and columns to the key code in data ↓
functionstart () {Data=[];//create an empty array to save in data      for(varr=0;r<rn;r++) {//r from 0 to <rnData.push ([]);//Press an empty sub-array into data           for(varc=0;c<cn;c++) {}//C ends from 0 to <CNdata[r][c]=0;//Save a 0 for the R row C position in data...}  }}start (); //call the Start function and the game starts

Two, randomly select a location in a two-dimensional array to generate 2 or 4

  • Key functions Create →function Randomnum () {}
  • The random number that generates the position of the row and vertical rows is saved between R and C→0~rn-1, between 0~cn-1
  • 2048 of the game has an important feature, each time you move a number will add two new numbers, and this number will not overwrite the original number
  • Pit: There is no number in the randomly generated position, that is, the value of R row C column in data is 0 o'clock, it is possible to randomly save a 2 or 4 for the R row C column in data
  • Workaround: Execute the above algorithm repeatedly until the condition is met before saving this random 2 or 4
  • Pits: Need to be random, and can only be selected in either 2 or 4 cases
  • Solution: Because Math.random () generated random number between 0~1, and the game requires only 2, you can determine whether the generated random number is <0.5 to decide to save 2 or 4, if the game to increase the difficulty, I hope one of the number of probability generation to a larger, Then the 0.5 figure is the key to the probability control.
  • Pits: 2048 games each time you add two new numbers
  • WORKAROUND: When calling random Generate function Randomnum (), make sure to call two times so that you can generate two numbers
  • Pit: This time there is no effect on the page
  • Solution: Because now still just keep the number in the memory of the two-dimensional array, has not been written to the page, so you need to write to the page, check the console only on the control table
// generate 2 or 4 in a random position in data function Randomnum () {    while (true) {        var r = parseint (Math.random () * RN);         var c = parseint (Math.random () *CN);         if (data[r][c]==0) {            data[r][c]=math.random () <0.5?2:4;   0.5 Control 2 and 4 probability of occurrence break            ;     }}}

Third, the traversal algorithm fills the array elements into the page corresponding Div

    • Key functions Create →function Updateview () {}
    • after iterating over the elements of the two-dimensional array, it is critical to correspond to the div of the page ↓
    1. When the page div is named, C01 is the div that represents the 1th column of row No. 0.
    2. After you get the elements of the two-dimensional array, the "C" + line number + column number makes up the ID of the corresponding Div.
    3. After the ID is spelled, the corresponding DIV element is found by ID
  • Traverse data Two-dimensional array two for loop → Outer loop control row, Inner loop control column
  • Save the value of the traversed R row C column to the content of the div →div.innerhtml = data[r][c];
  • Pit: The value of the R row C column in a two-dimensional array may be 0 when the random number has not been obtained, according to the rules of the 2048 game, this time is not saved in the Div
  • Resolution: Plus, if the value of the R row C column is not 0, the value is saved to the Div, otherwise , the contents of the corresponding div with the value 0 of the R row C column are cleared, because the element in the two-dimensional array is 0, actually there are two cases, One is that there has never been a value, but this situation will increase with the number of moves in the game, gradually decrease, more is that the position has a value, and there are numbers on the Div, but after the movement of the line moved, this time, It is necessary to immediately clear the contents of the corresponding R row C column Div, in order to ensure that the changes in the page numbers are the same as the changes in the two-dimensional numbers.
  • Add a nto the class of div with a value of * , and clear the class attribute of the div itself →n* the specific background color of the corresponding number in the CSS class
//fill in the corresponding div of the page with each element in dataUpdateview ();functionUpdataview () {//Traverse Data     for(varr=0;r< This. rn;r++){         for(varc=0;c< This. Cn;c++){            varid = "C" +r+C; vardiv =document.getElementById (ID); if( This. data[r][c]!=0) {div.innerhtml=Data[r][c]; Div.classname= "N" +Data[r][c]; }Else{div.innerhtml= ""; Div.classname= ""; }        }    }    varspan = document.getElementById ("Score"); Span.innerhtml=score;}


NOTE: Reprint please indicate the source

"2048 games"--traversal algorithm of native JS crawl show two-dimensional array contents

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.