2048 Small game _javascript skills written using JavaScript

Source: Internet
Author: User

The recent whim, the project is over, use JavaScript to write a small game, practice and accept it, write a bad also ask heroes to give critical suggestions.

The HTML code is as follows

<! DOCTYPE html>  

CSS code is as follows

@charset "Utf-8";
 #gridPanel {width:480px;height:480px;
 margin:0 Auto;
 Background-color: #bbada0;
 border-radius:10px;
position:relative;
 }. grid,.cell{width:100px; height:100px;
border-radius:6px;
 }. Grid{background-color: #ccc0b3;
 margin:16px 0 0 16px;
Float:left;
 }. cell{/*margin:16px 0 0 16px;
 Float:left;
 position:relative;
 Z-index:10;
 top:-464px;
 left:0;*/Position:absolute;
 Text-align:center;
 line-height:100px;
font-size:60px; #c00, #c01, #c02, #c03 {top:16px} #c10, #c11, #c12, #c13 {top:132px;} #c20, #c21, #c22, and #c23 {top:248px} #c30, #c31, #c32, #
C33{TOP:364PX} #c00, #c10, #c20, #c30 {left:16px} #c01, #c11, #c21, #c31 {left:132px;} #c02, #c12, #c22, and #c32 {left:248px} #c03, #c13, #c23, #c33 {left:364px}. N2{background-color: #eee3da}. N4{background-color: #ede0c8}. N8{background-color : #f2b179}. N16{background-color: #f59563} n32{background-color: #f67c5f}. N64{background-color: #f65e3b}. n128{ Background-color: #edcf72}. N256{background-color: #edcc61}. N512{background-color: #9c0}. n1024{backgRound-color: #33b5e5}. N2048{background-color: #09c}. N4096{background-color: #a6c}. N8192{background-color: #93c}. N8 ,. N16,.n32,.n64,. n128,.n256,.n512,. N1024,.n2048,.n4096,.n8192{color: #fff}. n1024,.n2048,.n4096,.n8192{font-size
 : 40px}/* Score display * * p{width:480px margin:0 Auto;
 Font-family:arial;font-weight:bold; font-size:40px;
padding-top:15px;
 /*game over*/#gameOver {width:100%; height:100%; Position:absolute; top:0;
 left:0;
Display:none;
 } #gameOver >div{width:100%; height:100%; Background-color: #555;
opacity:.5;
 } #gameOver >p{width:300px; height:200px;
 border:1px solid #edcf72; Line-height:1.6em;
 Text-align:center; Background-color: #fff;
 border-radius:10px; Position:absolute; top:50%;
 left:50%; margin-top:-135px;
margin-left:-150px;
 }. button{padding:10px; border-radius:6px; Background-color: #9f8b77;
 Color: #fff;
Cursor:pointer; }

JavaScript code is as follows

var game={data:[],//saves a two-dimensional array of all numbers rn:4,//Total rows Cn:4,//Totals state:0,//game current status: Running| Gameover running:1, gameover:0, score:0,//Score Isgameover:function () {//To determine if the game state is over//if not full, return False if (!this.isfull ()
  ) {return false; }else{//otherwise//starts with the first element in the upper-left corner, traversing the two-dimensional array for (Var row=0;row<this.rn;row++) {for (Var col=0;col<this.cn;col++) {/ /If the current element is not the rightmost element if (col<this.cn-1) {//if the current element = = right element if (this.data[row][col]== this.data[row][col+1]
      ) {return false; }//If the current element is not the lowest element if (row<this.rn-1) {//if the current element = = below element = if (this.data[row][col]== this.d
      Ata[row+1][col]) {return false;
  }}}return true; }, Start:function () {//game started this.state=this.
  RUNNING;
  Find game End interface, hide Var Div=document.getelementbyid ("Gameover");
  Div.style.display= "None";
  this.data=[//initializes two-dimensional arrays [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]]; this.score=0;
Reset score is 0/*for (var r=0;r<this.rn;r++) {   this.data[r]=[];//add each row of array to an empty array for (Var c=0;c<this.cn;c++) {///To add the default element 0 this.data[r][c]=0 to the current empty row array;
  }*///Generate 2 or 4 this.randomnum () at two random locations;
  This.randomnum ();
 Update the data to the page This.updateview ();
  }, Isfull:function () {//To determine whether the current array is full for (Var row=0;row<this.rn;row++) {//Traversal two-dimensional array for (Var col=0;col<this.cn;col++) {
  Whenever the current element is found ==0 if (this.data[row][col]==0) {return false;
 }}//(if the loop normally exits) return true; }, Randomnum:function () {///generate a number of if (!this.isfull ()) {//in random empty position {//if * not * full, {while (true) {//loop true//0-3 randomly generate line number row V
    Ar row=parseint (math.random () *this.rn);
    0-3 randomly generated a column number col var col=parseint (Math.random () *this.cn); If Data[row][col]==0 if (this.data[row][col]==0) {//Math.random (): <0.5 >=0.5//2 4//randomly generate a number
     <0.5?2:4,//Put in Data[row][col] this.data[row][col]= math.random () <0.5?2:4; break;//exit Loop}}}, Updateview:function () {///to place the number of each lattice in a two-dimensional array in the foreground/loop through each element of the two-dimensional array, for example: Row=2,col=3, for (Var row=0;row<this.rn;row++) {for (Var col=0;col<this.cn;col++) {/* All elements of the page, attributes, text are objects/var div=document.
           getElementById ("C" +row+col); "C23" var curr=this.data[row][col];
  Current element value//modify the content between the DIV start tag and the end tag Div.innerhtml=curr!=0?curr: ""; Modify div's class attribute div.classname=curr!=0? "
 Cell n "+curr: Cell"//Class}} var Span=document.getelementbyid ("Score");
 Span.innerhtml=this.score; Judge and modify the game status to Gameover if (This.isgameover ()) {this.state=this.
  Gameover;
  var Div=document.getelementbyid ("Gameover");
  var Span=document.getelementbyid ("Finalscore");
 Span.innerhtml=this.score;
 Modify the Div's Style property under the Display child property is "block" div.style.display= "block";
  },//updateview Method End/* Implementation Left/* To find the current position to the right, * next * not 0 number * * * getrightnext:function (ROW,COL) {//loop variable:nextc--> refers to the next element of the column subscript Starts with Col+1, traverses the remaining elements in the row row, &LT;CN ends for (var nextc=col+1;nextc<this.cn;nextc++) {//If the element that is traversed to!=0 if (this.data[row][ne
   xtc]!=0) {//returns NEXTC return NEXTC; }}return-1;//(Cycle normal exit,Returns-1},/* Judge and move left * Each element in the specified row * * moveleftinrow:function (ROW) {//col starts at 0, traverses each element in the row row, <cn-1 ends for (var col=0;col<
  this.cn-1;col++) {//Get the subscript nextc var nextc=this.getrightnext (Row,col) for the next element of the current element that is not 0;
   If Nextc==-1, (stating that there is no!=0 element behind) if (Nextc==-1) {break; }else{//otherwise//if the current position ==0, if (this.data[row][col]==0) {//will be the value of the next position, when entering the current position this.data[row][col]= THIS.D
  ATA[ROW][NEXTC];
     The next position is set to 0 this.data[row][nextc]=0;   col--;//let Col back a grid, repeat check}else if (this.data[row][col]== THIS.DATA[ROW][NEXTC]) {//Otherwise, if the current position ==NEXTC position//
     *=2 the current position;
  this.data[row][col]*=2;
     The next position is set to 0;
  this.data[row][nextc]=0;
    Add the current position value to the score This.score+=this.data[row][col];
  }},/* Move all Lines */Moveleft:function () {var oldstr=this.data.tostring ();
  Iterate through each line for (Var row=0;row<this.rn;row++) {//Call Moveleftinrow method, passing in the current line number row this.moveleftinrow (row);
  }//(after the end of the cycle) var newstr=this.data.tostring (); if (Oldstr!=neWSTR) {//Call Randomnum (), randomly generate a number of this.randomnum ();
  Call Updateview (), More Rows page This.updateview ();
  }, Moveright:function () {var oldstr=this.data.tostring ();
  for (Var row=0;row<this.rn;row++) {this.moverightinrow (row);
  var newstr=this.data.tostring ();
   if (oldstr!=newstr) {this.randomnum ();
  This.updateview (); },/* Determine and right Move * Each element in the specified row * * moverightinrow:function (ROW) {//col starts from cn-1, to >0 end for (Var col=this.cn-1;col>0;col--)
   {var nextc=this.getleftnext (row,col);
   if (nextc==-1) {break;
     }else{if (this.data[row][col]==0) {this.data[row][col]= THIS.DATA[ROW][NEXTC];
     this.data[row][nextc]=0;
    col++;
     }else if (this.data[row][col]== THIS.DATA[ROW][NEXTC]) {this.data[row][col]*=2;
     this.data[row][nextc]=0;
    This.score+=this.data[row][col]; }},/* Find the left of the current position, the next number not 0/getleftnext:function (row,col) {//NEXTC starts at Col-1, traverses the remaining elements in the row row, >=0 ends for (var next c=col-1;nextc>=0;nextc--) {//all overDuring the calendar process, the same getrightnext if (this.data[row][nextc]!=0) {return NEXTC;
 }}return-1; /* Get position below 0 in any position/* Getdownnext:function (Row,col) {//nextr starts at row+1, ends with <this.rn for (Var nextr=row+1;nextr<th
   is.rn;nextr++) {if (this.data[nextr][col]!=0) {return nextr;
 }}return-1; },/* judge and move up * Specify each element in the column */moveupincol:function (col) {//row starts at 0, to <rn-1, traversing each row element for (Var row=0;row<this.rn-1;row++)
   {//First get the row nextr var nextr=this.getdownnext (row,col) below the current position; if (nextr==-1) {break;//If nextr==-1}else{//otherwise///if the current position equals 0 if (this.data[row][col]==0) {//replace the current position with the NEXTR position
  Elements of this.data[row][col]= This.data[nextr][col];
     Setting the NEXTR position to 0 this.data[nextr][col]=0; row--;//a row, and then keep in place}else if (this.data[row][col]== This.data[nextr][col]) {//Otherwise, if the current position equals NEXTR position//Will
  Current position *=2 this.data[row][col]*=2;
  Setting the NEXTR position to 0 this.data[nextr][col]=0;
 Add the value of the current position to the score property This.score+=this.data[row][col];   }}},/* Move all Columns up/* * Moveup:function () {var oldstr=this.data.tostring ();
  Traverse all columns for (Var col=0;col<this.cn;this.moveupincol (col++));
  var newstr=this.data.tostring ();
   if (oldstr!=newstr) {this.randomnum ();
  This.updateview (); },/* Move all Columns down */movedown:function () {var oldstr=this.data.tostring (); for (Var col=0;col<this.cn;this.movedownincol
  col++));
  var newstr=this.data.tostring ();
   if (oldstr!=newstr) {this.randomnum ();
  This.updateview (); }, Movedownincol:function (col) {//row from this.rn-1, to >0 end, row--for (var row=this.rn-1;row>0;row--) {var nextr
   =this.getupnext (Row,col);
   if (nextr==-1) {break;
     }else{if (this.data[row][col]==0) {this.data[row][col]= this.data[nextr][col];
     this.data[nextr][col]=0;
    row++;
     }else if (this.data[row][col]== This.data[nextr][col]) {this.data[row][col]*=2;
     this.data[nextr][col]=0;
    This.score+=this.data[row][col]; }},/* Obtain a position that is not 0 above any position*/Getupnext:function (Row,col) {for (Var nextr=row-1;nextr>=0;nextr--) {if (this.data[nextr][col]!=0) {return n
   EXTR;
 }}return-1; }//onload Event: When the page loads * automatically executes window.onload=function () {Game.start ();//When the page loads, automatically starts the game//when pressing the keyboard button, triggers the move: Document.onkeydown =function () {//Get the keyboard number of the event object: 2 Step//Event object: Automatically create//encapsulates the information of the event when the event occurs (game.state==game. RUNNING) {//step1: Get event object var e=window.event| |
     Arguments[0];
   IE DOM Standard//STEP2: Get keyboard Number: E.keycode if (e.keycode==37) {game.moveleft ();
   }else if (e.keycode==39) {game.moveright ();
   }else if (e.keycode==38) {game.moveup ();
   }else if (e.keycode==40) {game.movedown (); //If you press the left button, call MoveLeft//Otherwise if you press the right button, call MoveRight}}

The above code is written in JavaScript 2048 games, the code is easy to understand and with comments, I hope you like.

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.