How to fix undefined variable in javascript - javascript

For some reason my function is not returning a 1 or 2 even though it's specifically setup to do so. What am I doing wrong? I'm looking at the chrome dev tools and it's telling me that var processed is undefined.
I'm quite stumped on this. I've been reading if it's because a variable could be used as a parameter but I'm not sure if this is the case
var processChoices = function (player, computer){
switch (player) {
case player == 'rock':
if (computer == 'paper'){
var winner = 2;
} else if (computer == 'scissors'){
var winner = 1;
}
break;
case player == 'paper':
if (computer == 'scissors'){
var winner = 2;
} else if (computer == 'rock'){
var winner = 1;
}
break;
case player == 'scissors':
if (computer == 'rock'){
var winner = 2;
} else if (computer == 'paper'){
var winner = 1;
}
break;
default:
if (computer == player){
var winner = console.log('We have a tie, go again!');
}
break;
}
return winner
}
var determineWinner = function (){
var computer = computerPlay();
var player = playerChoice();
var processed = processChoices(player, computer);
if (processed == 1){
playerCount += 1;
} else {
computerCount += 1;
}
var message = (processed == 2) ? `The computer wins! ${computer} beats ${player}!` : `The player wins! ${player} beats ${computer}!`;
console.log(message);
}
I'm expecting the output of var processed to be 1 or 2. It's coming back as undefined.

It looks like you're not using the switch statement correctly. Your case statements need to just be the value that you want to match. See below.
It's would also be good to declare the variable winner once.
var processChoices = function(player, computer) {
var winner = 0;
switch (player) {
case 'rock':
if (computer == 'paper') {
winner = 2;
} else if (computer == 'scissors') {
winner = 1;
}
break;
case 'paper':
if (computer == 'scissors') {
winner = 2;
} else if (computer == 'rock') {
winner = 1;
}
break;
case 'scissors':
if (computer == 'rock') {
winner = 2;
} else if (computer == 'paper') {
winner = 1;
}
break;
default:
if (computer == player) {
console.log('We have a tie, go again!');
}
break;
}
return winner
}
var computer = "rock";
var player = "paper";
console.log("Player chose:", player, "Computer chose:", computer);
console.log("The winner is...", processChoices(player, computer));

First off the switch format is wrong.
switch (player) {
case player == 'rock': // wrong
case 'rock': // correct
Second you need to check all states of computer or else check at the end
var processChoices = function (player, computer){
let winner = 0;
switch (player) {
case 'rock':
if (computer === 'paper'){
winner = 2;
} else if (computer === 'scissors'){
winner = 1;
}
break;
case 'paper':
if (computer === 'scissors'){
winner = 2;
} else if (computer === 'rock'){
winner = 1;
}
break;
case 'scissors':
if (computer === 'rock'){
winner = 2;
} else if (computer === 'paper'){
winner = 1;
}
break;
}
if (winner === 0) {
console.log('We have a tie, go again!');
}
return winner
}
ps:
use const and let. Don't use `var'
use === not ==
Also the entire thing can be a lot smaller
const winnerTable = {
rock: {
rock: 0,
paper: 2,
scissors: 1,
},
paper: {
rock: 1,
paper: 0,
scissors: 2,
},
scissors: {
rock: 2,
paper: 1,
scissors: 0,
},
};
var processChoices = function (player, computer){
return winnerTable[player][computer];
};

well I guess it's in var determineWinner u called
var processed = processChoices(player, computer);
and processChoices is a var not a function with parameters
=>delete (player, computer);

Related

Ternary Condition for if { } else if { if { } else { } }

I want to change all the if else statements to ternary operator. Whats the ternary operator for this if else statements ?
const compareHands = (playerChoice, computerChoice) => {
// Update Text
const winner = document.querySelector('.winner');
const winnerIs = (who, isPlayerWin) => {
winner.textContent = `${who} Wins!`;
isPlayerWin ? pScore++ : cScore++;
updateScore();
};
// Check for tie
if (playerChoice === computerChoice) {
winner.textContent = 'It Is A Tie!';
// Check For Winner
} else if (playerChoice === 'rock') {
if (computerChoice === 'scissors') {
winnerIs('Player', true);
} else {
winnerIs('Computer', false);
}
} else if (playerChoice === 'paper') {
if (computerChoice === 'scissors') {
winnerIs('Computer', false);
} else {
winnerIs('Player', true);
}
} else if (playerChoice === 'scissors') {
if (computerChoice === 'rock') {
winnerIs('Computer', false);
} else {
winnerIs('Player', true);
}
}
}
Honestly, I don't think the use of ternary operator will make the code better.
I suggest the you try to reduce the if-else chain by creating a data structure for easy look up, something like this:
const whatBeats = {
'scissors': 'rock',
'paper': 'scissors',
'rock': 'paper'
};
const compareHands = (playerChoice, computerChoice) => {
// Update Text
const winner = document.querySelector('.winner');
const winnerIs = (who, isPlayerWin) => {
winner.textContent = `${who} Wins!`;
isPlayerWin ? pScore++ : cScore++;
updateScore();
};
// Check for tie
if (playerChoice === computerChoice) {
winner.textContent = 'It Is A Tie!';
// Check For Winner
} else if (playerChoice === whatBeats[computerChoice]) {
winnerIs('Player', true);
} else {
winnerIs('Computer', false)
}
}
In this case, we are treating the game dynamics as data, centralizing it on one place.
For the next questions, try to solve the problem before (there are tons of tutorial regarding ternary operators).
Try like this. Though readability is a problem since there are too many nested if else which is replaced by ternary operator. true & false are replace with !0 & !1 respectively to shorten the statement
playerChoice === computerChoice ?
winner.textContent = "It Is A Tie!" :
"rock" === playerChoice ?
"scissors" === computerChoice ?
winnerIs("Player", !0) :
winnerIs("Computer", !1) :
"paper" === playerChoice ?
"scissors" === computerChoice ?
winnerIs("Computer", !1) :
winnerIs("Player", !0) :
"scissors" === playerChoice && ("rock" === computerChoice ? winnerIs("Computer", !1) :
winnerIs("Player", !0));
As Nina Scholz says, I would not use either. I know this does not answer the literal question, but how about this instead?
const loser_to = {
paper: 'rock',
rock: 'scissors',
scissors: 'paper'
};
if (loser_to[playerChoice] === computerChoice) {
// player wins
} else if (loser_to[computerChoice] === playerChoice) {
// computer wins
} else {
// noone wins
}
Using too many ternary could lead to unreadable code. I suggest you can use switch case combining with ternary operators.
switch (playerChoice) {
case computerChoice: winner.textContent = 'It Is A Tie!';break;
case 'rock': computerChoice === 'scissors' ? winnerIs('Player', true) : winnerIs('Computer', false); break;
case 'paper': computerChoice === 'rock' ? winnerIs('Player', true) : winnerIs('Computer', false); break;
case 'scissors': computerChoice === 'paper' ? winnerIs('Player', true) : winnerIs('Computer', false); break;
}
If you want a much more DRYied code. You could try this solution to avoid multiple call of winnerIs function.
const compareHands = (playerChoice, computerChoice) => {
const winner = document.querySelector('.winner');
if (playerChoice == computerChoice) {
winner.textContent = 'It Is A Tie!';
return;
}
let choices = ['rock', 'paper', 'scissor'];
let playerIndex, computerIndex, isPlayerWin;
playerIndex = choices.indexOf(playerChoice);
choices.push(choices.shift());
computerIndex = choices.indexOf(computerChoice);
isPlayerWin = playerIndex !== computerIndex;
winner.textContent = `${isPlayerWin ? 'Player' : 'Computer'} Wins!`;
isPlayerWin ? pScore++ : cScore++;
updateScore();
}

How to compare two different values after they have been changed already?

I am creating a rock paper scissors game, I’m using buttons that the user can choose from to either select rock paper or scissors, but I don’t know how to compare the results of the user’s answer and the computer’s answer to find out who won.
number = Math.floor(Math.random()*6)+1;
function results(){
switch(number){
case 6: case 5: var a = document.getElementById("computer").innerHTML="Rock";
break;
case 4: case 3: var b = document.getElementById("computer").innerHTML="Paper";
break;
case 2: case 1: var c = document.getElementById("computer").innerHTML="Scissors";
break;
}
}
function paper(){
switch(true){
case (number <= 6): var paper = document.getElementById("user").innerHTML="Paper";
break;
}
}
function rock(){
switch(true){
case (number <= 6): var rock = document.getElementById("user").innerHTML="Rock";
break;
}
}
function scissors(){
switch(true){
case (number <= 6): var rock = document.getElementById("user").innerHTML="Scissors";
break;
}
}
You need only one function which will trigger when user click on any of options, then in same function you produce a choice for computer and then based on them figure out the winner. check the example below :
HTML :
<div id="c"></div>
<div id="u"></div>
<div id="r"></div>
// send parameter to function, 1 for Rock, 2 for Paper and 3 for Scissors
<button onclick="startg(1)">
Rock
</button>
<button onclick="startg(2)">
Paper
</button>
<button onclick="startg(3)">
Scissors
</button>
Java script :
function startg(userChoice){
document.getElementById("u").innerHTML="";
document.getElementById("c").innerHTML="";
document.getElementById("r").innerHTML="";
var comNumber = Math.floor(Math.random()*3)+1;
switch (userChoice){
case 1 : {
document.getElementById("u").innerHTML="You Choosed : Rock";
break;
}
case 2 : {
document.getElementById("u").innerHTML="You Choosed : Paper";
break;
}
case 3 : {
document.getElementById("u").innerHTML="You Choosed : Scissors";
break;
}
}
switch (comNumber){
case 1 : {
document.getElementById("c").innerHTML="Compouter Choosed :Rock";
break;
}
case 2 : {
document.getElementById("c").innerHTML="Compouter Choosed :Paper";
break;
}
case 3 : {
document.getElementById("c").innerHTML="Compouter Choosed :Scissors";
break;
}
}
//Results :
if (userChoice == 1 && comNumber==2)
document.getElementById("r").innerHTML="Result : Computer Win!";
else if (userChoice == 2 && comNumber==1)
document.getElementById("r").innerHTML="Result : You Win!";
else if (userChoice == 1 && comNumber==3)
document.getElementById("r").innerHTML="Result : You Win!";
else if (userChoice == 3 && comNumber==1)
document.getElementById("r").innerHTML="Result : Computer Win!";
else if (userChoice == 2 && comNumber==3)
document.getElementById("r").innerHTML="Result : Computer Win!";
else if (userChoice == 3 && comNumber==2)
document.getElementById("r").innerHTML="Result : You Win!";
else if (userChoice == comNumber)
document.getElementById("r").innerHTML="Result : Draw";
}
You can see a working example here : https://jsfiddle.net/emilvr/wpkj6rw6/4/

Javascript function only seeing default values on global variables passed in as argument

Disclaimer: I'm fairly new to Javascript so I'm guessing I'm either doing something wrong, or misunderstanding how this works.
I have two variables with a default value of 0, which are later changed by a couple of functions.
var userAnswerContainer = 0;
var computerAnswerContainer = 0;
function userInput() {
userAnswerContainer = prompt("Please choose either Rock, Paper, or Scissors:").toLowerCase();
switch (userAnswerContainer) {
case "rock":
break;
case "paper":
break;
case "scissors":
break;
default:
alert(userAnswerContainer + " is not a valid answer.");
userInput();
}
}
function computerInput() {
computerAnswerContainer = Math.floor(Math.random() * 9);
if (computerAnswerContainer <= 3) {
computerAnswerContainer = "rock";
} else if (computerAnswerContainer >= 4 && computerAnswerContainer <= 6) {
computerAnswerContainer = "paper";
} else {
computerAnswerContainer = "scissors";
}
}
After these variables are changed, I'm passing them in as an argument for a separate function (on a rock, paper, scissors game) however the function seems to only be seeing the original values of the variables.
function gameStartV2(y, c) {
userInput();
computerInput();
alert(computerAnswerContainer + " / " + userAnswerContainer);
/*Testing: Displays values of AnswerContainers applied by respective functions*/
if (c === y) {
alert("You chose " + y + ". Computer chose " + c + ". It's a tie!");
} else if (c === "rock") {
if (y === "paper") {
alert("Paper covers rock, you win!");
userScore++;
} else {
alert("Rock smashes scissors, you lose!");
computerScore++;
}
compareScore();
} else if (c === "scissors") {
if (y === "rock") {
alert("Rock smashes scissors, you win!");
userScore++;
} else {
alert("Scissors cuts paper, you lose!");
computerScore++;
}
} else if (c === "paper") {
if (y === "rock") {
alert("Paper covers rock, you lose!");
computerScore++;
} else {
alert("Scissors cuts paper, you win!");
userScore++;
}
} else {
alert("Error, please try again.");
}
compareScore();
}
gameStartV2(userAnswerContainer,computerAnswerContainer);
If I run a check on the variables inside of the argument function, I can see that they are indeed holding the values from the changing functions, however the if/else statement is still only seeing 0. What's happening here?
Jfiddle: https://jsfiddle.net/Spiderpiggie/ucuzry8p/9/
You never update your values:
function gameStartV2() {
userInput();
computerInput();
y = userAnswerContainer;
c = computerAnswerContainer;
Change it to this and it should work as intended.
In your code the script always works with the original values that were supplied to the function (0 and 0).
You don't even need to provide gameStartV2 with the values from userAnswerContainer and computerAnswerContainer
Made some improvements here below, take a peak!
var userAnswerContainer = 0;
var computerAnswerContainer = 0;
var userScore = 0;
var computerScore = 0;
function userInput() {
var userAnswerContainer = prompt("Please choose either Rock, Paper, or Scissors:").toLowerCase(); //use var to keep it within the scope of this function.
switch (userAnswerContainer) {
case "rock":
break;
case "paper":
break;
case "scissors":
break;
default:
alert(userAnswerContainer + " is not a valid answer.");
userInput();
}
return userAnswerContainer;
}
function computerInput() {
var computerAnswerContainer = Math.floor(Math.random() * 9); //use var to keep it within the scope of this function.
if (computerAnswerContainer <= 3) {
computerAnswerContainer = "rock";
} else if (computerAnswerContainer >= 4 && computerAnswerContainer <= 6) {
computerAnswerContainer = "paper";
} else {
computerAnswerContainer = "scissors";
}
return computerAnswerContainer; //use return to set the variable to computerAnswerContainer
}
function gameStartV2() {
c = userAnswerContainer = userInput(); //set the global and c
y = computerAnswerContainer = computerInput(); //set the global and y
alert(computerAnswerContainer + " / " + userAnswerContainer);
/*Testing: Displays values of AnswerContainers applied by respective functions*/
if (c === y) {
alert("You chose " + y + ". Computer chose " + c + ". It's a tie!");
} else if (c === "rock") {
if (y === "paper") {
alert("Paper covers rock, you win!");
userScore++;
} else {
alert("Rock smashes scissors, you lose!");
computerScore++;
}
} else if (c === "scissors") {
if (y === "rock") {
alert("Rock smashes scissors, you win!");
userScore++;
} else {
alert("Scissors cuts paper, you lose!");
computerScore++;
}
} else if (c === "paper") {
if (y === "rock") {
alert("Paper covers rock, you lose!");
computerScore++;
} else {
alert("Scissors cuts paper, you win!");
userScore++;
}
} else {
alert("Error, please try again.");
}
compareScore();
}
function compareScore()
{
alert("the score is you: " + userScore + " vs. computer: " + computerScore);
}
gameStartV2(userAnswerContainer,computerAnswerContainer);
"y" and "c" are copies by value from the original values passed to the function. Remove the arguments and just use the actual variables, or create local var copies inside your gameStartV2 function, but after you've invoked your modifier functions.
function gameStartV2() {
var y = userInput();
var c = computerInput();
var r;
alert("Testing Check " + c + " / " + y);
/*Testing: Displays values of AnswerContainers applied by respective functions*/
if (y === c) {
alert("You chose " + y + ". Computer chose " + c + ". It's a tie!");
} else {
r = y + c;
switch (r) {
case "paperrock":
alert("Paper covers rock, you win!");
userScore++;
break;
case "paperscissors":
alert("Scissors cuts paper, you lose!");
computerScore++;
break;
case "rockpaper":
alert("Paper covers rock, you lose!");
computerScore++;
break;
case "rockscissors":
alert("Rock smashes scissors, you win!");
userScore++;
break;
case "scissorspaper":
alert("Scissors cuts paper, you win!");
userScore++;
break;
case "scissorsrock":
alert("Rock smashes scissors, you lose!");
computerScore++;
break;
default:
alert("Error, please try again.");
}
}
compareScore();
}

jQuery: Running a random number generator on button press

I've created a rock, paper, scissors game to learn JS and jQuery with. What I'm trying to figure out is how to call the same function on button click, so that the number will change, giving a different result for the game.
I've made a jsFiddle demo for this here:
https://jsfiddle.net/iKaleb/v1kbxg2g/3/
Essentially, in the fiddle example, I'd like to click the blue box and the computers choice would change every time. compChoice() is the random number generator, but when I call it again by clicking the button, it doesn't change the computers choice.
Any help with this will be greatly appreciated!
var player = "Rock";
var computer = compChoice();
function compChoice() {
var compMath = Math.floor(Math.random() * 3) + 1;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
return pick;
}
function vsChoice() {
if (player === "Rock") {
if (computer === "Scissors") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Paper") {
if (computer === "Rock") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Scissors") {
if (computer === "Paper") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
}
$('#box').on('click', function() {
console.log("Players Choice: " + player);
console.log("Computer Choice: " + computer);
vsChoice();
});
I just edited your js and it is working for me
function compChoice() {
compMath = Math.floor(Math.random() * 3) + 1;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
return pick;
}
function compChoice() {
var compMath = Math.floor(Math.random() * 3) + 1;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
return pick;
}
function vsChoice() {
if (player === "Rock") {
if (computer === "Scissors") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Paper") {
if (computer === "Rock") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Scissors") {
if (computer === "Paper") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
}
$('#box').on('click', function() {
player = compChoice();
computer = compChoice();
console.log("Players Choice: " + player);
console.log("Computer Choice: " + computer);
vsChoice();
});
You need to call function that generates the choice instead of showing the same value every time:
$('#box').on('click', function() {
computer = compChoice();
console.log("Players Choice: " + player);
console.log("Computer Choice: " + computer);
vsChoice();
});
Note that it would be better to pass choice as parameters to vsChoice function instead of using global variables.
Your Mistake is
You are printing initial computed value.
Try like this
$('#box').on('click', function() {
console.log("Players Choice: " + player);
console.log("Computer Choice: " + compChoice());
vsChoice();
});
OR
Refreshing your computed value computer var
function compChoice() {
var compMath = Math.floor(Math.random() * 3) + 1;
debugger;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
computer = pick;
return pick;
}
JSFiddle :
https://jsfiddle.net/v1kbxg2g/7/

Using text box info as variable in Javascript?

So, I'm making a rock,paper,scissors game using Javascript and I'm having some trouble starting. I need to have a text box and submit button, then the user input of "rock", "paper", "scissors" will be played against the computer's random choice. How would I have the computer take what's entered into the text field and run it against the computers choice? I'm a novice and in need of a nudge in the right direction, because I'm not sure how to start this problem.
Thanks
Edit:
So, a friend sent me some code and I added onto some of it and it looks like it would work(at least to me), but I'm not sure what to set the variable "player" equal to in order to equal the textbox information.
var player =
var choices = ["rock","paper","scissors"];
var computer = choices[Math.floor(Math.random()*3)];
var win = "Your "+player+" beats "+computer+". You win.";
var lose = "Your "+player+" loses to "+computer+". You lose.";
var draw = "A draw: "+player+" on "+computer+".";
if(player === "rock"){
if(computer === "scissors"){
result = win;
alert="win";
}
else if(computer === "paper"){
result = lose;
alert="lose";
}
else if(computer === "rock"){
result = draw;
alert="draw";
}
}
else if(player === "paper"){
if(computer === "rock"){
result = win;
alert="win";
}
else if(computer === "scissors"){
result = lose;
alert="lose";
}
else if(computer === "paper"){
result = draw;
alert="draw";
}
}
else if(player === "scissors"){
if(computer === "paper"){
result = win;
alert="win";
}
else if(computer === "rock"){
result = lose;
alert="lose";
}
else if(computer === "scissors"){
result = draw;
alert="draw";
}
}
</script>
</head>
<body>
<form>
<input type="text" id="rockTextInput" size="100" placeholder="Rock, Paper, or Scissors" >
<input type="button" id="Button" value="Play Hand">
</form>
</body>
</html>
The computer's choice could be generated like this:
...
var plays = ["rock", "paper", "scissors"];
var rand = Math.round(Math.random() * 2);
alert("Computer played: " + plays[rand]);
//Check to see the winner
...
Hope that helps give you a start.
Due to the limited number of possibilities, a way to do it is with a look-up table. You'd have to use further JavaScript to link it to your HTML. For that you'll probably want to use document.getElementById with an <input>'s value and output to some other Element.
/*
Usage:
play(player_choice)
player_choice String, 'rock', 'paper' or 'scissors'
returns Object with properties
player String, player's choice
ai String, ai's choice
result Integer, 0 - lose, 1 - draw, 2 - win
resultText String, description of result
*/
var play = (function () {
var options = ['rock', 'paper', 'scissors'],
result_table = {
'rock': {
'rock': 1,
'paper': 0,
'scissors': 2
},
'paper': {
'rock': 2,
'paper': 1,
'scissors': 0
},
'scissors': {
'rock': 0,
'paper': 2,
'scissors': 1
}
},
result_text = ['AI wins', 'Draw', 'Player wins'];
return function (player_choice) {
var ai_choice;
player_choice = player_choice.toLowerCase();
if (!result_table.hasOwnProperty(player_choice)) {
throw '[' + player_choice + '] not a valid choice.';
}
ai_choice = options[Math.floor(Math.random() * options.length)];
return {
'player': player_choice,
'ai': ai_choice,
'result': result_table[player_choice][ai_choice],
'resultText': result_text[result_table[player_choice][ai_choice]]
};
};
}());

Categories

Resources