Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - Rock Paper Scissors coding challenege

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...