for a gaming app, a player can select card types for his/her deck (first eachfor) and amount of each card type (2nd each.for). After this, I want to push this selection in an array.
Following part of my code works well:
//defining card types
let availableRoles = ["werwolf", "dorfbewohner", "seherin", "hexe", "jaeger", "armor", "heiler", "prinz"]
let gameState = {
roles: {}
}
//set card amount 0
;(() => {
availableRoles.forEach(role => gameState.roles[role] = 0)
})()
//adding & subtracting roles
const addRole = role => {
gameState.roles[role]++
document.getElementById(role + "_btn_remove").disabled = false;
document.getElementById(role + '_cnt').innerHTML = gameState.roles[role];
document.getElementById('total_cnt').innerHTML = totalNumberOfRolesInGame();
}
const removeRole = role => {
gameState.roles[role]--
if (gameState.roles[role] <= 0) {
gameState.roles[role] = 0
document.getElementById(role + "_btn_remove").disabled = true;
}
document.getElementById(role + '_cnt').innerHTML = gameState.roles[role];
document.getElementById('total_cnt').innerHTML = totalNumberOfRolesInGame();
}
const totalNumberOfRolesInGame = () => Object.values(gameState.roles).reduce((a,c) => a + c)
Now I want to hit every role and hit every number insider the role by using for each command. But it does not work.
var rollen = []
function Holmir() {
;(() => {
gameState.roles.forEach(element => element.forEach (myRole => rollen.push(myRole))
) })()
{
I'm thankful for any help!
forEach works with an array.
gameState = {
roles: {}
}
gameState.roles gives you an object so forEach won't work with this
Related
The following code is used to generate NFTs by combining layers which are located inside folders.
What if I wanted to use the entire collection of folders provided in props.folderNames but also force the program that if among the folders provided there were more than one folder with the similar first word (for example "Face Old" and "Face New") it only use one of these folders for the generation process randomly and not both of the at once.
For example the the first artwork is generated by combining the layers inside the "Face Old" and "Hats New" folder and the second artwork is generated by combining the layers inside the "Face new" and "Hats futuristic" folder etc.
const constructLayerToDna = (_dna = "", _layers = []) => {
let mappedDnaToLayers = _layers.map((layer, index) => {
let selectedElement = layer.elements.find(
(e) => e.id == cleanDna(_dna.split("-")[index])
);
return {
name: layer.name,
selectedElement: selectedElement,
};
});
return mappedDnaToLayers;
};
const startCreating = async () => {
props.setProgress(0);
let editionCount = 1;
let failedCount = 0;
while (editionCount <= props.config.supply) {
let newDna = createDna(props.folderNames);
if (isDnaUnique(dnaList, newDna)) {
let results = constructLayerToDna(newDna, props.folderNames);
let loadedElements = [];
results.forEach((layer) => {
loadedElements.push(loadLayerImg(layer));
});
await Promise.all(loadedElements).then((renderObjectArray) => {
ctx.clearRect(0, 0, props.config.width, props.config.height);
renderObjectArray.forEach((renderObject, index) => {
drawElement(renderObject, index);
});
saveImage(editionCount);
addMetadata(newDna, editionCount);
saveMetaDataSingleFile(editionCount);
console.log(`Created edition: ${editionCount}`);
});
dnaList.add(filterDNAOptions(newDna));
editionCount++;
props.setProgress(editionCount - 1);
} else {
console.log("DNA exists!");
failedCount++;
if (failedCount >= 1000) {
console.log(
`You need more layers or elements to grow your edition to ${props.config.supply} artworks!`
);
process.exit();
}
}
}
writeMetaData(JSON.stringify(metadataList, null, 2));
};
I tried adding the following code:
const folderGroups = props.folderNames.reduce((groupedFolders, folder) => {
const folderName = folder.toString().split(" ")[0];
groupedFolders[folderName] = groupedFolders[folderName] || [];
groupedFolders[folderName].push(folder);
return groupedFolders;
}, {});
const selectedFolders = Object.values(folderGroups).map((folderGroup) => {
const randomIndex = Math.floor(Math.random() * folderGroup.length);
return folderGroup[randomIndex];
});
and also changed the startCreating function to this:
const startCreating = async () => {
props.setProgress(0);
let editionCount = 1;
let failedCount = 0;
while (editionCount <= props.config.supply) {
let newDna = createDna(selectedFolders);
if (isDnaUnique(dnaList, newDna)) {
let results = constructLayerToDna(newDna, selectedFolders);
// rest of the code
However, this didn't work and resulted in the program to only use one of the folders provided to it out of the entire collection of folders.
Everything is working fine in below code. But when I want to put a greater quantity than exiting quantity in a specific products, It returns me negative value. Where to write the code to return the following two reuslts?
(1). I want to put value up to 0.
(2). If It goes below 0, alert with "No product in Store".
const inputValue = id => {
const input = document.getElementById(id);
const inputValue = input.value;
input.value = '';
return inputValue;
}
const addProduct = () => {
const productName = inputValue('product-name');
const productQnt = inputValue('product-quantity');
// console.log(productName, productQnt);
// check typeof input value
// console.log(typeof productName, typeof productQnt)
// check input type
const number = Number(productQnt);
if (!isNaN(productName || !Number.isInteger(number))) {
alert('nai');
return;
}
// console.log(Number.isInteger(number));
setProductInLocalStorage(productName, productQnt);
// showdata on table at console
// getLocalStorageData();
displayProduct();
}
// get items
const getLocalStorageData = () => {
const products = localStorage.getItem('All-Products');
const parseProducts = JSON.parse(products);
return parseProducts;
}
// set items
const setProductInLocalStorage = (productName, productQnt) => {
let products = getLocalStorageData();
if (!products) {
products = {};
}
// add updated quantities
if (products[productName]) {
products[productName] = parseInt(products[productName]) + parseInt(productQnt)
} else {
products[productName] = productQnt;
}
localStorage.setItem('All-Products', JSON.stringify(products));
};
// display product on UI
const displayProduct = () => {
const allProducts = getLocalStorageData();
const section = document.getElementById('all-products');
section.textContent = '';
for (const product in allProducts) {
const name = product;
const quantity = allProducts[product]
const div = document.createElement('div');
div.innerHTML = `
<div class="shadow-sm p-3 mb-2 bg-body rounded">
<span class="fs-4">${name}</span>
Quantity:<small class="fw-bold">
${quantity}
</small>
</div>
`;
section.appendChild(div);
}
}
// call display products to display on UI
displayProduct();
My take on this one:
Use a function to get quantity from your object:
function getSafeQuantity(quantity) {
const safeQuantity = Number(quantity) < 0 ? 0 : Number(quantity);
if (!safeQuantity) {
alert("No product in store");
}
return safeQuantity;
}
...
const quantity = getSafeQuantity(allProducts[product]);
...
Code written below is maybe helpful. And i thought your way of checking productQnt whether is a Integer seems doesn't work, therefore i show you one valid way meanwhile. Hope it shall be useful to you.
// check input type
const number = Number(productQnt);
if(!productName || !Number.isInteger(number)){
alert('nai');
return;
}
if (number < 0) {
alert ("No product in Store");
return;
}
I am building a multiplayer quiz game, The code below gives one point on the correct answer and minus one on the wrong.
But I want it like this: if a player answer first it gets 2 points, 2nd player gets 1 point, and the wrong answer 0 points for the same question.
function enableAnswering() {
// Enable clicking of answers buttons
document.querySelectorAll("#answers .optionblock").forEach((answer) => {
answer.onclick = (e) => {
const answerButton = answer;
const playerAnswer = answer.dataset.answer;
const playerNumber = Number(answerButton.dataset.player);
const correctAnswer = options[thiskey];
if (playerAnswer.toLowerCase() == correctAnswer.toLowerCase()) {
answerButton.classList.add("correctAnswer");
scores[playerNumber] += 2;
var plusAudio = new Audio("../audio/correct.mp3");
plusAudio.play();
clearQuestionTimerManually();
setTimeout(() => {
loadNextQuestionInHTML();
}, 2000);
}
else {
answerButton.classList.add("wrongAnswer");
scores[playerNumber]--;
// answerButton.attr('disable','disable');
var minusAudio = new Audio("../audio/Wrong.mp3");
minusAudio.play();
}
finishGameAndShowResults();
answer.onclick = () => {};
};
});
}
So basically im working on a cron job in my app that fires every 3 hours and updating users 'score' by calling the RiotApi
basically the function so far
exports.updatePlayersPoints = async () => {
console.log('STARTED UPDATING');
try {
const players = await UserLadder.findAll();
await Promise.all(
players.map(async (player) => {
const p = await RiotAccount.findOne({
where: {
userId: player.userId,
},
include: RiotRegions,
});
const beginTime = new Date(player.dataValues.createdAt);
let data;
try {
const res = await axios.get(
`https://${
p.dataValues.riot_region.dataValues.name
}.api.riotgames.com/lol/match/v4/matchlists/by-account/${
p.dataValues.accountId
}?queue=420&beginTime=${beginTime.getTime()}&api_key=${
process.env.RIOT_KEY
}`
);
data = res.data;
} catch (error) {
if (!error.response.status === 404) {
console.error(error);
}
}
if (!data) {
return;
}
let totalScore = player.dataValues.userPoints;
await Promise.all(
data.matches.map(async (match, i) => {
if (i < 15) {
const { data } = await axios.get(
`https://${p.dataValues.riot_region.dataValues.name}.api.riotgames.com/lol/match/v4/matches/${match.gameId}?api_key=${process.env.RIOT_KEY}`
);
const calculateScore = () => {
return new Promise((resolve) => {
const { stats } = _.find(
data.participants,
(o) => o.championId === match.champion
);
const killsPts = stats.kills * 2;
const deathPts = stats.deaths * -1.5;
const assistsPts = stats.assists;
const wardsPts = stats.wardsPlaced / 4;
const firstBloodPts = stats.firstBloodKill ? 3 : 0;
const firstBloodAssistPts = stats.firstBloodAssist ? 3 : 0;
const firstTowerPts = stats.firstTowerKill ? 2 : 0;
const firstTowerAssistPts = stats.firstTowerAssist ? 2 : 0;
const score =
killsPts +
deathPts +
assistsPts +
wardsPts +
firstBloodPts +
firstBloodAssistPts +
firstTowerPts +
firstTowerAssistPts;
totalScore += score;
resolve();
});
};
await calculateScore();
}
})
);
const user = await UserLadder.findOne({
where: {
userId: player.userId,
},
});
user.userPoints = parseFloat(totalScore);
user.lastGameId = data.matches[0].gameId;
await user.save();
})
);
console.log('FINISHED UPDATING');
} catch (error) {
console.error(error);
}
};
Basically it just looks up the table userladder to find the players that are signed to the ladder and for each one of these players it fires a map function that makes a request to the riotapi to get the match history of this player and then later make an inside map function to map each one of these matches.
but basically I updated it to now keep track of the game id of the last call before 3 hours so it doesn't have to make request that was already done.
user.lastGameId = data.matches[0].gameId;
but now in my second map function that maps the matches I wasn't it so that if the last game from my database matches the game id that currently being mapped I want to stop the map function and not continue this record or the ones after because it also means they all have been already counted.
but I can not seem to find a way to do it.
i tried using break; but it didn't work
any ideas?
using for loop
I tried a small test with for loop so I tried
for (let i = 0; i < 15; i++) {
await new Promise(async (resolve, reject) => {
const match = data.matches[i];
console.log(match);
resolve();
if (i === 1) {
break;
}
});
}
but I still go the same error
SyntaxError: Illegal break statement
Instead of trying to "break" a map, you should filter the matches that you want to process before you execute the map.
Something like this:
await Promise.all(
const filteredMatches = data.matches.filter(match => match.gameId > previousId);
filteredMatches.map(async (match, i) => { ...
More on filter() in javascript.
Edit: If generated id's are random and are not ordered, you can store all previous id's in a Set, and then just ask if it has been previously added
await Promise.all(
const filteredMatches = data.matches.filter(match => mySet.has(match.gameId));
filteredMatches.map(async (match, i) => { ...
More on Set in javascript.
There is a page with two images where you can vote to one of the pictures.
After the voting two new images is loading randomly and so on. The votes should be
incremented and saved to the server, but here comes the problem that I can not put the incremented
number, because I get an array: [{"votes":2},null]
I'd like to increment, save, and load the two new images with one onClick event.
Here it is what I tried to do:
handelVote(id) {
this.setState(
prevState => ({ //I get an array
voteNr: prevState.castles.map(c =>
c.id === id ? { votes: c.votes + 1 } : console.log(this.state.voteNr)
)
})
this.getCastles(),
axios
.put("............." + id, {
vote: this.state.voteNr
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
})
);
}
here I'm getting the data from the server and load only two pictures and the belonging two votes:
componentDidMount() {
if (this.state.castles.length === 0) this.getCastles();
}
async getCastles() {
let castles = [];
let voteNr = [];
let i = [];
for (i = 0; i < 1; i++) {
const f = z(4); //random nr from Choise.js
const uniqueSet = new Set(f); //to avoid duplicates
const b = [...uniqueSet];
if (b.length < 2) {
b.shift();
b.push(1, 2); //in case of duplicates load the first two images
}
let res = await axios.get(".....");
let { data } = res;
let castle = data;
this.setState({ castles: castle });
for (i = 0; i < 2; i++) {
//load only two
var t;
t = b[i];
let name = castle[t].name;
let id = castle[t]._id;
let image = castle[t].image;
let votes = castle[t].vote;
castles.push({ image, name, id, votes });
voteNr.push({votes});
}
}
this.setState(prevState => ({
loading: false,
castles: [...castles]
}));
}
and after this comes the already qouted onClick event what makes the problems.