Search code examples
javascripthtmlcanvas2d-games

Save position of elements in canvas while is moving others


I'm starting to learn Html5 canvas with a simple game, Tetris. I need to save the position of the pieces in canvas when this pieces arrive to the bottom of canvas, and then stay there. Then create other piece and moving it to the bottom. But when the first piece arrives to the bottom of the canvas it dissapears and the new piece appears at the top and starts to down. Why the first piece not remains in the bottom? This is the code:

var canvas;
var context;
var _this;
var pantalla = {
    width: 325,
    height: 650,
    figuras: []
}

The object "pantalla" is an object with the properties of the screen, width, height, and the pieces that are painted.

function Game(dificulty){
   this.time = dificulty; 
   this.initGame = function(){
      canvas = document.getElementById("canvas");
      context = canvas.getContext("2d");
      //context = canvas.getContext("3d");  

      _this = this;
      figura = _this.generarFigura();
      interval = setInterval(function(){_this.loop()},_this.time);  
   };

The "initGame" method creates the context and creates the first piece and then initiates the loop.

   this.loop = function(){
      figura.update();
      figura.paint();
      if((figura.y)>=pantalla.height){
        clearInterval(interval);
        figura = _this.generarFigura();
        interval = setInterval(function(){_this.loop()},_this.time);
      }
   };

The method "loop" iterates until the piece is in the bottom of the canvas, then is stopped the iteration clearing the interval, is created a new piece and starts the interval again.

   this.generarFigura = function(){
      var numeroFigura = Math.floor(Math.random() * 0);
      var numeroPosFigura = Math.floor(Math.random() * 10);
      var figurasPosibles = ['i','j','t','o','z','s','l'];
      var figura;

      switch(figurasPosibles[numeroFigura]){
        case 'i': figura = new Figura('i'); break;
        case 'j': break;
        case 't': break;
        case 'o': break;
        case 'z': break;
        case 's': break;
        case 'l': break;
      }

      pantalla.figuras[pantalla.figuras.length] = figura;


      //Si sale un numero que colocando la posicion se salga de la pantalla
      //No me complico y la dejo en la (0,0)
      if(((numeroPosFigura * 32.5) + figura.width) <= pantalla.width){
          figura.x = 32.5 * numeroPosFigura;
      }

      figura.paint();
      return figura;
   };

The method "generarFigura" chooses a piece random and is added to the list of pieces of the object screen (pantalla). And then this pieces is painted in the context.

 function Figura(tipo){
    this.x = 0;
    this.y = 0;
    switch(tipo){
       case 'i': this.width = 162.5; this.height = 32.5; 
          this.update = function(direccion){
            context.clearRect(this.x,this.y,this.width,this.height);    
            if(direccion){
                if(direccion=='derecha' && (this.x+this.width)<pantalla.width){
                    this.x += 32.5;
                }else if(direccion=='izquierda' && this.x>0){
                    this.x -= 32.5;
                }
            }else{//Si no se mueve en ninguna dirección la figura baja
                this.y += 32.5;
            }
          };
          this.paint = function(){
            context.beginPath();
            context.canvas.width = context.canvas.width;        
            context.fillRect(this.x,this.y,this.width,this.height);
            context.stroke();
          }; break;
     }
  };

The "update" method of each piece deletes the old position of the piece and update the parameters (If "direccion" exists moves the piece to right or to left). The "paint" method paints the piece in the parameters indicated of this.

Can someone help me? Thanks.


Solution

  • Your update() function is still moving the pieces even after they reach the bottom. The fix is to move the piece only if it has not reached the bottom:

    // in update()
    if(this.y<pantalla.height-this.height){
        this.y+=32.5;
        // adjust if the piece is slightly below the bottom
        if(this.y>pantally.height-this.height{
            this.y=pantally.height-this.height;
        }
    }
    

    BTW, your Math.floor(Math.random() * 0) will always be zero.

    Good luck with your Tetris game!