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.
Related
It seems my if else condition has a syntax error, can somebody help? The console spits out this link { /home/ccuser/workspace/javascript_101_Unit_3_v2/rockPaperScissors.js:38
}); } and an error points to the ")"
userInput = userInput.toLowerCase();
if (userInput !== "rock" && userInput !== "paper" && userInput !== "scissor") {
console.log("Error");
} else {
return userInput;
}
}
const getComputerChoice = () => {
const randomNumber = Math.floor(Math.random() * 3);
switch(randomNumber){
case 0: return "scissor";
break;
case 1: return "rock";
break;
default: return "paper";
break;
}
}
const determinWinner = (userChoice, computerChoice) => {
if(userChoice === computerChoice){
return "Its a tie";
} else if (userChoice === "rock" && computerChoice ==="scissor"){
return "The user won";
} else if (userChoice === "paper" && computerChoice ==="rock"){
return "The user won";
} else if (userChoice === "scissor" && computerChoice ==="paper"){
return "The user won";
} else if (userChoice === "rock" && computerChoice ==="paper"){
return "The computer won";
} else if (userChoice === "paper" && computerChoice ==="scissor"){
return "The computer won";
} else if (userChoice === "scissor" && computerChoice ==="rock"){
return "The computer won";
}
You defining an enclosure, but you're missing the final }
const determinWinner = (userChoice, computerChoice) => {
if(userChoice === computerChoice){
return "Its a tie";
} else if (userChoice === "rock" && computerChoice ==="scissor"){
return "The user won";
} else if (userChoice === "paper" && computerChoice ==="rock"){
return "The user won";
} else if (userChoice === "scissor" && computerChoice ==="paper"){
return "The user won";
} else if (userChoice === "rock" && computerChoice ==="paper"){
return "The computer won";
} else if (userChoice === "paper" && computerChoice ==="scissor"){
return "The computer won";
} else if (userChoice === "scissor" && computerChoice ==="rock"){
return "The computer won";
}
}
You are just missing the last/closing } for your determinWinner(...) method.
This is how you code should look like!
const determinWinner = (userChoice, computerChoice) => {
if(userChoice === computerChoice){
return "Its a tie";
} else if (userChoice === "rock" && computerChoice ==="scissor"){
return "The user won";
} else if (userChoice === "paper" && computerChoice ==="rock"){
return "The user won";
} else if (userChoice === "scissor" && computerChoice ==="paper"){
return "The user won";
} else if (userChoice === "rock" && computerChoice ==="paper"){
return "The computer won";
} else if (userChoice === "paper" && computerChoice ==="scissor"){
return "The computer won";
} else if (userChoice === "scissor" && computerChoice ==="rock"){
return "The computer won";
}
}
Try this:
At the end of computerChoice){, add : and see if that works!
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)
So I am making a little rock, paper and scissors game in which you play VS the computer.
However, I made an if statement that should check whether you have filled out 'rock, paper or scissors'. If not, it should return an alert() that you did NOT fill out one of these 3, however when I do fill out rock, paper or scissors it still returns the alert().
The function:
function rockPaperScissors() {
let computerChoice;
let loopFunction = false;
let draw = 0;
while (loopFunction === false) {
let playerGuess = prompt('Enter rock, paper or scissors!');
let computerChoiceCalculator = Math.floor(Math.random() * 10);
if (playerGuess == '') {
window.alert('ggggg');
return;
} else if (playerGuess != 'rock' || 'paper' || 'scissors') {
window.alert('Please enter rock, paper or scissors');
}
else {
if (computerChoiceCalculator <= 4) {
computerChoice = 'rock';
console.log(computerChoice);
} else if (computerChoiceCalculator <= 7) {
computerChoice = 'paper';
console.log(computerChoice);
} else {
computerChoice = 'scissors';
console.log(computerChoice);
}
if (playerGuess === computerChoice) {
draw += 1;
window.alert('THIS WAS A DRAW! THE COMPUTER HAD ' + computerChoice + ' AND U HAD ' + playerGuess);
} else if (playerGuess === 'rock' && computerChoice === 'paper' || playerGuess === 'paper' && computerChoice === 'scissors' || playerGuess === 'scissors' && computerChoice === 'rock') {
window.alert('The computer won this round! Lets try again! your try was ' + playerGuess + ' and the computer had ' + computerChoice);
} else {
window.alert('fuck yeah! u won!');
}
}
}
}
the code which causes the problem:
else if (playerGuess != 'rock' || 'paper' || 'scissors') {
window.alert('Please enter rock, paper or scissors');
}
Ohh this is wrong:
else if (playerGuess != 'rock' || 'paper' || 'scissors')
This conditional won't work because you can't group equality operators like this.
You have to make the comparison for each item. This conditional, as written, will always return true because 'paper' will always be a truthy value.
You should do this instead:
else if (playerGuess != 'rock' && playerGuess != 'paper' && playerGuess != 'scissors')
Or you could do this, which is prettier:
else if (!['rock', 'paper', 'scissors'].includes(playerGuess))
you can't use this form of if statement else if (playerGuess != 'rock' || 'paper' || 'scissors')
it should be devided into three different comparasions like this:
else if (playerGuess != 'rock' && playerGuess != 'paper' && playerGuess != 'scissors')
you should replace it with :
if (playerGuess != 'rock' && playerGuess != 'paper' && playerGuess != 'scissors') {
or
if(!['rock','paper','scissors'].includes(playerGuess))
As others have suggested, else if (playerGuess != 'rock' || 'paper' || 'scissors') is incorrect syntax.
However, I think this syntax is probably the most modern and readable:
else if (!['rock', 'paper', 'scissors'].includes(playerGuess))
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
I have this code right now for my Rock Paper Scissors JS game. In my compare function, I tried to program it so that it will display an alert message if either "Rock", "Paper", or "Scissors" is not entered. It does not work though, and I get no response when I enter in a different string than the 3 choices that work.
var userChoice = prompt("Rock, Paper, or Scissors");
var computerChoice = Math.random();
var compchoice = function ()
{
if (computerChoice <= 0.34)
{
return computerChoice = "Rock";
}
else if(computerChoice <= 0.67 && computerChoice >= 0.35)
{
return computerChoice = "Paper";
}
if (computerChoice >= 0.68)
{
return computerChoice = "Scissors";
}
};
var compare = function (choice1, choice2)
{
if (computerChoice === "Rock" || "Paper" || "Scissors")
{
if (choice1 === choice2)
{
return alert("The result is a tie!");
}
else if (choice1 === "Rock")
{
if (choice2 === "Scissors")
{
return alert("Rock crushes Scissors!");
}
else if (choice2 === "Paper")
{
return alert("Paper covers Rock!");
}
}
if (choice1 === "Scissors")
{
if (choice2 === "Rock")
{
return alert("Rock crushes Scissors!");
}
else if (choice2 === "Paper")
{
return alert("Scissors cuts Paper!");
}
}
else if (choice1 === "Paper")
{
if (choice2 === "Rock")
{
return alert("Paper covers Rock!");
}
else if (choice2 === "Scissors")
{
return alert("Scissors cuts Paper!");
}
}
}
else
{
return alert("Please type Rock, Paper, or Scissors next time");
}
};
compchoice();
compare(userChoice, computerChoice);
Any reasons why?
computerChoice === "Rock" || "Paper" || "Scissors" is always true, since it parses as:
(computerChoice === "Rock") || ("Paper") || ("Scissors")
And "Paper" is a truthy value.
Also, you seem to be comparing computerChoice, not userChoice.
Fixed:
if (userChoice === "Rock" || userChoice === "Paper" || userChoice === "Scissors")
Or:
// array and indexOf
if (["Rock", "Paper", "Scissors"].indexOf(userChoice) > -1)
// doesn't work in IE8
Or:
// regex
if (/^(Rock|Paper|Scissors)$/.test(userChoice))
if (computerChoice === "Rock" || computerChoice === "Paper" || computerChoice === "Scissors")
TADA!.... "Paper" as a string resolves as true :D
You have a logic error in your first if in the compare:
if (computerChoice === "Rock" || "Paper" || "Scissors")
Should be:
if (computerChoice === "Rock" || computerChoice === "Paper" || computerChoice === "Scissors")
Edit: why you have this if statement in the first place does not make sense to me. You want to compare choice1 against choice2.
You can't do comparisons like this:
if (computerChoice === "Rock" || "Paper" || "Scissors")
You need to check each separately, like:
if(computerChoice === "Rock" || computerChoice === "Paper" || computerChoice === "Scissors")
The answer is given already, but you could optimize your code even more. This is what I would write:
var options=["Rock","Paper","Scissors"];
var beats=["crushes","covers","cuts"];
function play(choice){// "choice" = index of option
if(choice<0||choice>options.length-1){alert("invalid input");}
var loser=choice>0?choice-1:options.length-1; // what would lose from "choice"
var winner=choice<options.length-1?choice+1:0; // what would beat "choice"
switch(Math.floor(Math.random()*3)){ //chance of 1 in 3
case 0: alert(options[choice]+beats[choice]+options[loser]); break;// win :-)
case 1: alert(options[winner]+beats[winner]+options[choice]); break;// lose :-(
case 2: alert("The result is a tie!"); break;
}
}
play(0);// 0=rock!
Since the chance is 1 in 3 you only have to create 3 static outcomes (win, lose or draw), and generate the message for it.
I think you need the comparison to be userChoice like
if (userChoice === "Rock" || "Paper" || "Scissors")
{