Trigger function to roll a dice - javascript

I have a function to get a random value (1->6) to roll a dice:
const rollDice = () => {
document.dispatchEvent(
new CustomEvent('rollDice', {
detail: { value: Math.floor(Math.random() * 6) + 1 },
bubbles: true,
cancelable: false
})
);
};
Get the value from rollDice() and put in the correct positions, but I don't know why it work incorrectly. The result need show as the picture:
Result
I am newbie here, Can anyone help point out where I'm going wrong?
const rollDice = () => {
document.dispatchEvent(
new CustomEvent('rollDice', {
detail: {
value: Math.floor(Math.random() * 6) + 1
},
bubbles: true,
cancelable: false
})
);
};
let btn = document.querySelector("#roll-button");
btn.addEventListener('click', function() {
var varones = toNumber(parseInt(document.querySelector("#ones p").textContent));
var vartwos = toNumber(parseInt(document.querySelector("#twos p").textContent));
var varthrees = toNumber(parseInt(document.querySelector("#threes p").textContent));
var varfours = toNumber(parseInt(document.querySelector("#fours p").textContent));
var varfives = toNumber(parseInt(document.querySelector("#fives p").textContent));
var varsixes = toNumber(parseInt(document.querySelector("#sixes p").textContent));
rollDice();
document.addEventListener('rollDice', (e) => {
alert(e.detail.value);
if (e.detail.value == 1) {
varones = varones + 1;
}
if (e.detail.value == 2) {
vartwos = vartwos + 1;
}
if (e.detail.value == 3) {
varthrees = varthrees + 1;
}
if (e.detail.value == 4) {
varfours = varfours + 1;
}
if (e.detail.value == 5) {
varfives = varfives + 1;
}
if (e.detail.value == 6) {
varsixes = varsixes + 1;
}
total = varones + vartwos + varthrees + varfours + varfives + varsixes;
document.querySelector("#ones p").textContent = varones;
document.querySelector("#twos p").textContent = vartwos;
document.querySelector("#threes p").textContent = varthrees;
document.querySelector("#fours p").textContent = varfours;
document.querySelector("#fives p").textContent = varfives;
document.querySelector("#sixes p").textContent = varsixes;
document.querySelector("#totals p span").textContent = total;
});
});
function toNumber(a) {
if (isNaN(a)) {
a = 0;
}
return a;
}
<h1>Events Triggered and Emitted</h1>
<h2>Dice Rolls</h2>
<div id="rolls">
<div id="ones">
<span class="dice">⚀</span>
<p>-</p>
</div>
<div id="twos">
<span class="dice">⚁</span>
<p>-</p>
</div>
<div id="threes">
<span class="dice">⚂</span>
<p>-</p>
</div>
<div id="fours">
<span class="dice">⚃</span>
<p>-</p>
</div>
<div id="fives">
<span class="dice">⚄</span>
<p>-</p>
</div>
<div id="sixes">
<span class="dice">⚅</span>
<p>-</p>
</div>
<div id="dice">
<button id="roll-button"><span class="dice">⚂</span></button>
</div>
<div id="totals">
<p>Total rolls: <span>0</span></p>
</div>
</div>
<!-- Template for dice roll 1 -->
<template id="template1"><span class="dice">⚀</span></template>
<!-- Template for dice roll 2 -->
<template id="template2"><span class="dice">⚁</span></template>
<!-- Template for dice roll 3 -->
<template id="template3"><span class="dice">⚂</span></template>
<!-- Template for dice roll 4 -->
<template id="template4"><span class="dice">⚃</span></template>
<!-- Template for dice roll 5 -->
<template id="template5"><span class="dice">⚄</span></template>
<!-- Template for dice roll 6 -->
<template id="template6"><span class="dice">⚅</span></template>

I don't understand all your code, but I think you should write your rollDice event listener out of you click button event listener, because in your example, the event is triggered before the document is listening to this event.
btn.addEventListener('click', () => {
// do something
rollDice()
})
document.addEventListener('rollDice', () => {
// do something
})

First of all, don't type more code than necessary inside an eventListener. If you had refactored your code into a method, you would see that you tried to create an event listener inside an event listener. Here is how an eventListener should be set up:
btn.addEventListener('click', rollDice);
I don't understand why you created an event listener inside rollDice(). Was that part of an assignment? I just called the correct method straight away.
The second part I did was to try to reduce code by looking at similarities in the code. I can use the :nth-child selector to get the proper dice container by using the randomized roll.
rollsDiv.querySelector(`div:nth-child(${roll}) > p`)
The third thing to remember, is to write as short methods as possible, by having them do at most one thing. If you can't do that, try to write methods as a table of content. A person should be able to read the code and understand what's happening just by how it's written. That means refactor complex code, like getCorrectDiceElement(), or using variables and naming them to make each row comprehensible.
These are more tips for intermediate coding, but it could be nice to know this on beforehand. Otherwise, you won't understand your own code when looking at it after a half year. :)
As a present, I added a four more lines (a, b) for functionality that I guess you would like to implement in the future. Good luck!
const rollsDiv = document.getElementById("rolls");
// const totalsDiv = document.getElementById("totals"); // a
const btn = document.getElementById("roll-button");
// var numberOfRolls = 0; // a
const randomize = (max = 6, min = 1) => {
return Math.floor(Math.random() * max) + min;
};
const rollDice = () => {
var roll = randomize();
let diceElement = getCorrectDiceElement(roll);
let previousNumber = toNumber(diceElement.textContent);
// let diceSymbol = document.getElementById("template" + roll).textContent; // b
// console.log(roll, diceElement.parentNode.id)
previousNumber++;
// numberOfRolls++; // a
diceElement.textContent = previousNumber;
}
const getCorrectDiceElement= (roll) => {
return rollsDiv.querySelector(`div:nth-child(${roll}) > p`)
}
function toNumber(a) {
return isNaN(a) ? 0 : a;
}
btn.addEventListener('click', rollDice);
#rolls {
display: flex;
margin-bottom: 1rem;
}
#rolls > div,
#roll-button
{
text-align: center;
font-size: 2rem;
padding: 0rem 1rem;
}
#rolls p {
margin: 0;
}
<h2>Dice Rolls</h2>
<div id="rolls">
<div id="ones">
<span class="dice">⚀</span>
<p>-</p>
</div>
<div id="twos">
<span class="dice">⚁</span>
<p>-</p>
</div>
<div id="threes">
<span class="dice">⚂</span>
<p>-</p>
</div>
<div id="fours">
<span class="dice">⚃</span>
<p>-</p>
</div>
<div id="fives">
<span class="dice">⚄</span>
<p>-</p>
</div>
<div id="sixes">
<span class="dice">⚅</span>
<p>-</p>
</div>
</div>
<div>
<div id="dice">
<button id="roll-button">Roll</button>
</div>
<div id="totals">
<p>Total rolls: <span>0</span></p>
</div>
</div>
<!-- Template for dice roll 1 -->
<template id="template1"><span class="dice">⚀</span></template>
<!-- Template for dice roll 2 -->
<template id="template2"><span class="dice">⚁</span></template>
<!-- Template for dice roll 3 -->
<template id="template3"><span class="dice">⚂</span></template>
<!-- Template for dice roll 4 -->
<template id="template4"><span class="dice">⚃</span></template>
<!-- Template for dice roll 5 -->
<template id="template5"><span class="dice">⚄</span></template>
<!-- Template for dice roll 6 -->
<template id="template6"><span class="dice">⚅</span></template>
[EDIT] Added back the original rollDice() method.
const rollsDiv = document.getElementById("rolls");
// const totalsDiv = document.getElementById("totals"); // a
const btn = document.getElementById("roll-button");
// var numberOfRolls = 0; // a
const randomize = (max = 6, min = 1) => {
return Math.floor(Math.random() * max) + min;
};
const rollDice = () => { // NEW
let eventName = "rollDice";
let eventDetail = {'value': randomize()};
let eventProperties = {detail: eventDetail, 'bubbles': true, 'cancelable': false};
let customEvent = new CustomEvent(eventName, eventProperties);
document.dispatchEvent(customEvent);
};
const handleDiceResult = (event) => {
var eventDetail = event.detail; // NEW
var roll = eventDetail.value;
let diceElement = getCorrectDiceElement(roll);
let previousNumber = toNumber(diceElement.textContent);
// let diceSymbol = document.getElementById("template" + roll).textContent; // b
// console.log(roll, diceElement.parentNode.id)
previousNumber++;
// numberOfRolls++; // a
diceElement.textContent = previousNumber;
}
const getCorrectDiceElement= (roll) => {
return rollsDiv.querySelector(`div:nth-child(${roll}) > p`);
}
function toNumber(a) {
return isNaN(a) ? 0 : a;
}
btn.addEventListener('click', rollDice);
document.addEventListener('rollDice', handleDiceResult); // NEW
#rolls {
display: flex;
margin-bottom: 1rem;
}
#rolls > div,
#roll-button
{
text-align: center;
font-size: 2rem;
padding: 0rem 1rem;
}
#rolls p {
margin: 0;
}
<h2>Dice Rolls</h2>
<div id="rolls">
<div id="ones">
<span class="dice">⚀</span>
<p>-</p>
</div>
<div id="twos">
<span class="dice">⚁</span>
<p>-</p>
</div>
<div id="threes">
<span class="dice">⚂</span>
<p>-</p>
</div>
<div id="fours">
<span class="dice">⚃</span>
<p>-</p>
</div>
<div id="fives">
<span class="dice">⚄</span>
<p>-</p>
</div>
<div id="sixes">
<span class="dice">⚅</span>
<p>-</p>
</div>
</div>
<div>
<div id="dice">
<button id="roll-button">Roll</button>
</div>
<div id="totals">
<p>Total rolls: <span>0</span></p>
</div>
</div>
<!-- Template for dice roll 1 -->
<template id="template1"><span class="dice">⚀</span></template>
<!-- Template for dice roll 2 -->
<template id="template2"><span class="dice">⚁</span></template>
<!-- Template for dice roll 3 -->
<template id="template3"><span class="dice">⚂</span></template>
<!-- Template for dice roll 4 -->
<template id="template4"><span class="dice">⚃</span></template>
<!-- Template for dice roll 5 -->
<template id="template5"><span class="dice">⚄</span></template>
<!-- Template for dice roll 6 -->
<template id="template6"><span class="dice">⚅</span></template>

Related

How can i use corretly Latex notation via forEach function in vanilla JS?

This question was migrated from Webmasters Stack Exchange because it can be answered on Stack Overflow.
Migrated last month.
I have array examples where i have example (ax^2 + 5x +1 = 0), example (ax^2 + 9x +9 = 0) etc.
I have following logic
const container = document.querySelector("#examples-container");
examples.forEach((ex, i) => {
const example = `
<div class="card">
<div class="example">
${ex.question}
</div>
<button type="button" class="toggle" onclick="toggle(${i})">
Toggle
</button>
<div id="result_${i}" style="display:none" class="result">${ex.answer}</div>
</div>`;
container.innerHTML += example;
});
Somehow is not working i get only string with array value and nothing else. <p>(ax^2 + 5x +1 = 0)</p> Works well
Instead of updating container.innerHTML with each example, compose first the html of all examples, and add that to the container:
const examples = [
{ question: '(ax^2 + 5x +1 = 0)', answer: '(answer for ax^2 + 5x +1 = 0)'},
{ question: '(ax^2 + 9x +9 = 0)', answer: '(answer for ax^2 + 9x +9 = 0)'},
];
function toggle(i) {
const div = document.querySelector(`#result_${i}`);
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
}
let html = '';
examples.forEach((ex, i) => {
const example = `
<div class="card">
<div class="example">
${ex.question}
</div>
<button type="button" class="toggle" onclick="toggle(${i})">
Toggle
</button>
<div id="result_${i}" style="display:none" class="result">${ex.answer}</div>
</div>`;
html += example;
});
const container = document.querySelector("#examples-container");
//console.log(html);
container.innerHTML = html;
.card {
border: solid gray 1px;
margin: 5px 0;
padding: 3px 10px;
}
<div id="examples-container"></div>

Check if true or false on json parse into html

Currently have all data displaying perfectly except the boolean ones.
I have some data that if true or false they should display different html/css
So, how can I have a class or html that shows the data if returns true?
I'm a bit stuck on parsing this data on this code. As I was on the right direction until this new request.
The Json loooks like this:
{
"name": "Serena Gosling",
"supporterNumber": "0123456789",
"isStrongRelationship": true,
"ticketingPoints" :"2,500 Ticket Points",
"thumbnailUrl": "https://i.pravatar.cc/100"
},
fetch("supporters.json")
.then(response => response.json())
.then(supporters => {
localStorage.setItem("supporters", JSON.stringify(supporters));
});
let container = document.querySelector(".content");
let loadMoreButton = document.querySelector(".content button");
let initialItems = 4;
let loadItems = 2;
function loadInitialItems() {
let supporters = JSON.parse(localStorage.getItem("supporters"));
let out = "";
let counter = 0;
for (let supporter of supporters) {
if (counter < initialItems) {
out += `
<div class="supporter">
<h4 class="supporter__name">
<span class="supporter__thumbnail"></span>
${supporter.name}
${supporter.relationship}
<span class="supporter__number">(${supporter.supporterNumber})</span>
</h4>
<span class="supporter__points">${supporter.ticketingPoints}</span>
</div>
`;
}
counter++;
}
let div = document.createElement("div");
container.insertBefore(div, loadMoreButton);
div.innerHTML = out;
}
function loadData() {
let supporters = JSON.parse(localStorage.getItem("supporters"));
let currentDisplayedItems = document.querySelectorAll(".supporter").length;
let out = "";
let counter = 0;
for (let supporter of supporters) {
if (counter >= currentDisplayedItems && counter < loadItems + currentDisplayedItems) {
out += `
<div class="supporter">
<h4 class="supporter__name">
<span class="supporter__thumbnail"></span>
${supporter.name}
${supporter.relationship}
<span class="supporter__number">(${supporter.supporterNumber})</span>
</h4>
<span class="supporter__points">${supporter.ticketingPoints}</span>
</div>
`;
}
counter++;
}
let div = document.createElement("div");
container.insertBefore(div, loadMoreButton);
div.innerHTML = out;
div.style.opacity = 0;
if (document.querySelectorAll(".supporter").length == supporters.length) {
loadMoreButton.style.display = "none";
}
fadeIn(div);
}
function fadeIn(div) {
let opacity = 0;
let interval = setInterval(function() {
if (opacity <= 1) {
opacity = opacity + 0.1;
div.style.opacity = opacity;
} else {
clearInterval(interval);
}
}, 30);
}
loadInitialItems()
<div class="content">
<!-- content displaye from the javascript file -->
<button onclick="loadData()" class="load-more-button"><span>❭</span> </button>
</div>
You can use a ternary expression in the template literal.
out += `
<div class="supporter">
<h4 class="supporter__name">
<span class="supporter__thumbnail"></span>
${supporter.name}
${supporter.relationship}
<span class="supporter__number">(${supporter.supporterNumber})</span>
</h4>
<span class="supporter__points">${supporter.ticketingPoints}</span>
<span class="supporter__relationship">${supporter.isStrongRelationship ? "Strong" : "Weak"} relationship</span>
</div>
`;

Spread object values into input boxes

I'm trying to write a javascript quiz app. Atm I'm stuck with putting a possible answer into one of the four boxes. So just to make sure you're understanding what I'm trying to become: I fetch questions from an API. The answers are collected in an object and I want to take the answers and put them randomly in my 4 option boxes. I've tried some things but at this moment I have no clue what's going on... Here's my code:
<body>
<div id="questioncontainer" class="main-container">
<div id="progression"><div id="progressfull"></div></div>
<div id="header">
<h2 id="vraagnummer">Vraag #</h2>
<div><h2 id="timer"></h2></div>
</div>
<h2 id="vraaginput">In welke film wordt er kritiek geuit op de socio-economische situatie in Tsjechië in de late jaren 70?</h2>
<div id="antwoordcontainer">
<li id="Qst1"><p class="choice-text" data-number="1">Choice 1</p></li>
<li id="Qst2"><p class="choice-text" data-number="2">Choice 2</p></li>
<li id="Qst3"><p class="choice-text" data-number="3">Choice 3</p></li>
<li id="Qst4"><p class="choice-text" data-number="4">Choice 4</p></li>
<li id="Qst5"><p class="choice-text" data-number="5">Choice 5</p></li>
<li id="Qst6"><p class="choice-text" data-number="6">Choice 6</p></li>
</div>
<button id="Quitgame">Ik stop ermee ze</button>
</div>
</body>
This is less code and has the most important stuff in it.
fetch(myUrl)
.then((res) => {
return res.json();
})
.then((loadedQuestions) => {
for (let i = 0; i < MAX_VRAGEN; i++) {
vragen = loadedQuestions;
vragenTeller++;
mijnVraag.innerHTML = vragen[i].question;
console.log(vragen[i]);
choices.forEach((choice) => {
choice.innerHTML = vragen[i].answers.object;
});
};
startGame();
})
.catch(err => {
console.error(err);
});
Here is a working example. I decided it was better to create the options in HTML, rather than hard code seven answers and hide the ones that doesn't contain a selectable answer. This made the code slightly longer, but more dynamic.
The problem is that the answers came in form of an object, so I needed to use Object.keys(question.answers) so I had a max value to randomize. Then I just randomized a position, and cut that position out while adding answers in a while loop.
I hope the code is self-explanatory. I tried to refactor the code as much as I could.
Oh, and I just preload one question at the time, instead of fetching fifteen like in your original code.
const quizURL = 'https://quizapi.io/api/v1/questions?apiKey=kAFKilHLeEcfLkGE2H0Ia9uTIp1rYHDTIYIHs9qf&limit=1';
var progression = 0;
var questionObj = {};
const questionEl = document.getElementById('vraaginput');
const answerContainerEl = document.getElementById('antwoordcontainer');
const currentQuestionEl = document.getElementById('vraagnummer');
document.getElementById('startGame').addEventListener('click', startGame);
document.getElementById('nextQuestion').addEventListener('click', nextQuestion);
function fetchQuestion() {
fetch(quizURL)
.then((res) => {
return res.json();
})
.then((loadedQuestions) => {
questionObj = loadedQuestions.pop();
})
.catch(err => {
console.error(err);
});
}
function startGame() {
document.getElementById('startGame').setAttribute('hidden', true);
document.getElementById('questionContainer').removeAttribute('hidden');
nextQuestion();
}
function nextQuestion() {
displayQuestion(questionObj);
fetchQuestion();
}
function displayQuestion(question) {
progression++;
currentQuestionEl.innerHTML = `Vraag #${progression}`;
questionEl.innerText = question.question;
randomizeAnswerOptions(question.answers, question.correct_answers);
}
// Here is the randomization for the options.
// I created the radio buttons in javascript.
function randomizeAnswerOptions(options, answers) {
const divContainer = document.createElement('div');
var randomIndex, answerText = '', answerIndex = 0, isExistingAnswer = false, isCorrectAnswer = false;
var optionsKeys = Object.keys(options);
while(optionsKeys.length) {
randomIndex = randomize(optionsKeys.length);
randomIndex = optionsKeys.splice(randomIndex, 1)[0];
answerText = options[randomIndex];
isExistingAnswer = answerText != null;
if (isExistingAnswer) {
isCorrectAnswer = answers[randomIndex + '_correct']
answerIndex++;
divContainer.appendChild(createAnswerRow(answerText, isCorrectAnswer, 'answerInput' + answerIndex));
}
}
answerContainerEl.innerHTML = '';
answerContainerEl.appendChild(divContainer);
}
function createAnswerRow(answerText, isCorrectAnswer, inputId) {
let answerRow = document.createElement('div');
let bullet = document.createElement('input');
let label = document.createElement('label');
bullet.setAttribute('type', 'radio');
bullet.setAttribute('name', 'answer');
bullet.setAttribute('id', inputId);
bullet.setAttribute('data-answer', isCorrectAnswer);
label.setAttribute('for', inputId);
label.innerText = answerText;
answerRow.appendChild(bullet);
answerRow.appendChild(label);
return answerRow;
}
function randomize(max, min) {
return Math.floor(Math.random() * max + (min || 0));
}
fetchQuestion();
#antwoordcontainer > div > div {
margin: 0.25rem;
}
label, input[type="radio"] {
cursor: pointer;
}
label {
padding: 0.25rem;
}
input[type="radio"]:checked ~ label {
background: pink;
}
input[type="radio"][data-answer="true"]:checked ~ label {
background: lightgreen;
}
<button id="startGame">Start Game</button>
<div id="questionContainer" class="main-container" hidden>
<div id="progression">
<div id="progressfull"></div>
</div>
<div id="header">
<h2 id="vraagnummer">Vraag #</h2>
<div>
<h2 id="timer"></h2>
</div>
</div>
<h2 id="vraaginput"></h2>
<div id="antwoordcontainer"><!--ANSWERS--></div>
<button id="nextQuestion">Next Question</button>
<!--<button id="Quitgame">Ik stop ermee ze</button>-->
</div>

Javascript: Don't sum elements that are not visible

I'm trying to sum a list of values from HTML elements, but I want to EXCLUDE values are that hidden using pure JS.
HTML:
<div class="grams">1</div>
<div style="display: none;">
<div class="grams">2</div>
</div>
<div class="milligrams">100</div>
<div class="milligrams">2</div>
<br>
<div>Total:</div>
<div class="servings"></div>
JS:
window.addEventListener('load', function() {
let gramdivs = document.getElementsByClassName("grams");
let milligramdivs = document.getElementsByClassName("milligrams");
var total = 0;
for (let item of gramdivs) {
let itemPrice=parseFloat(item.textContent);
total += itemPrice;
}
for (let item of milligramdivs) {
let itemPrice=parseFloat(item.textContent);
total = total + itemPrice / 1000;
}
document.getElementsByClassName("servings")[0].innerText = total.toFixed(3);
})
https://jsfiddle.net/smhok7yd/2/
In the JS Fiddle, you can see that all the numbers are being added, including the hidden one.
The correct output should be 1.102.
Please note that I cannot change the hierarchy of the HTML.
I am relatively new to JS and have been trying to find a solution all day.
When iterating over elements, check to see if their offsetParent is null - if so, they're not visible:
const getClassValues = (className, multiplier = 1) => [...document.getElementsByClassName(className)]
.filter(elm => elm.offsetParent !== null)
.reduce((a, b) => a + (b.textContent * multiplier), 0);
document.querySelector('.servings').textContent = (
getClassValues('grams') + getClassValues('milligrams', 0.001)
);
<div class="grams">1</div>
<div style="display: none;">
<div class="grams">2</div>
</div>
<div class="milligrams">100</div>
<div class="milligrams">2</div>
<br>
<div>Total:</div>
<div class="servings"></div>
If you set display: none; on the specific grams div you can check for the property before adding it to the total:
https://jsfiddle.net/et6wzph2/28/
function isVisible(e) {
return !!( e.offsetWidth || e.offsetHeight || e.getClientRects().length );
}
window.addEventListener('load', function() {
let gramdivs = document.getElementsByClassName("grams");
let milligramdivs = document.getElementsByClassName("milligrams");
let total = 0;
for (let item of gramdivs) {
if(!isVisible(item)) continue;
let itemPrice = parseFloat(item.textContent);
total += itemPrice;
}
for (let item of milligramdivs) {
if(!isVisible(item)) continue;
let itemPrice = parseFloat(item.textContent);
total = total + itemPrice / 1000;
}
document.getElementsByClassName("servings")[0].innerText = total.toFixed(3);
})
<div class="grams">1</div>
<div style="display: none;">
<div class="grams">2</div>
</div>
<div class="milligrams">100</div>
<div class="milligrams">2</div>
<br>
<div>Total:</div>
<div class="servings"></div>

javascript adding new buildings

I'm not sure how to add a new building by array. I'm a beginner javascript person.
I added saving/loading among other things to the back end but the client side is giving me issues for some reason.
I think it has something to do with me not under standing arrays correctly but if you could point me in the right direction i would love to learn.
I want to add a second building called
loadbuilding("taco stand")
Here is the code:
var Timer = window.setInterval(function() {
Tick()
}, 1000);
var buildings = [];
//The object declaration for game saves
function GameSave() {
this.money = 0;
this.buildings = [];
for (var i = 0; i < buildings.length; i++) {
this.buildings[i] = 0;
}
}
//The object declaration for buildings
function Building() {
this.Name = "Lemonade Stand";
this.Cost = 10;
this.PerSec = 1;
}
//The function to initialise all buildings
function InitBuildings() {
LoadBuilding("Lemonade Stand", 10, 1);
LoadBuilding("Taco Stand", 100, 1);
}
//The function to automatically load a building into the buildings array
function LoadBuilding(name, cost, persec) {
var cur = buildings.length;
buildings[cur] = new Building();
buildings[cur].Name = name;
buildings[cur].Cost = cost;
buildings[cur].PerSec = persec;
}
//The function used to gather money
function GatherMoney() {
game.money++; //++ tells javascript to add 1 to the variable
//Display the player's current money
document.getElementById("money").innerHTML = game.money;
}
//The function that gets run every second
function Tick() {
for (var i = 0; i < buildings.length; i++) {
game.money += game.buildings[i] * buildings[i].PerSec;
}
document.getElementById("money").innerHTML = game.money;
}
//The function to buy a lemonade stand
function Build(id) {
if (game.money >= buildings[id].Cost) { //Check if the player has enough money, then subtract it and add a new building if they do
game.money -= buildings[id].Cost;
game.buildings[id] = game.buildings[id] + 1;
document.getElementById("money").innerHTML = game.money;
document.getElementById("Building1Qty").innerHTML = game.buildings[id];
}
}
//Run this code once the page has loaded fully
window.onload = function() {
InitBuildings();
window.game = new GameSave();
};
<!--Pleae refer to Lesson 9.txt for a full description on this lesson -->
<html>
<head>
<title>Basic Incremental Game</title>
<link rel="stylesheet" type="text/css" href="css/Incremental.css">
<script src="js/Incremental.js"></script>
</head>
<body>
<div id="page">
<div id="header">
<div id="game-title">
Basic Incremental Game
</div>
</div>
<div id="content">
<div id="stats" class="block">
<div class="label">Money:</div>
<div id="money" class="label">0</div>
</div>
<div id="clickables" class="block">
<input type="button" value="Click Me!" onclick="GatherMoney();">
</div>
<div id="buildings" class="block">
<div id="Building1">
<input type="button" value="Lemonade Stand" onclick="Build(0);">
<div>
<div class="label">Cost:</div>
<div id="Building1Cost" class="label">10</div>
</div>
<div>
<div class="label">Per Sec:</div>
<div id="Building1PerSec" class="label">1</div>
</div>
<div>
<div class="label">Quantity:</div>
<div id="Building1Qty" class="label">0</div>
</div>
</div>
<div id="Building2">
<input type="button" value="Taco Stand" onclick="Build(1);">
<div>
<div class="label">Cost:</div>
<div id="Building2Cost" class="label">10</div>
</div>
<div>
<div class="label">Per Sec:</div>
<div id="Building2PerSec" class="label">1</div>
</div>
<div>
<div class="label">Quantity:</div>
<div id="Building2Qty" class="label">0</div>
</div>
</div>
</div>
<div id="upgrades" class="block">
This is where our upgrades will go!
</div>
</div>
</body>
EDIT:
i tried changing the but tit didnt work
buildings[]
to
buildings["Lemonade Stand", "Taco Stand"]
How about,
LoadBuilding("myBuilding", 12, 1);
Because you have this factory function,
function LoadBuilding(name, cost, persec) {
var cur = buildings.length;
buildings[cur] = new Building();
buildings[cur].Name = name;
buildings[cur].Cost = cost;
buildings[cur].PerSec = persec;
}
You could build an array of Building objects then iterate through them using a while loop.
See JSFIDDLE, or attached code.
Let me know if that helps.
class Building {
constructor(name, cost, persec) {
this.name = name;
this.cost = cost;
this.persec = persec;
}
}
var buildings = [];
buildings.push(new Building('Building One', '$10', '1'));
buildings.push(new Building('Building Two', '$20', '0.5'));
buildings.push(new Building('Building Three', '$25', '2'));
var count = 0;
while(count < buildings.length) {
document.getElementById('stores').innerHTML += '<p>' + buildings[count].name + '<br />' + buildings[count].cost + '<br />' + buildings[count].persec + '</p>';
count++;
}
<div id="stores">
</div>

Categories