scrimba
Create an RPG game - Rob Sutcliffe
Separate character constructor
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Separate character constructor
by
AboutCommentsNotes
Separate character constructor
by
Expand for more info
index.js
run
preview
console
// 1. Seperate Character into a seperate file 
// and move the import from utils to the new file too
// 2. Import character at the top of this file
import characterData from "./data";
import { getDiceRollArray, sumArray } from "./utils";

function Character(data) {

Object.assign(this, data);

this.currentDiceRole = [];

this.rollDice = function() {
this.currentDiceRole = getDiceRollArray(this.diceCount);
return sumArray(this.currentDiceRole);
};

this.takeDamage =function(damage) {
this.health -= damage;
};

this.getDiceElementArray = function() {
return this.currentDiceRole.map((num) => `<div class="dice">${num}</div>`);
};

this.getTemplate = function() {
const { name, emoji, health } = this;
const diceElementArray = this.getDiceElementArray();

return `<div class="character">
<div class="name">${name}</div>
<div class="emoji">️${emoji}</div>
<div class="health">health: <b>${health}</b></div>
<div class="dice-container">
${diceElementArray.join("")}
</div>
</div>`;
}

};

function render() {
document.getElementById(hero.elementId).innerHTML = hero.getTemplate();
document.getElementById(monster.elementId).innerHTML = monster.getTemplate();
}

const hero = new Character(characterData.hero);
const monster = new Character(characterData.monster);

render();


document.getElementById("attack-button").onclick = function() {

const heroAttackScore = hero.rollDice();
const monsterAttackScore = monster.rollDice();

hero.takeDamage(monsterAttackScore);
monster.takeDamage(heroAttackScore);

render();
}
Console
/index.html
-2:36