jQuery: Running a random number generator on button press - javascript

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/

Related

Tie result cannot be outputted

While creating the rock, paper, scissors application, I am tasked to output specific results in the console, such as outputting paper-paper and receive 'It's a tie' result. Well, I have tried to do that but for some reason, I cannot do so. The code is as below:
const user = userInput => {
userInput = userInput.toLowerCase();
if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
return userInput;
} else {
console.log('error');
}
}
function computer() {
random = Math.floor(Math.random() * 3);
switch(random){
case 0 : return 'rock';
break;
case 1 : return 'paper';
break;
default : return 'scissors';
}
};
const winner = () => {
const choice1 = user('rock');
const choice2 = computer();
if(choice1 === choice2) {
return 'It\'s a tie!';
}
if(choice1 === 'rock') {
if(choice2 === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if(choice1 === 'paper') {
if(choice2 === 'scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if(choice1 === 'scissors') {
if(choice2 === 'rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
}
console.log(winner('paper', 'paper'));
When I try to type console.log(winner('paper', 'paper')) for example, the result is random meaning that it can be either win, lost or tie due to the fact (or what I suppose is the reason) that the computer's choice is random but this is how I am asked to create the computer's choice. If I type console.log(('paper', 1)) I get the same result but somehow, the task is asking me to use console.log(winner('paper', 'paper')) and is telling me that the result should be a tie. I have also tried to let the user with no parameter in choice1 but I get an error due to the fact that there is no input in the user's choice.
The tasks are as below:
console.log(determineWinner('paper', 'scissors')); // prints something like 'The computer won!'
console.log(determineWinner('paper', 'paper')); // prints something like 'The game is a tie!'
console.log(determineWinner('paper', 'rock')); // prints something like 'The user won!'
Any help or idea would be appreciated. Thanks!
Something like this would work. If It is what you need.
const user = userInput => {
userInput = userInput.toLowerCase();
if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
return userInput;
} else {
console.log('error');
}
}
function computer() {
const random = Math.floor(Math.random() * 3);
switch(random){
case 0 : return 'rock';
break;
case 1 : return 'paper';
break;
default : return 'scissors';
}
};
// Here is where you need to change something
const determineWinner = (userChoice, computerChoice) => {
// And use the parameters here:
const choice1 = userChoice;
const choice2 = computerChoice;
if (choice1 === choice2) {
return 'It\'s a tie!';
}
if (choice1 === 'rock') {
if (choice2 === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if (choice1 === 'paper') {
if (choice2 === 'scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if (choice1 === 'scissors') {
if (choice2 === 'rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
};
const userInput = 'rock';
console.log(determineWinner(user(userInput), computer()));
console.log(determineWinner('rock', 'paper'));
console.log(determineWinner('paper', 'paper'));
// For you requirement:
console.log(determineWinner('paper', 'scissors'));
console.log(determineWinner('paper', 'paper'));
console.log(determineWinner('paper', 'rock'));
But if you hardcode the parameters as you requirement suggests then your functions user and computer are not used.

How to fix undefined variable in 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);

ReferenceError: prompt is not defined - Rock, Paper, or Scissors

I am experiencing some issues to finish this code.
ReferenceError: prompt is not defined
at Object. //(/home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:1:80) this is the first error, I tried not to use prompt, and just calling the code at the end, but I need some advice on what is the best practice for that.
Could someone give tips to improve this code?
let userPrompt = prompt("enter a choice: ");
const getUserChoice = userPrompt => {
if (userInput === 'rock' || userInput === 'Paper' || userInput === 'scissors') {
return userInput;
} else {
console.log('Error');
}
}
const randomNumber = 'Math.floor(Math.random() * 3)';
switch (randomNumber) {
case 0:
return 'rock';
// I don't know if I have to have a break here.
case 1:
return 'Paper';
case 2:
return 'scissors';
case 3:
return 'bomb';
}
console.log(getUserChoice());
function determineWinner(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return 'the game is a tie';
}
if (userChoice === 'bomb') {
return 'You won!'; /* add a fourth condition that checks if the userInput is 'bomb'.At the beginning of determineWinner(), add another if statement that makes the user win if the userChoice is 'bomb'.*/
}
if (userChoice === 'rock') {
if (computerChoice === 'paper') {
return 'The computer won!';
} else {
return 'You won!';
}
} else if (userChoice === 'Paper') {
if (computerChoice === 'rock') {
return 'The user won';
} else {
return 'The computer won';
}
} else if (userChoice === 'Scissors') {
if (computerChoice === 'Paper') {
return 'The user won';
} else {
return 'The computer won';
}
}
}
console.log(determineWiner('rock', 'paper'));
console.log(determineWiner('paper', 'rock'));
console.log(determineWiner('scissors', 'paper'));
const playGame = () => {
const userChoice =
getUserChoice('scissors');
const computerChoice =
getComputerChoice();
console.log(`you threw: ${userChoice}`);
console.log(`The computer threw: ${computerChoice}`);
console.log(determineWinner(userChoice, computerChoice));
};
playgame();

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();
}

Javascript not running - no error message

I've set up this rock, paper scissors game. However, the Javascript is not running and I'm not receiving any errors. Any suggestions?
function play(humanScore) {
var computerScore = getcomputerScore();
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
human++
} else if (computerScore == "paper") {
computer++
}
} else if (humanScore == "scissors") {
if (computerScore == "scissors") {
} else if (computerScore == "paper") {
human++
} else if (computerScore == "rock") {
computer++
}
} else if (humanScore == "paper") {
if (computerScore == "paper") {
} else if (computerScore == "scissors") {
computer++
} else if (computerScore == "rock") {
human++
}
}
}
function getcomputerScore() {
var randomplay = ["rock", "paper", "scissors"];
var play = randomplay[Math.floor(Math.random() * myArray.length)];
return play
}
This is the code setting up humanScore:
var human = 0;
var computer = 0;
document.getElementById("rock").onClick = pickRock;
document.getElementById("scissors").onClick = pickScissors;
document.getElementById("paper").onClick = pickPaper;
function pickRock() {
play("rock");
}
function pickScissors() {
play("scissors");
}
function pickPaper() {
play("paper");
}
The name of the property is onclick, not onClick; note the lowercase c.
There’s at least one other error (myArray.length, as #RobG points out), but this will make them actually throw.
Probably better suited to a code review section, but here goes…
function play(humanScore) {
var computerScore = getcomputerScore();
variables humanScore and computerScore aren't actually scores, they are symbols the players have chosen to play, so the variables might be better as humanChoice and computerChoice. This also means that the globals human and computer can be better named as humanScore and computerScore.
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
Rather than leaving a blank block, better to either insert a comment to say "no adjustment". Better to test equivalent choices up front, then you're left with binary choices, so you can do something like:
var humanScore = 0;
var computerScore = 0;
function play(humanChoice) {
// IE tends to play with capitalisation of values
humanChoice = humanChoice.toLowerCase();
var computerChoice = getComputerChoice();
// If same choice, no change of score
if (computerChoice == humanChoice) {
return;
}
// Only binary win/lose choices left
if (humanChoice == 'rock') {
computerChoice == 'paper'? ++computerScore : ++humanScore;
} else if (humanChoice == 'paper') {
computerChoice == 'scissors'? ++computerScore : ++humanScore;
} else if (humanChoice == 'scissors') {
computerChoice == 'rock'? ++computerScore : ++humanScore;
}
}
There was an error in this function too:
function getComputerChoice() {
var choices = ['rock','paper','scissors'];
return choices[Math.random()*choices.length | 0];
}
Lastly, make sure the buttons are in the page before adding the listener, and make sure the property names have the correct case (it doesn't matter for HTML attributes, but it does for javascript property names):
window.onload = function() {
document.getElementById("rock").onclick = pickRock;
document.getElementById("scissors").onclick = pickScissors;
document.getElementById("paper").onclick = pickPaper;
}

Categories

Resources