H5实现俄罗斯方块(四)

图片加载的js:

(function (window) {

    'use strict';
   //定义缓存的Map对象
  var cacheMap = new Map(); 
  //资源的总数量
  var resourceTotalCount = 1; 
 //当前加载资源的数量
  var currentLoaded = 0; 

   //判断是否都是加载成功
 var isAddLoaded = function () {
    //当前的数量  +1
      currentLoaded += 1;
     //当前的数量是否等于我们的总量 判断是否为函数
   if (currentLoaded === resourceTotalCount && typeof window.ResourceManager.onResourceLoaded === 'function') {
      window.ResourceManager.onResourceLoaded();
    }
  };
   //加载资源的方法
   var init = function () {
     //定义图片的对象
   var image = new Image();
      //加载时的回调函数
   image.onload = function () {
        //把对象进行存储
     cacheMap.set('blocks', image);
      isAddLoaded();
    };
     //指定加载的路径
     image.src = 'images/blocks.png';
  };

var getResource = function (key) {
      //返回资源
    return cacheMap.get(key);
  };
 //ResourceManager  挂在到window上
   window.ResourceManager = {
    getResource: getResource,
    init: init,
    onResourceLoaded: null // 资源加载完成回调
  };
})(window);

 当前得分的js:

(function (window) {
  'use strict';
   //得分的面板
  function Score() {
    this.canvas = new Canvas('score', 100, 70);
     //得分
   this.score = 0;

    this._init();
  }

 Score.prototype = {
    constructor: Score,
    _init: function () {
      this._render();
    },
     //绘制得分
    _render: function () {
      this.canvas.drawText(this.score);
    },
     //分数的变化
     addScore:function(value){
       this.score+=value;
       //渲染
     this._render();
     //返回当前的得分
     return this.score;
     }
   };


   window.Score=Score;
})(window);

 方块的调整js:

(function (window) {
  'use strict';
  //布局
var shapeLayouts=[
        [[0,1,0],[1,1,1]],
        [[1,1,1,1]],
        [[1,1],[1,1]],
        [[0,1],[1,1],[1,0]],
        [[1,0],[1,1],[0,1]],
        [[1,0,1],[1,1,1]],
        [[0,1],[1,1]],
        [[1,1]],
        [[1,1],[1,0],[1,0]],
        [[1,1],[0,1],[0,1]],
];

   //生成随机数的方法(通过最小值和最大值随机生成数据)
    var random=function(minValue,maxValue){
    return  minValue+ Math.floor(Math.random()*maxValue);//产生随机数  从0到1  (包含0,不包含1)
      };
       //定义颜色总类
      var styleCount=7;

  function Shape() {
     this.x = 0;
    this.y = 0;
    //随机生成颜色
    this.blockType=random(1,styleCount);
    this.block = new Block(this.blockType);
  
   this.layout=shapeLayouts[random(0,shapeLayouts.length)]; 
  }

  Shape.prototype = {
    constructor: Shape,
    draw: function (context,size) {
      for (var i = 0; i < this.layout.length; i++) {
        for (var j = 0; j < this.layout[i].length; j++) {
          if (this.layout[i][j]) {
            this.block.draw(context, j + this.x, i + this.y,undefined,size);
          }
        }
      }
    },
 
   
 
    //反转算法
     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._setLayout();
     },
  _setLayout: function () {
      if (this.x < 0) {
        this.x = 0;
      }
      if (this.y < 0) {
        this.y = 0;
      }
      if (this.x + this.layout[0].length > TetrisConfig.cols) {
        this.x = TetrisConfig.cols - this.layout[0].length;
      }
      if (this.y + this.layout.length > TetrisConfig.rows) {
        this.y = TetrisConfig.rows - this.layout.length;
      }
    },

   //算出最大的cols
   _getMaxCols:function(){
        var max=0;
        for(var y=0;y<this.layout.length;y++)
        {
          max=Math.max(max,this.layout[y].length);   
        }
        return max;
   },
   _getMaxRos:function(){
     return this.layout.length;
   }, 
    //ignoreRows 主面板和小面板显示的效果
    setPosition:function(cols,rows,ignoreRows){
     this.x=Math.floor((cols- this._getMaxCols()) /2);
      if(!ignoreRows){
        this.y=Math.floor((rows-this._getMaxRos())/2);
      }
    }
  };

  window.Shape = Shape;
})(window);

 整个文件加载js:

(function (window) {
  'use strict';

  //计时器的id
  /** var intervalId;
var speed=200;*/

function Tetris() {
   
    this.board = new Board(this);
    //成绩
    this.score=new Score();
    //时间
      this.timer = new Timer();
      this.level=new Level();
      //下一方块
       this.nextshape=new NextShape();
       //最高分
     this.highscore = new HighScore();
      
   this._sound;
   this._state='playing'; 

    //启动键盘事件
    (new keyboard()).init(this.board); 
}

Tetris.prototype ={
  
     constructor: Tetris,
     _initAudio:function(){
     this._sound =new Howl({
         src:['audio/bg.wav'],
         loop:true,
         //音量
         volume:0.3,
       });
     
     this._playSound();
     },

_playSound:function(){
 if(window.TetrisConfig.config.enableSound){
 this._sound.play();
      }
},

//重复利用的方法进行封装
_startTick(){
var self=this;
      var self=this;
  window.TetrisConfig.intervalId = window.setInterval(function(){
       //每次调用他的tick
       self.board.tick();
     }, TetrisConfig.speed);
},
   //取消tick的公用方法
_stopTick:function(){
    window.clearInterval(window.TetrisConfig.intervalId);
},

   //开始
    startGame: function(){
     //初始化音频
     this._initAudio();
     //开始tick方法
     this._startTick();
   },

   //结束
   endGame:function(){
    //停止声音播放   找到声音实例  停止
    this._sound.stop();
    //停止Tick
    this._stopTick();
    //停止计时
    this.Timer.stop();

   },
   pause:function(){
     if(this._state==='over'){
       return;
     }
     //暂停播放音乐
     this._sound.pause(); 
     //暂停事件响应
     this._state='pause';

     //取消tick
    this._stopTick();
    //暂停计时器
    this.timer.pause();
   },
   resume:function(){
     //避免再次生效
     if(this._state==='over'){
       return;
     }
   //this._sound.play();
   this._playSound();
   this._state='playing';
   //恢复tick方法
   this._startTick();
   //重新激活
   this.timer.resume(); 

   } 

};

  window.Tetris = Tetris;

})(window);

 计时器的js:

(function (window) {
  'use strict'
  function Timer() {
    this.canvas=new Canvas('timer',100,70);
    //毫秒数
    this.time=0;
    //存储时间的Inver
    this.timerId;

    this._init();
  };

 Timer.prototype = {
    constructor: Timer,
    _init: function () {
       var self=this;
       this._render();
      //时间的累加
      this.resume();
    },
    //处理time的值
    _format:function(seconds){
       //取出毫秒数  小时
      var hours=Math.floor(seconds/(3600));
      seconds=seconds-hours*3600;
      //分钟
      var minutes=Math.floor(seconds/ 60);
      seconds=seconds-minutes*60;
      if(hours<10){
        //补零
        hours='0'+hours;
      }
      if(minutes<10){
        minutes='0'+minutes;
      }
      if(seconds<10){
        seconds='0'+seconds;
      }
      return hours+':'+minutes+':'+seconds;
    },
    _render: function () {
      this.canvas.drawText(this._format(this.time));
    },
    pause:function(){
      window.clearInterval(this.timerId)
    },
    resume:function(){
       //恢复时激活
       var self=this;
       this.timerId=window.setInterval(function(){
         self.time += 1;
         self._render();
       },1000);
    },
    stop:function(){
        this.pause();
    }
  };

  window.Timer = Timer;
})(window);

 开发工具vscode

原文地址:https://www.cnblogs.com/sunliyuan/p/6219558.html