HTML5 Canvas学习笔记(8)俄罗斯方块游戏之二(方块)

阅读更多
接上一遍《HTML5 Canvas学习笔记(7)俄罗斯方块游戏之一(色块)》
http://128kj.iteye.com/blog/2088202
先看这个游戏中的第二个重要类Shape,它表示一种随机的俄罗斯方块,由若干个色块Block组成。

代码:
 // Shape Constructor 方块由色块组成
 function Shape(image){
   this.block = new Block(image);
   this.layout;//表示某种俄罗斯方块的结构,二维数组
   this.blockType;//块的类型
   this.currentX = 0;
   this.currentY = 0;
   this.layouts = [//俄罗斯方块的所有类型
      [
       [ 0, 1, 0 ],
       [ 1, 1, 1 ]
      ],[
       [ 0, 0, 1 ],
       [ 1, 1, 1 ]
      ],[
       [ 1, 0, 0 ],
       [ 1, 1, 1 ]
      ],[
       [ 1, 1, 0 ],
       [ 0, 1, 1 ]
      ],[
       [ 0, 1, 1 ],
       [ 1, 1, 0 ]
      ],[
       [ 1, 1, 1, 1 ]
      ],[
       [ 1, 1 ],
       [ 1, 1 ]
      ]
    ];
   }
 
  Shape.prototype = {
     random: function(){
        //取一种随机类型
       var layout = this.layouts[ Math.floor(Math.random() * this.layouts.length) ];
       this.blockType = this.block.random();//随机的块类型
       for (var y=0; y < layout.length; y++){
         for (var x=0; x < layout[0].length; x++){
           if (layout[y][x]) layout[y][x] = this.blockType;
	  }
       }
       this.layout = layout; 
     },
	
     defaultXY: function(){//缺省的方块位置
        this.currentX = Math.floor((13 - this.layout[0].length)/2);
        this.currentY = 0;
     },
     new: function(){//产生一个新的俄罗斯方块
        this.random();
        this.defaultXY();
        return this;
     },
     fixCurrentXY: function(){//修正方块的位置
        if (this.currentX < 0) this.currentX = 0;
        if (this.currentY < 0) this.currentY = 0;
        if (this.currentX + this.layout[0].length > 13) 
                 this.currentX = 13 - this.layout[0].length;
        if (this.currentY + this.layout.length    > 20)
                 this.currentY = 20 - this.layout.length;
     },
     rotate: function(){//旋转此方块
         var newLayout = [];//新的方块
         for (var y=0; y < this.layout[0].length; y++){
            newLayout[y] = [];
            for (var x=0; x < this.layout.length; x++){
               newLayout[y][x] = this.layout[this.layout.length - 1 - x][y];
             }
          }
          this.layout = newLayout;
          this.fixCurrentXY();
      },
      draw: function(context){//绘制此方块         
         try {
           for (var y=0; y < this.layout.length; y++){
            for (var x=0; x < this.layout[y].length; x++){
              if (this.layout[y][x]) 
  this.block.draw(context, x + this.currentX, y + this.currentY, this.blockType);
	     }
	    }
	   } catch(e){
             console.log("Error: can't draw the shape.");
          }
      }
     }



下面是测试效果图:
HTML5 Canvas学习笔记(8)俄罗斯方块游戏之二(方块)_第1张图片

点击可看效果:
http://www.108js.com/article/canvas/7/2/e2.html

测试代码:






俄罗斯方块:方块测试




 

    Your browser doesn't support Canvas
 




欢迎访问博主的网站: http://www.108js.com
下载源码:
  • HTML5 Canvas学习笔记(8)俄罗斯方块游戏之二(方块)_第2张图片
  • 大小: 7.1 KB
  • 2.zip (9 KB)
  • 下载次数: 10
  • HTML5 Canvas学习笔记(8)俄罗斯方块游戏之二(方块)_第3张图片
  • 大小: 3.4 KB
  • 查看图片附件

你可能感兴趣的:(游戏,html5,javascript,html,编程)