skip to Main Content

JS:

function computerRandom(){
var compImgs = ["rock1Computer.png", "paper1Computer.png", "scissors1Computer.png"];
var compRps =  Math.floor(Math.random() * compImgs);

const showComp = document.canvas.src = compImgs[compRps];
var showImg = compImgs[showComp];
};

HTML:

<div class="playerBtn">
    <button type="button" onclick="showPRock()" onclick="computerRandom()"  id="rockBtn">Rock</button>
    <button type="button" onclick="showPPaper()" onclick="computerRandom()" id="paperBtn">Paper</button>
    <button type="button" onclick="showPScissors()" onclick="computerRandom()" id="scissorsBtn">Scissors</button>
</div>

this is the stack overflow editor that shos the code this way the format is fine.
i made a function to generate a random image, but it isn’t working and I’m not sure why.

2

Answers


  1. If I understand correctly, you should change your var compRps = Math.floor(Math.random() * compImgs); to var compRps = Math.floor(Math.random() * compImgs.length);.

    As Andy said in comments, your trying to multiply it by array instead of number of elements it contains.

    Login or Signup to reply.
  2. Your try has a lot of mistakes. I write out a whole code for you and explain it here.

    HTML:

    <div class="playerBtn">
        <button type="button" onclick="showPRock()" onclick="computerRandom()"  id="rockBtn">Rock</button>
        <button type="button" onclick="showPPaper()" onclick="computerRandom()" id="paperBtn">Paper</button>
        <button type="button" onclick="showPScissors()" onclick="computerRandom()" id="scissorsBtn">Scissors</button>
    </div>
    <img src = "rock1Computer.png" alt = "Computer chooses rock!"id = "imgrock">
    <img src = "paper1Computer.png" alt = "Computer chooses paper!"id = "imgpaper">
    <img src = "scissors1Computer.png" alt = "Computer chooses scissors!"id = "imgscissors">
    

    Your html is mostly fine. I also added imgs assuming "rock1Computer.png", "paper1Computer.png" and "scissors1Computer.png" are actual paths

    Javascript

    function computerRandom(){
    var compImgs = ["rock1Computer.png", "paper1Computer.png", "scissors1Computer.png"];
    var compRps =  Math.floor(Math.random() * compImgs.length);
    
    const showComp = compImgs[compRps];
    var showImg = document.getElementById("img" + showComp.split("1")[0]);
    showImg.style.display = "block"
    };
    

    we take a random string from the array then we take the characters before 1 (either rock paper or scissors) and we make them visible

    CSS:

    [id^="img"] {
        display: none;
    }
    

    we hide the img elements from before

    This answer should work

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search