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

Use a constructor function 1
AboutCommentsNotes
Use a constructor function 1
Expand for more info
index.js
run
preview
console
function getDiceRollArray(diceCount) { 
return new Array(diceCount).fill(0).map(function(){
return Math.floor(Math.random() * 6) + 1
});
}

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

const hero = {
elementId: "hero",
name: "Wizard",
avatar: "images/wizard.png",
health: 60,
diceCount: 3
}

const monster = {
elementId: "monster",
name: "Orc",
avatar: "images/orc.png",
health: 10,
diceCount: 1
}
/*
Challenge
1. Create a new constructor function called Character which
takes our data as a paramenter.
2. Set up "this" for each of the 5 properties in our objects
(eg: this.health = data.health).
*/


function renderCharacter(data) {
const { elementId, name, avatar, health, diceCount } = data;
const diceHtml = getDiceHtml(diceCount)

document.getElementById(elementId).innerHTML =
`<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>`;
}

renderCharacter(hero);
renderCharacter(monster);
Console
/index.html
-1:57