当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Trying to display images instead of letters for Rock Paper Scissors game

问题描述:

I am working on a R,P,S game and I want to display images instead of letters for the choices the user and computer make. I started an if statement about half way down the page but I cant seem to get it to display the image on the page. Any help would be much appreciated.

 var computerChoices = ['r', 'p', 's'];

var wins = 0;

var losses = 0;

var ties = 0;

document.onkeyup = function(event) {

var userGuess = String.fromCharCode(event.keyCode).toLowerCase();

var computerGuess = computerChoices[Math.floor(Math.random() * computerChoices.length)];

if ((userGuess == 'r') || (userGuess == 'p') || (userGuess == 's')){

if ((userGuess == 'r') && (computerGuess == 's')){

wins++;

}else if ((userGuess == 'r') && (computerGuess == 'p')){

losses++;

}else if ((userGuess == 's') && (computerGuess == 'r')){

losses++;

}else if ((userGuess == 's') && (computerGuess == 'p')){

wins++;

}else if ((userGuess == 'p') && (computerGuess == 'r')){

wins++;

}else if ((userGuess == 'p') && (computerGuess == 's')){

losses++;

}else if (userGuess == computerGuess){

ties++;

}

if (userGuess == 'r'){

var displayRock = "<img src='images/rock-user.png' alt='User Rock'>";

document.querySelector("#userGuess").innerHTML = displayRock;

}

var displayWins = wins;

document.querySelector('#wins').innerHTML = displayWins;

var displayLosses = losses;

document.querySelector('#losses').innerHTML = displayLosses;

var displayTies = ties;

document.querySelector('#ties').innerHTML = displayTies;

var displayUserGuess = userGuess;

document.querySelector('#userGuess').innerHTML = displayUserGuess;

var displayComputerGuess = computerGuess;

document.querySelector('#computerGuess').innerHTML = displayComputerGuess;

document.querySelector('#game').innerHTML = html;

}

}

网友答案:

You're setting the image:

if (userGuess == 'r'){
    var displayRock = "<img src='images/rock-user.png' alt='User Rock'>";
    document.querySelector("#userGuess").innerHTML = displayRock;
}

And it is immediatelly being replaced a few lines below:

document.querySelector('#userGuess').innerHTML = displayUserGuess;

You might want to use the insertAdjacentHTML('beforeend', displayUserGuess) function.

Also, it is not good practice to query for the same element multiple times - it is better to query once and keep it in a variable like:

var userGuessEl = document.querySelector('#userGuess');

// and then below
userGuessEl.innerHTML = ...
分享给朋友:
您可能感兴趣的文章:
随机阅读: