简体   繁体   English

将JavaScript中的图像输出到子手游戏中

[英]Outputting an image in JavaScript onto a hangman game

I am creating a hangman game and I have to output images, when the users lives get down from 7-0. 我正在创建一个from子手游戏,当用户的生命从7-0下降时,我必须输出图像。 I have put this code into my javascript , however it only outputs the if(lives ==8) image. 我已将此代码放入我的javascript中,但是它仅输出if(lives == 8)图像。 Unfortunality it does not seem to work at all ? 不幸似乎根本没有用吗?

I am very new to javascript and when I have read the other answers, I have found them hard to understand. 我对javascript非常陌生,当我阅读其他答案时,发现它们很难理解。

The fact that it doesn't output , does this mean I have an error in my code somewhere. 它不输出的事实,这意味着我的代码在某处出错。 ?

    function setup() {

    alphabet = "abcdefghijklmnopqrstuvwxyz";
    lives = 8;
    var words = ["ayeupmeducks", "pieceofcake", "bullinachinashop", "hangfire","greeneyedmonster",       "hairraising","bringhomethebacon","adiamondintherough","onceinabluemoon","afootinthedoor","bitethebullet"];
    messages = {
        win: 'Congratulations you have won the game of Hangman!',
        lose: 'You have been Hanged !!',
        guessed: ' already guessed, please try again...',
        validLetter: 'Please enter a letter from A-Z'
         };

     var getHint = document.getElementById("hint");
     var showClue = document.getElementById("clue");
     getHint.onclick = function() {
     hints = 
    ["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"];
    var hintIndex = words
    showClue.innerHTML = "Clue: - " +  hints [idx];
     };
    gussedLetter = matchedLetter = '';
    numberofMatchedLetters = 0;

  /* This chooses the word which will be displayed on the page */
     idx = Math.floor(Math.random() * words.length);
     currentWord = words[idx];
    output = document.getElementById("output");
    message = document.getElementById("message");
    guessInput = document.getElementById("letter");
    message.innerHTML = 'You have ' + lives + ' lives remaining';
    output.innerHTML = '';
    document.getElementById("letter").value = '';

    guessButton = document.getElementById("guess");
    guessInput.style.display = 'inline';
    guessButton.style.display = 'inline';

    letters = document.getElementById("letters");
    letters.innerHTML = '<li class="current-word">Current word:</li>';
    var letter, i;
    for (i = 0; i < currentWord.length; i++) {
    /*  returns the character at the specified index in a string.*/
        letter = '<li class="letter letter' + currentWord.charAt(i).toUpperCase() + '">' + currentWord.charAt(i).toUpperCase() + '</li>';
    /*  inserts the results node into Dom at the correct place, The BeforeEnd- inside the element, after its last child.*/
        letters.insertAdjacentHTML('beforeend', letter);
    }
}
function gameOver(win) {
    if (win) {
        output.innerHTML = messages.win;
        output.classList.add('win');
    } else {
        output.innerHTML = messages.lose;
        output.classList.add('error');

    } 
    guessInput.style.display = guessButton.style.display = 'none';
    guessInput.value = '';
}
window.onload = setup();
document.getElementById("restart").onclick = setup;
     guessInput.onclick = function () {
     this.value = '';
};

    document.getElementById('hangman').onsubmit = function (e) {
    if (e.preventDefault) e.preventDefault();
    output.innerHTML = '';
    output.classList.remove('error', 'warning');
    guess = guessInput.value;

    if (guess) {
        if (alphabet.indexOf(guess) > -1) {
        if ((matchedLetter && matchedLetter.indexOf(guess) > -1) || (gussedLetter && gussedLetter.indexOf(guess) > -1)) {
                output.innerHTML = '"' + guess.toUpperCase() + '"' + messages.guessed;
               output.classList.add("warning");
            }
            else if (currentWord.indexOf(guess) > -1) {
             var lettersToShow;
              lettersToShow = document.querySelectorAll(".letter" + guess.toUpperCase());
              for (var i = 0; i < lettersToShow.length; i++) {
                    lettersToShow[i].classList.add("correct");
                }


                for (var j = 0; j < currentWord.length; j++) {
                    if (currentWord.charAt(j) === guess) {
                        numberofMatchedLetters += 1;
                    }
                }
                matchedLetter += guess;
                if (numberofMatchedLetters === currentWord.length) {
                    gameOver(true);
               }
            }
            else {
                gussedLetter += guess;
                lives--;
                message.innerHTML = 'You have ' + lives + ' lives remaining';
                if (lives === 0) gameOver();
                               }
        }
        else {
            output.classList.add('error');
            output.innerHTML = messages.validLetter;
        }
    }
    else {
        output.classList.add('error');
        output.innerHTML = messages.validLetter;
    }
    return false;
    };

   var x = document.createElement("IMG");
   if (lives==8){
           x.setAttribute("src", "Hangman-0.png");
           x.setAttribute("width", "304");
           x.setAttribute("height", "228");
           x.setAttribute("alt", "Hangman");
           document.body.appendChild(x);}
  if (lives==7){
           x.setAttribute("src", "Hangman-1.png");
           x.setAttribute("width", "304");
           x.setAttribute("height", "228");
           x.setAttribute("alt", "Hangman");
           document.body.appendChild(x);}

From looking at you code, you can simplify a lot - each image has the same height, width, and alt, so you can move all of that out of the function. 通过查看代码,您可以简化很多工作-每个图像都具有相同的高度,宽度和高度,因此您可以将所有这些图像移出该函数。 Also, assuming the src attribute is just a number that is incrementing, you can instead do something like: 另外,假设src属性只是一个递增的数字,则可以执行以下操作:

var num_lives = 8;
var lives_left = 8;
function guess() {
    lives_left--;
    x.setAttribute('src', 'Hangman-' + (num_lives - lives_left) + '.png');
}

So, as a working example, your code would basically be: 因此,作为一个有效的示例,您的代码基本上是:

 var url = 'https://www.oligalma.com/downloads/images/hangman/files/'; const num_lives = 10; var lives = 10; var x = document.createElement("IMG"); x.setAttribute("width", "304"); x.setAttribute("height", "228"); x.setAttribute("alt", "Hangman"); x.setAttribute("src", url + (num_lives - lives) + '.jpg'); document.body.appendChild(x); function change() { lives--; if (lives < 0) { lives = num_lives; } x.setAttribute("src", url + (num_lives - lives) + '.jpg'); } 
 <button onClick="change()">Guess</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM