Problems and solutions in the implementation of Tetris with jquery

Time:2021-1-18

Record the problems when writing this game.

When the key is pressed, it is forbidden to trigger repeatedly

Demand: when the key is pressed, the speed will be reduced by 300 on the basis of the current value, speed – = 300
There is a problem: when the key is pressed and held, speed will continue to perform self subtraction
Solution: set a flag and add if condition. When the key is pressed, the flag value will change. When the Keyup event is triggered, the flag will change back to the original value.

//Triggered when Keydown
Game.prototype.speedUp = function(){
    if(!this.speedFlag){
        this.speed  -=300; // speed up to reduce the time interval between drops
        if(this.speed<50){
            this.speed = 50;
        }
        this.speedFlag = true;
    }

    console.log('speedUp'+this.speed);

}

//Triggered when Keyup
that.speed += 300;
                if(that.speed>(500 - (that.level -1)*50)){
                    that.speed = 500 - (that.level -1)*50;
                }
                that.speedFlag=false;

Press the key to control the time interval of setinterval

Requirement: when pressing the down button, the falling speed will be accelerated, that is, the running interval of setinterval will be reduced
There is a problem: whether you change the speed value outside or inside setinterval, it can only take effect after clearinterval, which cannot meet the requirements
Solution: change setinterval to setTimeout, call itself in setTimeout, form recursion, and then realize the requirement

Block position detection

Requirement: when there is no box, it will drop directly to the bottom of the interface. When there is a block, stop on the block.
Problem: how to record the position of the existing block
Solution: get the top and left positions of each block, splice them into a string, and store them in the array blockarea. Every time a block falls, it detects whether the next position of each block already exists in the block area. If not, it is allowed to fall. Otherwise, stop falling and generate the next block.