scrimba
Build an RPG
Build a role-playing game part 2 - Constructor functions
Export 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

Export Character constructor
AboutCommentsNotes
Export Character constructor
Expand for more info
index.js
run
preview
console
import characterData from '/data.js'
import {getDiceRollArray} from '/utils.js'

/*
Challenge
1. Create a file called 'Character.js'
2. Cut and paste the constructor function into it.
3. Decide if this should be a default or named export. Think
about this!!
4. Import it into index.js
5. You will hit a problem! Solve the problem!
*/

function Character(data) {
Object.assign(this, data)

this.getDiceHtml = function(diceCount) {
return getDiceRollArray(diceCount).map(function(num){
return `<div class="dice">${num}</div>`
}).join('')
}

this.getCharacterHtml = function () {
const { elementId, name, avatar, health, diceCount } = this;
let diceHtml = this.getDiceHtml(diceCount);

return `
<div class="character-card">
<h4 class="name"> ${name} </h4>
<img class="avatar" src="${avatar}" />
<div class="health">health: <b> ${health} </b></div>
<div class="dice-container">
${diceHtml}
</div>
</div>`;
}
}

function render() {
document.getElementById(wizard.elementId).innerHTML = wizard.getCharacterHtml();
document.getElementById(orc.elementId).innerHTML = orc.getCharacterHtml();
}

const wizard = new Character(characterData.hero)
const orc = new Character(characterData.monster)
render()
Console
/index.html
-3:30