'Trying to splice an array one by one randomly until empty
This is a javascript for a scratch card game. So far I want to make it to have one user can only scratch the game once. There are 3 var for example so it will be like after 3 user scratch it, the array should be empty and the alert function will call out. Now I can only use loop to empty the array and I can't figure out how to make it splice one by one per attempt.
var promoCode = '';
var bg1 = 'https://cdn.pixabay.com/photo/2020/06/01/22/23/eye-5248678__340.jpg';
var bg2 = 'http://farm5.static.flickr.com/4017/4717107886_dcc1270a65_b.jpg';
var bg3 = 'http://images6.fanpop.com/image/photos/41500000/adorable-puppies-cute-puppies-41538743-590-393.jpg';
var bgArr = [bg1, bg2, bg3];
for(var i=0; i <1; i++){
selectBG = bgArr.splice(Math.floor(Math.random() * bgArr.length), 1)[0];
console.log(selectBG);
}
if (selectBG === bg1) {
promoCode = 'SCRATCH400';
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
} else if (selectBG === bg2) {
promoCode = 'SCRATCH500';
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
} else if (selectBG === bg3) {
promoCode = 'SCRATCH600';
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
} else if (bgArr.length === 0) {
alert("No more voucher");
}
$('#promo').wScratchPad({
// the size of the eraser
size: 70,
// the randomized scratch image
bg: selectBG,
// give real-time updates
realtime: true,
// The overlay image
fg: 'https://cdn.glitch.com/2c225b7b-6134-4f2b-9842-1d5d060d9cd4%2Foverlay.png',
// The cursor (coin) image
'cursor': 'url("https://cdn.glitch.com/2c225b7b-6134-4f2b-9842-1d5d060d9cd4%2Fcoin1.png") 30 30, default',
scratchMove: function(e, percent) {
console.log(percent);
console.log(promoCode);
// Show the plain-text promo code and call-to-action when the scratch area is 50% scratched
if ((percent > 50) && (promoCode != '')) {
$('.promo-container').show();
$('body').removeClass('not-selectable');
$('.promo-code').html('Your code is: ' + promoCode);
}
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
