1

I am working with the following: http://codepen.io/anon/pen/jPJzZB

HTML:

<h1>Rock, Paper, Scissors, Lizard, Spock</h1><br>
<div id="user-choice">
    <button onClick="userChoice = rock" id="rock"><i class="fa fa-hand-rock-o fa-3x"></i></button>
    <button onClick="userChoice = paper" id="paper"><i class="fa fa-hand-paper-o fa-3x"></i></button>
    <button onClick="userChoice = scissors" id="scissors"><i class="fa fa-hand-scissors-o fa-3x"></i></button>
    <button onClick="userChoice = lizard" id="lizard"><i class="fa fa-hand-lizard-o fa-3x"></i></button>
    <button onClick="userChoice = spock" id="spock"><i class="fa fa-hand-spock-o fa-3x"></i></button>
</div>

CSS:

var choices  =  {rock : {name: "Rock", defeats: {scissors: "crushes", lizard: "crushes"}},
                 paper: {name: "Paper", defeats: {rock:  "covers", spock: "disproves"}},
                 scissors: {name: "Scissors", defeats:{paper : "cuts", lizard: "decapitates"}},
                 lizard: {name: "Lizard", defeats:{paper: "eats", spock: "poisons"}},
                 spock: {name: "Spock", defeats:{scissors : "smashes",rock : "vaporises"}}
                };

var computerChoice = Math.random();
if (computerChoice <= 0.2) {
    computerChoice = "rock";
} else if (computerChoice <= 0.4) {
    computerChoice = "paper";
} else if (computerChoice <= 0.6) {
    computerChoice = "scissors";
} else if (computerChoice <= 0.8) {
    computerChoice = "lizard";
} else {
    computerChoice = "spock";
}



document.write("I chose " + computerChoice + ".");





if(computerChoice == userChoice){
    document.write(" It's a tie...");
}else{
    userChoice = choices[userChoice];    

    var victory = userChoice.defeats[computerChoice] !== undefined;
    computerChoice = choices[computerChoice]

    if(victory) {        
        document.write(" You won! " + userChoice.name + " " + userChoice.defeats[computerChoice.name.toLowerCase()] + " " + computerChoice.name + "!") 
    }else{
        document.write(" I won! " + computerChoice.name + " " + computerChoice.defeats[userChoice.name.toLowerCase()] + " " + userChoice.name + "!");
    }   
}

I am not sure how to use the button onClick to assign a variable. The javascript is a modification of an answer found here:Rock, Paper, Scissors, Lizard, Spock in JavaScript

Community
  • 1
  • 1
Chris569x
  • 335
  • 1
  • 3
  • 14

1 Answers1

1

It's pretty easy! There's two options:

  • Using inline JavaScript in HTML.

  • Using JavaScript DOM API to get this done.

Option #1:

<button onclick="alert('Yeah!!, I was clicked')">Click me!</button>

Option #2:

document.getElementById('btn').onclick = function(){
  alert('Yeah!!!, I was clicked');
}
<button id="btn">Click me!</button>

Note that variable assignment is very similar to this, the only difference is you should replace that alert statement by an assignment statement.

frogatto
  • 28,539
  • 11
  • 83
  • 129