Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

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

  // Game logic goes here
}

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

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

Given the above, you got pretty much all the needed data.

  • Both player and computer values are an integer 0 (rock), 1 (paper), 2 (scissors)

Example of Rock Paper Scissors game with result

const fig = ["Rock", "Paper", "Scissors"];
const msg = ["You won!", "You lost :(", "It's a draw"];

functionplay() {
  const player = Number(this.dataset.player); // Get 0, 1, 2 from button data-playerconst computer = Math.floor(Math.random() * 3); // Generate random 0, 1, 2 integer// Game logic goes here// See: https://stackoverflow.com/a/53983473/383904let result;
  if (player === computer) {
    result = 2; // Draw
  } elseif ((computer + 1) % 3 === player) {
    result = 0; // Player wins
  } else {
    result = 1; // Computer wins
  }

  console.log(`PLAYER:${fig[player]} COMPUTER:${fig[computer]}${msg[result]}`);
}

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

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

Solution 2:

functionrock(playerInput) {
    
    this.playerInput = playerInput; 
    
}

var playerInput = 'blank'var myRock = newrock(playerInput);
console.log(myRock.playerInput) // Should output "Blank"

If you want to make an object with function notation, you need to use the new keyword:

var myRock = newrock();

And you should be passing the info to the object when you create it, not before. Try something like this.

functionrock(playerInput) {
    this.playerInput = playerInput; 
}

var myRock = newrock("Blank");
console.log(myRock.playerInput) // Should output "Blank"

Post a Comment for "Rock Paper Scissors Coding Challenege"