lundi 26 avril 2021

How do I adjust the code so that the image appears when the website loads and the guess is guessing what I want it to guess?

Basically, I want the score to go up by 1 point everytime the user guesses the name of the image. So for example, if the image shows chad, and they guess Chad in the textbox, they'll gain 1 point.

Currently, when the page is loaded there is no image located, so when the button is pressed the user is basically having to guess what the next image is going to be, which is not what I want. I want the user to be able to see the image to answer what the images name is.

<!DOCTYPE html>
<html>
    <body>
        <p id="Image"></p>

        <p id="GameScore">Score: 0</p>

        <button onclick="CheckAnswer()">Start Game!</button>

        <input id="userInput" type="text" />

        <script>
            let score = 0;
            var Chad = "Chad.jpg";
            var Bob = "Bob.jpg";
            var John = "John.jpg";

            var theArray = [Chad, Bob, John];

            function CheckAnswer() {
                var i;
                for (i = 0; i < 1; i++) {
                    var randomPhoto = theArrayArray[Math.floor(Math.random() * theArray.length)];

                    document.getElementById("Image").innerHTML = `<img src="${randomPhoto}" width="250" height="250" />`;
                }

                var userGuess = document.getElementById("userInput").value;
                console.log(randomPhoto);

                if (userGuess == randomPhoto) {
                    alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
                    score++;
                } else {
                    alert("SORRY, IT WAS INCORRECT");
                    score = score - 1;
                }
                document.getElementById("GameScore").innerHTML = "Score: " + score;
            }
        </script>
    </body>
</html>

Aucun commentaire:

Enregistrer un commentaire