JavaScript code to write Tetris Web version _javascript tips

Source: Internet
Author: User

Tetris is a childhood memory, from the beginning of the palm of the black and white game machine, to the video game machine, to the computer, there is no trace of it, today we come together to relive a way to realize it, but also to sort out my ideas it ...

Html+css+js to achieve the full version of Tetris, the material only pictures, want to download the picture by the prompt name save, CSS use time to pay attention to the path!! Mainly in JS! JS with detailed notes

Effect:

Key Tip: [Keyboard keys]

Material: Picture name corresponds to the code

 1. Background Picture: Tetris.png

  

2, the failure of the pop-up box picture: Game-over.png

  

 3, seven kinds of color small square Picture:

I.png:

J.png:

L.png:

O.png:

S.png:

T.png:

Z.png:

HTML code

<! DOCTYPE html>
 
 

CSS Code

. Playground {
  width:525px;
  height:550px;
  margin:20px Auto 0 auto;
  position:relative;
  Background-image:url ("Tetris.png");
Playground img {position:absolute}
. Playground p {font-size:30px;
        font-family: ' Simhei ';
        Font-weight:bold;
        Color: #667799;
        Position:absolute;
        left:305px;
        top:120px
}
. Playground p+p {top:176px}
. Playground p+p+p {top:232px;}     

JavaScript code: Two paragraphs with detailed step-by-step explanations

  1, Tetris.js

Window.$=htmlelement.prototype.$=function (selector) {return (this==window?document:this). Queryselectorall (
selector); var tetris={rn:20,//Total number of rows cn:10,//csize:26,//the width of each grid is 26px offset_x:15,//each cell has 15px offset_y:15,//to the left of each cell The top of the grid must be 15px pg:null,//Save the game main interface object currshape:null,//specifically save the graphics object that is being moved nextshape:null,//eight, save the next graphic specifically interval:500,//a second time => falling Speed Timer:null, wall:[],//Six, save all the dropped squares state:1,//10, save the game current status state_running:1,//10, the game is running state_gameover:0 ,//10, Game over state_pause:2,//10, game paused img_gameover: "Img/game-over.png", Img_pause: "Img/pause.png", scores:[0,10,50,80,2 
    00],//13, to add the fractional score:0,//13, the current total lines:0,//13, the current number of rows//10, a picture of a different state for the game paintstate:function () {//depending on the current game status, add a different picture for the game
    var img=new Image (); Switch (this.state) {//If the current state is state_gameover case this. State_gameover://IMG.SRC set to Img_gameover img.src=this.
      Img_gameover;
    Break If the current state is state_pause case this.
   State_pause://IMG.SRC set to Img_pause   Img.src=this.
    Img_pause;
  ///Add IMG to PG This.pg.appendChild (IMG);
    }, Init:function () {this.pg=$ (". Playground") [0];
    The object creating a random graph exists in the Currshape this.currshape=this.randomshape ();
    This.nextshape=this.randomshape (); The null Array object for (Var i=0;i<this) that initializes the wall array to RN.
    rn;i++) {this.wall[i]=[];
    this.score=0;//16, Initialize this.lines=0;//16, initialize this.state=1;//16, initialize This.paint ();
      Third, This.timer=setinterval (function () {//Call Tetris Drop Method Tetris.drop ();
      Then call the Tetris paint method;
    Tetris.paint ();
    },this.interval); Xi. document.onkeydown=function () {var e=window.event| |
      Arguments[0]; Switch (e.keycode) {case 37:tetris.movel (); break;//left Case 39:tetris.mover () break;//right case 40:te Tris.drop (); break;//down//15 steps, Case 38:tetris.rotater (), break;//on the right side of the control of the rotation cases 90:tetris.rotatel (); break;//Letter Z Key control control left rotate//16 step case 80:tetris.pause () break;//Letter P Key: Pause case 81:tetris.gameover (); break;//Letter Q: End game case 67:tetris.mycontinue () break;//letter C, valid after suspend : After the pause, continue the game Case 83://After the game is over, restart if (this.state==this).
          State_gameover) {tetris.init (); }//Letter S key: Restart game}},//init end//16, pause, start, continue, End gameover:function () {this.state=this.
    State_gameover;
    Clearinterval (This.timer);
    This.timer=null;
  This.paint (); }, Pause:function () {if (this.state==this). state_running) {this.state=this.
    State_pause; }, Mycontinue:function () {if (this.state==this). State_pause) {this.state=this.
    state_running; },//15, Rotater:function () {///key, rotate right if this.state==this.
      state_running) {//16 This.currShape.rotateR (); if (this.outofbounds () | |
      This.hit ()) {//Verify not through This.currShape.rotateL (); }}, Rotatel:function () {//key Z, rotate left if (this.state==this).
      state_running) {This.currShape.rotateL (); if (this.outOfbounds () | |
      This.hit ()) {//Verify not through This.currShape.rotateR ();
    }},//11, Mover:function () {This.currShape.moveR (); if (this.outofbounds () | |
    This.hit ()) {//Verify not through This.currShape.moveL ();
    }, Movel:function () {This.currShape.moveL (); if (this.outofbounds () | |
    This.hit ()) {//Verify not through This.currShape.moveR ();
    }, Outofbounds:function () {//checks whether the current graph is out of bounds///col<0 or &GT;=CN var cells=this.currshape.cells of any cell in the current shape; for (Var i=0;i<cells.length;i++) {if (cells[i].col<0| | Cells[i].col>=this.
      CN) {return true;
  return false;
    Hit:function () {//check whether the current shape is colliding//) any cell in the current shape has a lattice var cells=this.currshape.cells in the same position in the wall;
      for (Var i=0;i<cells.length;i++) {if (This.wall[cells[i].row][cells[i].col]) {return true;
  return false; },//Four, redraw all squares, fractions, etc. paint:function () {//Remove all IMG grids and redraw//End 4/*/this.pg.innerhtml=tHis.pg.innerHTML.replace (//g, "");
    This.paintshape ();
    This.paintwall ();
    This.paintnext ();
    13 This.paintscore (); This.paintstate ();//10,},//13, scoring paintscore:function () {//Find span element//first span This.score $ ("span") [0].innerh
    Tml=this.score;
  The second puts This.lines $ ("span") [1].innerhtml=this.lines; }, Drop:function () {//judge whether or not to drop if (this.state==this).
      state_running) {//The row is a 16th step plus if (This.candrop ()) {This.currShape.drop ();
        }else{//six, otherwise//six, if can not fall, will be in the graph of each cell, put into the wall array this.landintowall (); 12, the elimination line, and scoring var ln=this.deletelines ()//eliminate and return this deletion of the number of rows//13, scoring this.score+=this.
        SCORES[LN];
        THIS.LINES+=LN;
        Nine, if the game is not over before.
          if (!this.isgameover ()) {//Seven, will wait Nextshape, change to Currshape This.currshape=this.nextshape;
        Vii. This.nextshape=this.randomshape ();
         }else{//10, otherwise, the first-level end clearinterval (This.timer); This.timer=null; This.state=this.
          State_gameover; This.paint ()///manual Draw Once}}},//12, line up, and score deletelines:function () {//check wall each line to eliminate//traverse wall every Row that defines the number of rows for which the lines variable is deleted for the current row for (Var row=0,lines=0;row<this.
        rn;row++) {//If the current row is full: isfull (Row) if (This.isfull (row)) {//delete the current row: This.deletel (row);
      Each delete row, lines++ lines++;
  } return lines;    
      Isfull:function (Row) {//To determine whether the specified row is full//out of row wall in the line variable var line=this.wall[row]; Traverses each cell for (var c=0;c<this) in line.
      cn;c++) {///As long as the current cell is not valid if (!line[c]) {return false;
  return true when}//traversal ends; Deletel:function (Row) {//delete the specified row and move all the cell down This.wall.splice (row,1);//delete only one row this.wall.unshift ([]);//The top is pressed into a new empty Line//Starting at Row row, iterate up each line for (Var r=row;r>0;r--) {//the current row for (Var c=0;c<this) starts at 0.
       cn;c++) {//If the current grid is valid if (This.wall[r][c]) { The row++ of the current lattice is this.wall[r][c].row++; }},//nine, to determine whether the game is over Isgameover:function () {//Get all the cell in Nextshape, save in cells Var Cells=this.nextsha
    Pe.cells; Traverses the grid var cell=this.wall[cel for each cell for (Var i=0;i<cells.length;i++) {//Wall in cells and the same row,col position of the current cell.
      Ls[i].row][cells[i].col];
      Whenever a valid if (cell) {return true is encountered;
  End of}//for return false;
    },//Eight, paintnext:function () {var cells=this.nextshape.cells;
      for (Var i=0;i<cells.length;i++) {////row+1 of the current cell, var r=cells[i].row+1 in R variable;
      Then the col+11 of the current cell exists in the C variable var c=cells[i].col+11; var x=c*this. Csize+this.
      offset_x; var y=r*this. Csize+this.
      offset_y;
      var img=new Image ();
      img.src=cells[i].img;
      img.style.left=x+ "px";
      img.style.top=y+ "px";
    This.pg.appendChild (IMG); },//Seven, paintwall:function () {//Seven, wall each grid for (Var r=0;r<this) in a two-dimensional array. rn;r++) {For (Var c=0;c<this.
    cn;c++) {var cell=this.wall[r][c]; If the current cell is valid if (cell) {var x=cell.col*this. Csize+this.
          offset_x; var y=cell.row*this. Csize+this.
          offset_y;
          var img=new Image ();
          img.src=cell.img;
          img.style.left=x+ "px";
          img.style.top=y+ "px";
        This.pg.appendChild (IMG); }},//VI, put all stop-drop squares into wall landintowall:function () {///traverse the current graph for each cells////Will be cel L put the same row,col position in wall: this.wall[?] [?]
    =?
    var cells=this.currshape.cells;
    for (Var i=0;i<cells.length;i++) {This.wall[cells[i].row][cells[i].col]=cells[i]; },//Five,//determine whether continue to be able to drop candrop:function () {//traverse the cells in the current currshape//As long as the row==rn-1//of any cell is found to return FA
    LSE//VAR Cells=this.currshape.cells; for (Var i=0;i<cells.length;i++) {if (cells[i].row==this).
      RN-1) {return false; }//Seven, wall, the next line of the current cell is valid if (this.wall[cells[i].row+1][cells[i].col]) {return false}}//after traversal//seven, currshape, any cell below the wall cell return true;
      },//4, randomly generate a graph--two randomshape:function () {switch (parseint (math.random () *7)) {case 0:return new O ();
      Case 1:return New L ();
      Case 2:return New J ();
      Case 3:return New S ();
      Case 4:return New Z ();
      Case 5:return New I ();
    Case 6:return New T ();
    },//3 paintshape:function () {//3), a method that specifically plots the current graphic var cells=this.currshape.cells; for (Var i=0;i<cells.length;i++) {var x=cells[i].col*this. Csize+this.
      offset_x; var y=cells[i].row*this. Csize+this.
      offset_y;
      var img=new Image ();
      img.src=cells[i].img;
      img.style.left=x+ "px";
      img.style.top=y+ "px";
    This.pg.appendChild (IMG); End of},//paintshape}//tetris end Window.onload=function () {tetris.init ();}

2, Shapes.js

function Cell (row,col,img) {this.row=row;
  This.col=col;
  this.img=img; Three Drops if (!
    Cell.prototype.drop) {cell.prototype.drop=function () {this.row++; } if (!
    Cell.prototype.moveR) {//11 cell.prototype.mover=function () {this.col++; } if (!
    Cell.prototype.moveL) {//11 cell.prototype.movel=function () {this.col--;
  }}//14, whereabouts of various changing states function State (R0,C0,R1,C1,R2,C2,R3,C3) {//No. 0 cell relative to the reference cell subscript offset this.r0=r0;
  THIS.C0=C0;
  The 1th cell is this.r1=r1 relative to the subscript offset of the reference cell;
  THIS.C1=C1;
  The 2nd cell is this.r2=r2 relative to the subscript offset of the reference cell;
  THIS.C2=C2;
  The 3rd cell is this.r3=r3 relative to the subscript offset of the reference cell;
THIS.C3=C3;
  function Shape (img,orgi) {this.img=img; this.states=[];//14, save each graph different state of the array this.orgi=orgi;//14, with it as fixed reference point, to rotate deformation, is the array states subscript this.statei=0;// The default all graphics are in the initial state of 0//three if (!
      Shape.prototype.drop) {shape.prototype.drop=function () {///traversing each Cell object in the cells of the current object//calling the drop method of the current Cell object
    for (Var i=0;i<this.cells.length;i++) {    This.cells[i].drop (); }} if (! Shape.prototype.moveR) {///11 Shape.prototype.mover=function () {///traversing each Cell object in the cells of the current object for (Var i=0;i<th
      is.cells.length;i++) {//Calls the Drop Method This.cells[i].mover () of the current cell object; }} if (! Shape.prototype.moveL) {///11 Shape.prototype.movel=function () {///traversing each Cell object in the cells of the current object for (Var i=0;i<th
      is.cells.length;i++) {//Calls the Drop Method This.cells[i].movel () of the current cell object; }}//15 if (!
      Shape.prototype.rotateR) {shape.prototype.rotater=function () {//if (object.getprototypeof (this)!=o.prototype) {
        if (this.constructor!=o) {this.statei++;
        this.statei>=this.states.length&& (this.statei=0);
        Get the next state object Var State=this.states[this.statei];
        var Orgr=this.cells[this.orgi].row;
        var Orgc=this.cells[this.orgi].col; Iterates through each cell in the current Graph//by the offset in state, setting the new position for each cell for (Var i=0;i<this.cells. length;i++) {this.cells[i].row=orgr+state["R" +i];
        this.cells[i].col=orgc+state["C" +i]; End of}//for end of}//if}//function end of}//if if (! Shape.prototype.rotateL) {shape.prototype.rotatel=function () {//if () {object.getprototypeof (this)!
        O.prototype) {if (this.constructor!=o) {this.statei--;
        this.statei<0&& (this.statei=this.states.length-1);
        Get the next state object Var State=this.states[this.statei];
        var Orgr=this.cells[this.orgi].row;
        var Orgc=this.cells[this.orgi].col; Traverses each cell//in the current graph to set the heart position of each cell for (Var i=0;i<this.cells.length;i++) {this.cells[) according to the offset in state.
          i].row=orgr+state["R" +i];
        this.cells[i].col=orgc+state["C" +i]; End of}//for end of}//if end of}//function end}//if end of}//function Shape (Img,orgi)//Two function O () {//1 shape.call (th
  IS, "img/o.png"); if (! Shape.prototype.isPrototypeOf (O.prototype)) {object.setprototypeof (O. prototype,shape.prototype);//inheritance} this.cells=[new cell (0,4,this.img), new cell (0,5,this.img), new cell (1,4,th
IS.IMG), New Cell (1,5,THIS.IMG)];
  function T () {//2 Shape.call (this, "Img/t.png", 1); if (! Shape.prototype.isPrototypeOf (T.prototype)) {object.setprototypeof (t.prototype,shape.prototype);//inheritance} this.cells
  =[new Cell (0,3,this.img), new cell (0,4,this.img), new cell (0,5,this.img), new cell (1,4,this.img)];
  14 This.states[0]=new State (0,-1, 0, 0, 0, 1, 1,0);
  This.states[1]=new state ( -1,0, 0, 0, 1, 0, 0,-1);
  This.states[2]=new state (0,1, 0, 0, 0,-1, -1,0);
            This.states[3]=new State (1, 0, 0, 0, -1,0, 0,1);
  [0] [1] [2] [3]} function I () {//3 Shape.call (this, "Img/i.png", 1); if (! Shape.prototype.isPrototypeOf (I.prototype)) {object.setprototypeof (i.prototype,shape.prototype);//inheritance} this.cells
  =[new Cell (0,3,this.img), new cell (0,4,this.img), new cell (0,5,this.img), new cell (0,6,this.img)]; This.states[0]=new StaTe (0,-1, 0, 0, 0, 1, 0,2);
[0] [1] [2] [3] this.states[1]=new state ( -1,0, 0, 0, 1, 0, 2,0);
  } function S () {//4 Shape.call (this, "Img/s.png", 3); if (! Shape.prototype.isPrototypeOf (S.prototype)) {object.setprototypeof (s.prototype,shape.prototype);//inheritance} this.cells
  =[new Cell (0,4,this.img), new cell (0,5,this.img), new cell (1,3,this.img), new cell (1,4,this.img)];
  14 This.states[0]=new State ( -1,0, -1,1, 0,-1, 0,0);
            This.states[1]=new State (0,1, 1, 1, -1,0, 0,0);
  [0] [1] [2] [3]} function Z () {//5 Shape.call (this, "Img/z.png", 1); if (! Shape.prototype.isPrototypeOf (Z.prototype)) {object.setprototypeof (z.prototype,shape.prototype);//inheritance} this.cells
  =[new Cell (0,3,this.img), new cell (0,4,this.img), new cell (1,4,this.img), new cell (1,5,this.img)];
  This.states[0]=new state (0,-1, 0, 0, 1, 0, 1,1);
            This.states[1]=new state ( -1,0, 0, 0, 0,-1, 1,-1); [0] [1] [2] [3]} function L () {//6 Shape.call (this, "img/L.png ", 1); if (! Shape.prototype.isPrototypeOf (L.prototype)) {object.setprototypeof (l.prototype,shape.prototype);//inheritance} this.cells
  =[new Cell (0,3,this.img), new cell (0,4,this.img), new cell (0,5,this.img), new cell (1,3,this.img)];
  This.states[0]=new state (0,-1, 0, 0, 0, 1, 1,-1);
  This.states[1]=new state ( -1,0, 0, 0, 1, 0, -1,-1);
  This.states[2]=new state (0,1, 0, 0, 0,-1, -1,1);
            This.states[3]=new State (1, 0, 0, 0, -1,0, 1,1);
  [0] [1] [2] [3]} function J () {//7 Shape.call (this, "Img/j.png", 1); if (! Shape.prototype.isPrototypeOf (J.prototype)) {object.setprototypeof (j.prototype,shape.prototype);//inheritance} this.cells
  =[new Cell (0,3,this.img), new cell (0,4,this.img), new cell (0,5,this.img), new cell (1,5,this.img)];
  This.states[0]=new state ( -1,0, 0, 0, 1,-1, 1,0);
  This.states[1]=new state (0,1, 0, 0, -1,-1, 0,-1);
  This.states[2]=new State (1, 0, 0, 0, -1,1, -1,0);
            This.states[3]=new state (0,-1, 0, 0, 1, 1, 0,1); [0] [1] [2] [3]
} 

The final effect figure looks like this:

------------------------------------------------------------------------------------> Change for Life, create for change.

The above is a small series for you to share on the JavaScript code based on the web version of the Tetris. I hope you like it.

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.