My goal is to make a simple card game. I have this bug where sometimes it doesnt push one of the objects into the array. First I thought that the picked number wouldn't fit between the if statements to declare the values of the objects. I have tried to redefining the pickedNumber manually right after it got the random value. Then it worked. The numbers that I have problems with are: 36, 38, 24, 25, 37 when it was random, but when i defined the var pickedNumber manually it worked as it should. Any hints on how to fix this? Thanks a lot in advance.
picture of when the code fails
function log(txt) {
console.log(txt);
}
let cards = [];
let hand = [];
// fill card deck
for (let i = 1; i < 53; i++) {
cards.push(i);
}
// index for to make the random math not to choose a number over the highest index of cards[]
// loop for picking some random card with a value
for (let i = 0; i < 3; i++) {
// random index to choose
let randomNumber = Math.floor(Math.random() * cards.length);
log(randomNumber);
// random number
let pickedNumber = cards[randomNumber];
log(pickedNumber);
// remove the picked card
const index = cards.indexOf(pickedNumber);
if (index > -1) {
cards.splice(index, 1);
}
let finalValue;
let card = {
value: finalValue,
suit: "",
};
// these if statements are for deviding the cards from 52 to 4x13
if (pickedNumber < 14) {
card.value = pickedNumber;
card.suit = "♥";
hand.push(card);
} else if (pickedNumber > 13 && pickedNumber < 26) {
card.value = pickedNumber -= 13;
card.suit = "♣";
hand.push(card);
} else if (pickedNumber > 26 && pickedNumber < 39) {
card.value = pickedNumber -= 26;
card.suit = "♦";
hand.push(card);
} else if (pickedNumber > 39 && pickedNumber < 53) {
card.value = pickedNumber -= 39;
card.suit = "♠";
hand.push(card);
}
// reduce maxIndex to dont overpick index
}
log(hand);
Aucun commentaire:
Enregistrer un commentaire