JavaScript Rock, Paper, Scissors game logic - javascript

I am having some difficulty thinking through and implementing a JavaScript Rock, Paper, Scissors game. My problem is when I want to retrieve the data from the UI with an event listener, I am unable to stop the game until I have retrieved that data before it continues into the if-else statement.
Any criticism or feedback of any kind is certainly welcome.
Here is my code:
//1. GETTING DATA FROM THE UI AND THE COMPUTER
let model = (function() {
// dom strings:
const domStrings = {
userInput: "#textInput",
submit: "#submit"
}
return {
// A. Get user input
getUserInput: function(){
return document.querySelector(domStrings.userInput).value;
},
// B. Get computer input
compInput: function() {
let optionsArray = ["rock", "paper", "scissors"];
let randNum = Math.floor(Math.random()* 3);
console.log(randNum)
return optionsArray[randNum];
},
// C. Make DOM elements public
getDomStrings: function(){
return domStrings;
}
}
})();
// 2. USER INTERFACE CONTROLLER
let UI = (function(){
return {
insertHTML: function(outcome, playerScore, computerScore){
return `
<div class="text">
<p>${outcome}!</p>
<p>***********</p>
<p>Total scores: Player ${playerScore} - ${computerScore} Computer</p>
</div>
`
}
}
})()
// 3. APP CONTROLLER
let controller = (function(mdl, ui){
// (imported domStrings from model):
let DOM = mdl.getDomStrings();
let userInput = "scissors";
// a. Get user Input
document.querySelector(DOM.submit).addEventListener("click", (e) => {
e.preventDefault();
userInput = mdl.getUserInput();
});
// b. get computer Input
let compInput = mdl.compInput();
// c. check whether the player wins, the computer wins or if its a draw
if(userInput === compInput){
console.log("Draw!")
} else if(userInput === "rock" && compInput === "paper"){
console.log("Computer Wins!");
} else if(userInput === "rock" && compInput === "scissors"){
console.log("player wins");
} else if(userInput === "paper" && compInput === "scissors"){
console.log("computer wins")
} else if (userInput === "paper" && compInput === "rock"){
console.log("user wins");
} else if (userInput === "scissors" && compInput === "rock"){
console.log("player wins");
} else if (userInput === "rock" && compInput === "paper"){
console.log("computer wins");
} else if (userInput === "scissors" && compInput === "paper"){
console.log("computer wins");
}
// i. update score
// ii. display current score
})(model, UI)

You need to place your if statements inside the event listener. For example:
let controller = (function(mdl, ui){
// (imported domStrings from model):
let DOM = mdl.getDomStrings();
let userInput = "scissors";
// a. Get user Input
document.querySelector(DOM.submit).addEventListener("click", (e) => {
e.preventDefault();
userInput = mdl.getUserInput();
getResult();
});
// b. get computer Input
let compInput = mdl.compInput();
// c. check whether the player wins, the computer wins or if its a draw
function getResult() {
if(userInput === compInput){
console.log("Draw!")
} else if(userInput === "rock" && compInput === "paper"){
console.log("Computer Wins!");
} else if(userInput === "rock" && compInput === "scissors"){
console.log("player wins");
} else if(userInput === "paper" && compInput === "scissors"){
console.log("computer wins")
} else if (userInput === "paper" && compInput === "rock"){
console.log("user wins");
} else if (userInput === "scissors" && compInput === "rock"){
console.log("player wins");
} else if (userInput === "rock" && compInput === "paper"){
console.log("computer wins");
} else if (userInput === "scissors" && compInput === "paper"){
console.log("computer wins");
}
}
// i. update score
// ii. display current score
})(model, UI)

Related

if else statement failing in a paper-rock-scissors challenge

I'm a complete beginner in Javascript and coding in general.
I'm trying to make a simple command-line javascript paper-rock-scissors game but I keep getting a bug. I've created a function for the computer to randomly pick paper, rock or scissors and getting the user's selection from a prompt. To get the result I've written an if else statement that will show an alert with the outcome but regardless the input it always shows a tie. It seems that the code always ends up on the else part of the statement and I can't figure out why. Can someone help me with what's wrong with the statement and why it skips to else?
function computerPlay() {
let computerChoices = ["paper", "rock", "scissors"];
let computerChoice = computerChoices[Math.floor(Math.random() * computerChoices.length)];
return computerChoice;
}
function playRound(computerSelection, playerSelection) {
if (computerSelection === "rock" && playerSelection.toLowerCase() === "paper") {
alert("You win, paper beats rock!")
} else if (computerSelection === "paper" && playerSelection.toLowerCase() === "scissors") {
alert("You win, scissors beat paper!")
} else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "rock") {
alert("You win, rock beat scissors")
} else if (computerSelection === "rock" && playerSelection.toLowerCase() === "scissors") {
alert("You loose, rock beats scissors")
} else if (computerSelection === "paper" && playerSelection.toLowerCase() === "rock") {
alert("You loose, paper beats rock")
} else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "paper") {
alert("You loose, scissors beats paper")
} else {
alert("even steven")
}
}
for (let i = 1; i <= 5; i++) {
computerPlay()
const playerSelection = prompt("Please enter your choice", " ");
const computerSelection = computerPlay();
console.log(computerSelection);
console.log(playerSelection);
playRound(computerSelection, playerSelection);
}
Remove " " from the prompt, it's adding an unnnecessary white space causing issues in your if statements
function computerPlay() {
let computerChoices = ["paper", "rock", "scissors"];
let computerChoice = computerChoices[Math.floor(Math.random() * computerChoices.length)];
return computerChoice;
}
function playRound(computerSelection, playerSelection) {
if (computerSelection === "rock" && playerSelection.toLowerCase() === "paper") {
alert("You win, paper beats rock!")
} else if (computerSelection === "paper" && playerSelection.toLowerCase() === "scissors") {
alert("You win, scissors beat paper!")
} else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "rock") {
alert("You win, rock beat scissors")
} else if (computerSelection === "rock" && playerSelection.toLowerCase() === "scissors") {
alert("You loose, rock beats scissors")
} else if (computerSelection === "paper" && playerSelection.toLowerCase() === "rock") {
alert("You loose, paper beats rock")
} else if (computerSelection === "scissors" && playerSelection.toLowerCase() === "paper") {
alert("You loose, scissors beats paper")
} else {
alert("even steven")
}
}
for (let i = 1; i <= 5; i++) {
computerPlay()
const playerSelection = prompt("Please enter your choice");
const computerSelection = computerPlay();
console.log(computerSelection);
console.log(playerSelection);
playRound(computerSelection, playerSelection);
}

JS nested if statement logic not working as intended

function decideWinner() {
comChoice = generateComputerChoice();
userChoice = "Rock";
if (userChoice === comChoice) {
console.log("game drew");
} else {
if (userChoice === "Rock" && comChoice === ("Scissor" || "Lizard")) {
console.log("you win")
} else if (userChoice === "Paper" && comChoice === "Rock" || "Spock") {
console.log("you win")
} else if (userChoice === "Scissors" && comChoice === "Paper" || "Lizard") {
console.log("you win")
} else if (userChoice === "Lizard" && comChoice === "Spock" || "Paper") {
console.log("you win")
} else if (userChoice === "Spock" && comChoice === "Scissor" || "Rock") {
console.log("you win")
} else {
console.log("you lose")
}
}
}
decideWinner()
The comChoice is generated from another function. userChoice is set to "Rock" first part should return draw if both are the same and 2nd returns a win or loss depending on the outcome of the comChoice. But this is not happening i am getting a draw if "Spock" is drawn by the computer and a win in all other circumstances.
can anyone see what ive done wrong please
?
The problem is with how you are using the OR(||) operator.
Using val1 || val2 returns the value of the first one that is truth. So, essentially ("Scissor" || "Lizard") will return "Scissor" everytime. What you instead intend to do is to actually check equality with comChoice, so you should refactor your code as such:
if (userChoice === comChoice) {
console.log("game drew");
} else {
if (userChoice === "Rock" && (comChoice === "Scissor" || comChoice === "Lizard")) {
console.log("you win")
} else if (userChoice === "Paper" && (comChoice === "Rock" || comChoice === "Spock")) {
console.log("you win")
} else if (userChoice === "Scissors" && (comChoice === "Paper" || comChoice === "Lizard")) {
console.log("you win")
} else if (userChoice === "Lizard" && (comChoice === "Spock" || comChoice === "Paper")) {
console.log("you win")
} else if (userChoice === "Spock" && (comChoice === "Scissor" || comChoice === "Rock")) {
console.log("you win")
} else {
console.log("you lose")
}
}
One problem that I notice is with your OR operator. Checking comChoice === "Rock" || "Spock" is not doing what you expect.
instead you need to check it like this: (comChoice === "Rock" || comChoice === "Spock")
On another note I would just use == instead of === in your case since we can't see what data type is being passed which could result in false results.

Changing the value of a variable with DOM element click

Im trying to allow the player to click the Rock paper or scissors button and that changes the value of the 'playerChoice' variable so so the playRound function can be called with their choice but it doesnt seem to work and im not sure what im doing wrong
Code
// Rock paper scissors game
let rockBtn = document.querySelector('.Rock');
let paperBtn = document.querySelector('.Paper');
let scissorBtn = document.querySelector('.Scissors');
function computerPlay() {
let rps = ["Rock", "Paper", "Scissors"];
let computerChoice = rps[Math.floor(Math.random()*rps.length)];
return computerChoice;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection == "Rock" && computerSelection == "Rock") {
console.log('Its a Draw');
} else if (playerSelection == "Rock" && computerSelection == "Scissors") {
console.log("Player wins");
} else if(playerSelection == "Rock" && computerSelection == "Paper") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Paper") {
console.log("Its a draw");
} else if(playerSelection == "Paper" && computerSelection == "Scissors") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Rock") {
console.log("Player wins");
} else if(playerSelection == "Scissors" && computerSelection == "Scissors") {
console.log("Its a draw");
} else if(playerSelection == "Scissors" && computerSelection == "Paper") {
console.log("Player wins ");
} else if(playerSelection == "Scissors" && computerSelection == "Rock") {
console.log("Computer wins");
}
}
function game() {
const computerChoice = computerPlay();
var playerChoice = "";
rockBtn.addEventListener('click' , function() {
playerChoice = "Rock";
});
paperBtn.addEventListener('click' , function() {
playerChoice = "Paper";
console.log(playerChoice);
});
scissorBtn.addEventListener('click' , function() {
playerChoice = "Scissors";
});
console.log("Player choice is" + playerChoice);
console.log('Computer choice is' + computerChoice);
playRound(playerChoice, computerChoice);
}
game();
Is this the correct way to do this is there a better way?
You should call playRound method inside the click listeners.
// Rock paper scissors game
let rockBtn = document.querySelector('.Rock');
let paperBtn = document.querySelector('.Paper');
let scissorBtn = document.querySelector('.Scissors');
var playerChoice = "";
function computerPlay() {
let rps = ["Rock", "Paper", "Scissors"];
let computerChoice = rps[Math.floor(Math.random()*rps.length)];
return computerChoice;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection == "Rock" && computerSelection == "Rock") {
console.log('Its a Draw');
} else if (playerSelection == "Rock" && computerSelection == "Scissors") {
console.log("Player wins");
} else if(playerSelection == "Rock" && computerSelection == "Paper") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Paper") {
console.log("Its a draw");
} else if(playerSelection == "Paper" && computerSelection == "Scissors") {
console.log("Computer wins");
} else if(playerSelection == "Paper" && computerSelection == "Rock") {
console.log("Player wins");
} else if(playerSelection == "Scissors" && computerSelection == "Scissors") {
console.log("Its a draw");
} else if(playerSelection == "Scissors" && computerSelection == "Paper") {
console.log("Player wins ");
} else if(playerSelection == "Scissors" && computerSelection == "Rock") {
console.log("Computer wins");
}
playerChoice = "";
}
rockBtn.addEventListener('click' , function() {
playerChoice = "Rock";
playRound(playerChoice, computerPlay());
});
paperBtn.addEventListener('click' , function() {
playerChoice = "Paper";
playRound(playerChoice, computerPlay());
});
scissorBtn.addEventListener('click' , function() {
playerChoice = "Scissors";
playRound(playerChoice, computerPlay());
});

alert() not working in function

Added buttons to my rock paper scissors game, I was having trouble making the alert show up after the userChoice variable changes, so I used eventListeners for that and the winner stopped showing up with the alert, why is this happening? Is there a better way to do this?
I'm a beginner any help is appreciated.
<!DOCTYPE html>
<html>
<body>
</body>
<script>
function compPlay (){} //picks a random nb and makes it rock paper...
let userChoice;
function userPlay (){
btnRock.addEventListener("click", ()=>{
userChoice="rock";
return userChoice;
});
btnPaper.addEventListener("click", ()=>{
userChoice="paper";
return userChoice;
});
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
return userChoice;
});
}
function theGame (compPlay,userPlay) {
if (compPlay===userPlay) {
alert("its tied");
} else if (compPlay === "rock" && userPlay === "scissors") {
alert("you lose!");
} else if (compPlay === "scissors" && userPlay === "paper") {
alert("you lose");
} else if (compPlay=== "paper" && userPlay === "rock"){
alert("you lose");
} else if (compPlay === "scissors" && userPlay === "rock") {
alert("you win!");
} else if (compPlay === "paper" && userPlay === "scissors") {
alert("you win");
} else if (compPlay=== "rock" && userPlay === "paper"){
alert("you win");
}
}
theGame(compPlay(),userPlay());
</script>
</html>
The function call will happen during the load of the script.At that time, the compPlay function will return a value whereas the userPlay function will create the elements. Thereafter when the button click is happening, the function will not even be called.
Edit:For your info..This is one way to do it
<!DOCTYPE html>
<html>
<body>
</body>
<script>
function compPlay (){
let comChoice= Math.random();
console.log(comChoice);
if (comChoice<=0.33){
comChoice= "rock";
} else if (comChoice<=0.66){
comChoice= "scissors";
} else {
comChoice= "paper";
}
userPlay(comChoice);
}
let userChoice;
function userPlay (comChoice){//Function for user's click comparison with computer's option
let btnRock = document.createElement("button");
let tRock = document.createTextNode("Rock");
btnRock.appendChild(tRock);
document.body.appendChild(btnRock);
btnRock.addEventListener("click", ()=>{
userChoice="rock";
theGame(comChoice,userChoice);//Main function call to decide the winner
});
let btnPaper = document.createElement("button");
let tPaper = document.createTextNode("Paper");
btnPaper.appendChild(tPaper);
document.body.appendChild(btnPaper);
btnPaper.addEventListener("click", ()=>{
userChoice="paper";
theGame(comChoice,userChoice);
});
let btnScissors = document.createElement("button");
let tScissors = document.createTextNode("Scissors");
btnScissors.appendChild(tScissors);
document.body.appendChild(btnScissors);
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
theGame(comChoice,userChoice);
});
}
function theGame (compPlay,userPlay) {
if (compPlay===userPlay) {
alert("its tied");
} else if (compPlay === "rock" && userPlay === "scissors") {
alert("you lose!");
} else if (compPlay === "scissors" && userPlay === "paper") {
alert("you lose");
} else if (compPlay=== "paper" && userPlay === "rock"){
alert("you lose");
} else if (compPlay === "scissors" && userPlay === "rock") {
alert("you win!");
} else if (compPlay === "paper" && userPlay === "scissors") {
alert("you win");
} else if (compPlay=== "rock" && userPlay === "paper"){
alert("you win");
}
}
compPlay();//Basic initialising function call
</script>
</html>
You could call the game function when you click on a button
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
theGame(comChoice,userChoice);
});
EDIT:
I forgot to said that in order to work to you should change your comChoice to a Global variable.Thanks #Krisna Prashatt

How to make a counter for rock, paper, scissors game?

I'm trying to make a rock, paper, scissors game for class, but I'm stuck with creating a counter. I declared global variables and thought it would be simple to just add +1 every time somebody wins, but it doesn't seem to be working. Here's my code of what I'm using now. What should I add to make the counter work?
var game = false;
var playerScore = 0;
var compScore = 0;
while (game != true){
var userChoice = prompt("Pick your poison: Rock, paper, or scissors. Type 'exit' to quit.").toLowerCase();
if (userChoice === "rock" || userChoice === "paper" || userChoice === "scissors"){
var computerChoice = randomizeComputer();
console.log("You chose: " + userChoice);
console.log("Computer chose: " + computerChoice);
compare(userChoice);
} else if (userChoice === "exit"){
console.log("Thanks for playing");
game = true;
} else {
console.log("Sorry, you typed something we couldn't recognize");
}
}
function compare (choice){
//If it's the same thing
if (choice === computerChoice){
return console.log("It's a tie");
}
//If user chooses rock
if (choice === "rock"){
if (computerChoice === "scissors"){
return console.log("You win!");
counter(1);
} else if (computerChoice === "paper"){
return console.log("You lose!");
}
}
//If user chooses paper
if (choice === "paper"){
if (computerChoice === "rock"){
return console.log("You win!");
} else if (computerChoice === "scissors"){
return console.log("You lose!");
}
}
//If user chooses scissors
if (choice === "scissors"){
if (computerChoice === "paper"){
return console.log("You win!");
} else if (computerChoice === "rock"){
return console.log("You lose!");
}
}
}
//Randomizes
function randomizeComputer () {
var i = Math.floor(Math.random() * 3 + 1);
if (i === 1){
return "rock";
} else if (i === 2){
return"paper";
} else {
return "scissors";
}
}

Categories

Resources