Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to make a Rock Paper Scissors coding challenge for myself, and I got a simple version with a text box, so no I'm trying to make it with buttons, I have made it very far through, I'm just on the last step.

So what I want to do is take the info from the rock(), paper(), and scissors() functions and go further

This is what I have so far

var playerInput = "blank"
    
function rock(playerInput) {
    this.playerInput = playerInput; 
    playerInput = "rock";
}

function paper(playerInput) {
    this.playerInput = playerInput; 
    playerInput = "paper";
}

function scissors() {
    this.playerInput = playerInput; 
    playerInput = "scissors";
}

and what I want to do from there is take it into another function where I have already created the game itself.

I've tried

var rock = rock();
console.log(rock.playerInput);

and it didn't work please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's a super useful example on how to tackle the Rock, Paper, Scissors game logic using buttons.

Besides that, you don't need multiple functions, programming is not about copy/pasting code around a file, but to determine the characteristics we can reuse.

Use data-* attributes to store the figure index:

function play() {
  const player = Number(this.dataset.player); // Get 0, 1, 2 from button data-player
  const computer = Math.floor(Math.random() * 3); // Generate random 0, 1, 2 integer
  console.log(`PLAYER: ${player} COMPUTER:${computer}`);

  // Game logic goes here
}

const buttons = document.querySelectorAll("[data-player]");

buttons.forEach(function(el) {
  el.addEventListener("click", play);
});
<button data-player="0" type="button">ROCK</button>
<button data-player="1" type="button">PAPER</button>
<button data-player="2" type="button">SCISSORS</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...