Hard copy of array with instance of class within object

Jakub Menšík :

I am creating a simple game with multiple levels. Each level is represented by object of key-value pairs. Inside each level there is also array with new instances of class that will be loaded inside the level. So far it worked fine but when i implemented restart button program cannot load thoose instances again because i already changed them. So i need to hard copy thoose instances into level and when you press restart button you can just hard copy them again.

This is an example of my level object.

const level4 ={
 width:window.innerWidth,
 height:window.innerHeight,
 gates:[new Gate(canvas.width-20, 100,0,-2), new Gate(200, 15,4,-1)],
 blocks:[new Block(50,100,0, 0, 50, 1, 2), new Block(200,200,0, 0, 50, 1, 1)],
 difficulty:'easy',
 id:4
};

I already try to hard copy object with this parse function but it doesnt work.

const parseLevel = (currentLevel) =>{
  return {
    width: currentLevel.width,
    height: currentLevel.height,
    gates: parseObjects(currentLevel.gates),
    blocks: parseObjects(currentLevel.blocks),
    difficulty: currentLevel.difficulty,
    id: currentLevel.id
  };
};

const parseObjects = (array) =>{
  let newArray = [];
  for(let i of array){
  let newObj = Object.assign( Object.create( Object.getPrototypeOf(i)),i);
  newArray.push(newObj);
  }
return newArray;
};

And in my function where I am loading the level I call:

 level = parseLevel(level4);
zord :

I think the simple solution is to convert your level4 from a constant to a function. That way you could call it multiple times and always get a fresh instance.

const level4 = () => ({
  width: window.innerWidth,
  height: window.innerHeight,
  gates:[
    new Gate(canvas.width-20, 100,0,-2), 
    new Gate(200, 15,4,-1)
  ],
  blocks:[
    new Block(50,100,0, 0, 50, 1, 2), 
    new Block(200,200,0, 0, 50, 1, 1)
  ],
  difficulty: 'easy',
  id: 4
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29756&siteId=1