Want to clear old image position when player move to new position

want to clear old image position when player move to new position


const cvs = document.getElementById("game");
const ctx = cvs.getContext("2d");
const ROW = 15;
const COL =15;
const VACANT = "WHITE"
const SQ =40;
function drawSquare(x,y,color){
  ctx.fillStyle = color;
  ctx.fillRect(x*SQ,y*SQ,SQ,SQ);
  ctx.strokeStyle = "Black";
  ctx.strokeRect(x*SQ,y*SQ,SQ,SQ);
}
//create board 
let board= [];
for(r =0;r<ROW; r++){
   board[r] = [];
   for(c=0;c<COL;c++){
       board[r][c]=VACANT;
   }
}
//Draw the Board
function drawBoard(){
  for(r =0;r<ROW; r++){
   for(c=0;c<COL;c++){
       drawSquare(c,r,board[r][c]);
   }
  }
}

drawBoard();



let foodImg = new Image();
foodImg.src = "images/food.png" ;
let playerImg1 = new Image();
playerImg1.src = "images/player1.jpg" ;
let playerImg2 = new Image();
playerImg2.src = "images/player2.jpg" ;
//Block image
let blockImg = new Image();
blockImg.src = "images/block.jpg" ;
//let  blockImg = document.getElementById('block1');
let food = {
x: Math.floor(Math.random()*8 + 12) * SQ,
y: Math.floor(Math.random()*13 + 1) * SQ
}
let player1 ={
x: Math.floor(Math.random()*0 + 2) * SQ,
y: Math.floor(Math.random()*4+ 0) * SQ

}
let player2 ={
x: Math.floor(Math.random()*3 + 12) * SQ,
y: Math.floor(Math.random()*13 + 6) * SQ

}
//control Player
let d;
document.addEventListener("keydown",direction)
function direction(event){

  if(event.keyCode == 37){
     
      player1.x -= SQ * 3;
       
  }else if(event.keyCode == 38 ){
     player1.y -= SQ * 3;
  }else if(event.keyCode == 39){
     player1.x += SQ * 3;
  }else if(event.keyCode == 40){
     player1.y += SQ * 3;
  }

moveCharacter();
}
function moveCharacter(){
ctx.drawImage(foodImg,food.x,food.y);
ctx.clearRect(playerImg1,0,0,player1.x,player1.y);
  ctx.drawImage(playerImg1,player1.x,player1.y);
   
  ctx.drawImage(playerImg2,player2.x,player2.y);
    
}
function draw(){
  
	ctx.drawImage(foodImg,food.x,food.y);
	ctx.drawImage(playerImg1,player1.x,player1.y);
  
	ctx.drawImage(playerImg2,player2.x,player2.y);
    for(let i = 0 ; i<=10; i++ ){
    	let block ={
x: Math.floor(Math.random()*8 + 3) * SQ,
y: Math.floor(Math.random()*13 + 2) * SQ

}    

let j = ctx.drawImage(blockImg,block.x,block.y) ;
      
      j
      
	}


}

draw();
var button = document.getElementById("button");
button.addEventListener("click", draw); 


clear the entire board, remembering that you have player1, player2 and food stored somewhere. Then, simply redraw the players and food.

It’s brute-force, but it’s a common solution. Alternatively, you can create an oldX and oldY property on player1 and player2, and on move, before the move happens, set oldX and oldY to the players x and y values, then use those to only redraw the one tile you need.

Purely treating this as a thought experiment, haven’t coded it, but these are the two solutions that would be easiest to implement.

1 Like
  var player1 = { 
    image: 'images/player1.jpg' ,
    x: Math.floor(Math.random()*0 + 2) * SQ,
    y: Math.floor(Math.random()*4+ 0) * SQ
  }
  function getKeyAndMove(e){        
    var key_code=e.which||e.keyCode;
    switch(key_code){
      case 37: //left arrow key
        moveLeft();
        break;
      case 38: //Up arrow key
        moveUp();
        break;
      case 39: //right arrow key
        moveRight();
        break;
      case 40: //down arrow key
        moveDown();
        break;            
    }
  }
  function moveLeft(){
     player1.x -= SQ ;
  }
  function moveUp(){
    player1.y -= SQ ;
  }
  function moveRight(){
     player1.x += SQ ;
  }
  function moveDown(){
     player1.y += SQ ;
  }
//what does occupiedObject =this means?

 $('.grid-item').each(function(){
      const element = $(this);
      const block = this;
      // value larger with larger X
      if(isInDistance(player, block) && (block.dataset['x'] > player.position.x)){
        if(squareOccupied(element)){
          occupiedObject = this;
          $('.possible').each(function(){
            const element = $(this);
            const block = this;
            if (block.dataset['x'] > occupiedObject.dataset['x']){
              element.removeClass("possible");
            }
          });
        }
      }

When you get into the $('.possible').each(function(){...}, the context of this has changed.

Presumably, the OP is using occupiedObject = this; to keep the current `$(’.grid-item’) reference, within the context of the nested function

1 Like
//when i play game in first turn code works fine but in second turn red blocks merging dont know //why pls help
//Weapons
const weapons = [
  { 
    name:"Dagger",
    damage:15,
    className:"weapon-1",
    image:"images/daga.png"

  },
  { 

    name:"Dagger",
    damage:15,
    className:"weapon-2",
    image:"images/daga.png"

  },
  { 

    name:"Dagger",
    damage:15,
    className:"weapon-3",
    image:"images/daga.png"

  },
  { 

    name:"Dagger",
    damage:15,
    className:"weapon-4",
    image:"images/daga.png"

  },

];
//Players
const player1 ={
  position:{
   x:0,
   y:0
  },
  health: 100,
  hasWeapon: false,
  currentWeapon: weapons[0],
  isDefending: false
};
const player2 ={
  position:{
   x:0,
   y:0
  },
  health: 100,
  hasWeapon: false,
  currentWeapon: weapons[0],
  isDefending: false
};


 const generateRandomNum = () => Math.floor(Math.random() * 10);

  // Generate grid for game board with blocks
  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      $('.main').append('<div class="grid-item" data-y='+i+' data-x='+j+'>'+i+' '+j+' </div>');
      
    }
  }
  
  // Loop to elements to display them on the board
  function generate(func, times){
    for (let i = 0; i < Number(times); i++) {
      func();
    }
  }
// This functions checks available square and place blocks, weapons and players on the board
function placeElements(className) {
    const random_x = generateRandomNum();
    const random_y = generateRandomNum();
    $('.grid-item').each(function(){
      const element = $(this);
      if (this.dataset['x'] == random_x && this.dataset['y'] == random_y) {
        if (!(this.classList.contains("unavailable"))){
          element.addClass(className);
          element.addClass("unavailable");
          // updates the position values to the player objects
          if (className === "player-1") {
            player1.position.x = this.dataset['x'];
            player1.position.y = this.dataset['y'];
          } else if (className === "player-2"){
            player2.position.x = this.dataset['x'];
            player2.position.y = this.dataset['y'];
          } else if (className === "weapon-1" ||
                    className === "weapon-2"||
                    className === "weapon-3"||
                    className === "weapon-4"){
            element.addClass("weapon");
            
          }
        
        }else{
          placeElements(className);
        }
        
      }
    });
  }

  // Clean all the board
  function reset() {
    $('.grid-item').each(function(){
      const element = $(this);
      element.removeClass("block");
      element.removeClass("weapon");
      element.removeClass("weapon-1");
      element.removeClass("weapon-2");
      element.removeClass("weapon-3");
      element.removeClass("weapon-4");
      element.removeClass("frostbite");
      element.removeClass("shield");
      element.removeClass("player-1");
      element.removeClass("player-2");
      element.removeClass("possible");
      element.removeClass("unavailable");
      
       fightMode = false;
      
     
    });
  }

  // This functions generates que board calling on the diferent pieces
  function generateGame(){
  reset();
  // Anonymous functions so I can pass the parameters to the function without calling it
  generate(function(){
    placeElements("block");
  },12);
  generate(function(){
    placeElements("weapon-2");
  },1);
  generate(function(){
    placeElements("weapon-3");
  },1);
  generate(function(){
    placeElements("weapon-4");
  },1);
  generate(function(){
    placeElements("frostbite");
  },6);
  generate(function(){
    placeElements("shield");
  },1);
  generate(function(){
    placeElements("player-1");
  },1);
  generate(function(){
    placeElements("player-2");
  },1);
  movePlayer(player1);
  movePlayer(player2);
  pathHighlight();
  }
/////////////////// Move Player
let playerTurn = true; 
 function pathHighlight() {
    if (!fightMode){
      if (playerTurn) {
        possiblePath(player1);
      } else {
        possiblePath(player2);
      }
    }
  }

   function movePlayer(player){
  $('.grid-item').click(function(){
  pathHighlight();
  const element = $(this);
  const block = this;
    // Make sure is within distance
    if (element.hasClass("possible")) {
        if (player === player2) {
          if (!playerTurn){

            playerReset("player-2");

            element.addClass("player-2");
            playerTurn = !playerTurn;
            

            }
        } 
        if (player === player1) {
          if (playerTurn){
           playerReset("player-1");
            element.addClass("player-1");
            playerTurn = !playerTurn;
            
          }
        }
    }
    pathHighlight();
  });
  } 

 
  /////////////////////////////////////////////////////////////////////////////////////////
   function playerReset(player) {
    $('.grid-item').each(function(){
      const element = $(this);
      element.removeClass(player);
      element.removeClass("possible");
    });
  }

  function squareOccupied (element) {
    return (
      element.hasClass("block") || 
      element.hasClass("player-1") || 
      element.hasClass("player-2")
      );
  }

  function possiblePath(player) {
    $('.grid-item').each(function(){
      const element = $(this);
      const block = this;
      if (isInDistance(player, block) && !squareOccupied(element)){
        element.addClass("possible");
      }
    });
    $('.grid-item').each(function(){
      const element = $(this);
      const block = this;
      // value larger with larger X
      if(isInDistance(player, block) && (block.dataset['x'] > player.position.x)){
        if(squareOccupied(element)){
          occupiedObject = this;
          $('.possible').each(function(){
            const element = $(this);
            const block = this;
            if (block.dataset['x'] > occupiedObject.dataset['x']){
              element.removeClass("possible");
            }
          });
        }
      }
      // value with lower X
      if(isInDistance(player, block) && (block.dataset['x'] < player.position.x)){
        if(squareOccupied(element)){
         const occupiedObject  = this;
          $('.possible').each(function(){
            const element = $(this);
            const block = this;
            if (block.dataset['x'] < occupiedObject.dataset['x']){
              element.removeClass("possible");
            }
          });
        }
      }
      // value with higher y
      if(isInDistance(player, block) && (block.dataset['y'] > player.position.y)){
        if(squareOccupied(element)){
         const occupiedObject  = this;
          $('.possible').each(function(){
            const element = $(this);
            const block = this;
            if (block.dataset['y'] > occupiedObject.dataset['y']){
              element.removeClass("possible");
            }
          });
        }
      }
      // value with lower y
      if(isInDistance(player, block) && (block.dataset['y'] < player.position.y)){
        if(squareOccupied(element)){
         const  occupiedObject  = this;
          $('.possible').each(function(){
            const element = $(this);
            const block = this;
            if (block.dataset['y'] < occupiedObject.dataset['y']){
              element.removeClass("possible");
            }
          })
        }
      }
    })
  }

  // I need to reference all the elements that are "inDistance"
  // To determine if they have block or player class, if they do
  // movement is not possible
  function isInDistance (player, block) {
    const firstCondition = (Math.abs(block.dataset['x'] - player.position.x) <= 2)
    && (block.dataset['y'] === player.position.y);
    const secondCondition = (Math.abs(block.dataset['y'] - player.position.y) <= 2) 
    && (block.dataset['x'] === player.position.x);
    return (firstCondition || secondCondition);
  }
  
![pic1|690x430](upload://5O5n9yFDVzkxS8GCK7xGoUkALdG.png) ![pic2|690x430](upload://36E7AcQzL5FvODSxPVbDDfMEdQk.png)