简体   繁体   中英

updating JavaScript classes using template literals

I have a limited understanding of JavaScript classes and am finding it difficult to find good resources about them to help me with my project.

I have created the following classes for a turn based game;

 class Player { constructor(name, image, location, isTurn) { this.name = name; this.image = image; this.location = location; this.isTurn = isTurn; this.cssClass = "player"; this.weapon = "unarmed"; this.health = 100; //deal with default weapon here } // get css class getCSSClass() { return this.cssClass; } getPosition() { return this.location; } // set position setPosition(identifier) { this.location = identifier; return this.location.toString(); } } let player1 = new Player("player2", "css/player1.png", "", true); let player2 = new Player("player2", "css/player2.png", "", false);

I have also made a function to spawn the player on a random place on the board. Each tile has a unique numbered id (between 1 and 150). The random number function works fine.

below is my spawn function that i am having trouble with;

 function spawnPlayer(n, identifier) { let playerSpawn = document.getElementById(identifier); playerSpawn = playerSpawn.id; console.log(playerSpawn) if (occupied.includes(playerSpawn) == true) { spawnPlayer(n, identifier); } else { `player${n}`.setPosition(playerSpawn); console.log(("player" + `${n}`).getPosition()); playerArray.shift(); playerArray.unshift(playerSpawn.id); playerSpawn.classList.add("player"); playerSpawn.classList.add("player" + n.toString()); //console.log("player" + n); //console.log(player2.image); playerSpawn.style.setProperty( "background-image", "url(css/player" + n + ".png)" ); playerSpawn.style.setProperty("background-size", "cover"); } } spawnPlayer(1, randomise());

i am having trouble understanding how to use template literals in a way that i can re-use this function for both player 1 and 2 as arguments.

 `player${n}`.setPosition(playerSpawn);

this is the bit that's causing me problems. My current error is

Uncaught TypeError: n.setPosition is not a function at spawnPlayer

Any help would be greatly appreciated, also if anyone can recommend some material that explores JavaScript class implementation that would be very helpful

Thank You

Set player1 and player2 as properties of some object. Then you can access them dynamically:

const obj = {
  player1: new Player(...),
  player2: new Player(...),
}

// ...

obj[`player${n}`].setPosition(playerSpawn)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM