Find remaining indexes and storing them as values

Tags: , , ,



I’m making a small game. You have to find the ball under a randomized cup.

First the images are stored in a nodeList. Then the winning cup is calculated randomly from the length of the nodeList.

My problem: After the random value for winningCup has been calculated I don’t know how to find the other two indexes from the ‘images’ nodeList. How can I calculate for two values that AREN’T the randomized winningCup’s value?

My thought was to issue some kind of check, but I’m not sure what to check for. My goal for this is to have the two remaining cups switch to another ‘.png ‘ revealing empty cups.

enter image description here

window.onload = function() {
    getImages();
}

function getImages() {
    var images = document.getElementsByTagName('img');
    var winningCup = Math.floor(Math.random() * images.length);
 
    var empty1 = Math.floor(Math.random() * images.length);
    var empty2 = Math.floor(Math.random() * images.length);

    if(empty1 || empty2 === winningCup){


    }

    for(var i = 0; i < images.length; i++) {
        images[winningCup].onclick = winCup;
     
    }
    console.log(empty1);
    console.log(empty2)
    console.log(winningCup)
}

function winCup(eventObj){
    var cup = eventObj.target;
    var name = cup.id;
    name = name + 'ball.png';
    cup.src = name; 

    //adds photo of winning cup
}

function losingCups(eventObj){
    var cups = eventObj.target;
    var name = cups.id;
    name = name + 'up.png';
    cups.src = name

    //adds photo of losing cups


}

Answer

You only need a random winning cup. All others are losing, not random.

function getImages() {
    var images = document.getElementsByTagName("img");
    var winningCup = Math.floor(Math.random() * images.length);
    for (var i = 0; i < images.length; ++i)
        images[i].onclick = i == winningCup ? winCup : losingCups;
}


Source: stackoverflow