I'm working on a simple rock, paper, scissors game of HTML + JS.
Here are the full codes (CSS, JS, HTML): http://jsfiddle.net/fJw4R/ (too long to past here I thought). Here you can see it with pictures: http://shinebrightmedia.se/rps/rockpaperscissors.html
As you can see, the .math-module works, and when you choose rock, paper or scissor the computer randomizes a choice.
However, I now would like to have a textstring underneath the computer/monitor, and I'm wondering what the easiest way to do that. I want it to either say YOU WIN! or YOU LOSE!
I started on a function looking like this:
function theWinnerIs(userChoice, computerChoice) {
if (userChoice === computerChoice ) {
return 'No winner, it is a draw';
}
if ((userChoice === 'rock') && (computerChoice === 'scissor')) {
return 'human';
}
if ((userChoice === 'rock') && (computerChoice === 'paper')) {
return 'computer';
}
if ((userChoice === 'paper') && (computerChoice === 'scissor')) {
return 'computer';
}
if ((userChoice === 'paper') && (computerChoice === 'rock')) {
return 'human';
}
if ((userChoice === 'scissor') && (computerChoice === 'rock')) {
return 'computer';
}
if ((userChoice === 'scissor') && (computerChoice === 'paper')) {
return 'human';
}
}
What is the easiest way to send the return to the index-file? ie. YOU WIN! or YOU LOSE!
Thanks for any help.
No need to use this block of if
s - here's very compact alternative:
var choices = { rock: -1, paper: 0, scissors: 1 };
var score = choices[userChoice] - choices[computerChoice];
score = score - (score/2|0) * 3;
... which will give you -1
if user loses the round, 1
if they win, 0
in case of draw.
Now you can just send the output to any prepared container by filling its innerHTML property:
var results = {
'-1': 'YOU LOSE',
'1': 'YOU WIN',
'0': 'IT\'S A DRAW'
};
var resultContainer = document.getElementById('result');
resultContainer.innerHTML = results[score];
Here's a small demo to illustrate both those concepts.
From what I understand, you would like to display some text depending on the outcome of your "theWinnerIs" method. I would suggest you create a div on your page and set its content with JavaScript. There are numerous ways to accomplish your goal, however.
So you want to add a div to your page, something like <div id="output"></div>
. You can then update the text here with the following
var outputElement = document.getElementById("output");
outputElement.innerHTML = theWinnerIs(userChoice, computerChoice);
Here's an updated version of your code for perspective, though raina77ow's solution is much nicer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.