Counter value is not increasing, value remains constant in javascript - javascript

why does my variable pc_score and my_score not increase? The output is 0.
I have two more functions of the eventListener format that I omitted from the code, but it should not affect the results. .
I edited the post for runnable code. Thank you.
Thanks for looking at my question.
<script>
var options = ['rock','paper','scissors']
let my_score = 0;
var pc_score = 0;
let computerChoice ;
function computerSelection() {
computerChoice = options[Math.floor(Math.random()*options.length)]
return computerChoice;
}
var results = document.getElementById("result")
document.getElementById("rock").addEventListener("click", ()=> {
playerChoice=rock;
computerSelection();
if (computerChoice=='rock'){
results.innerHTML="It is a tie";
} else if (computerChoice=='paper'){
results.innerHTML="It is a loss";
pc_score += 1;
}else if (computerChoice=='scissors'){
results.innerHTML="It is a win";
my_score+= 1
}
})
const you = document.getElementById("You")
you.innerHTML= my_score
const computer = document.getElementById("Computer")
computer.innerHTML=pc_score
</script>

Since you are assigning the value outside the event handler function that code does not get executed when click happens (instead those code is executed on page load with the initial value). You have to update the HTML inside the event handler function.
Also I will suggest you to use innerText or textContent if the text is plain text (not htmlString).
Try the following:
var my_score = 0;
var pc_score = 0;
const you = document.getElementById("You");
const computer = document.getElementById("Computer");
document.getElementById("scissors").addEventListener("click", ()=> {
playerChoice=scissors;
computerSelection();
if (computerChoice == "rock"){
results.textContent = "It is a loss";
pc_score++;
} else if (computerChoice == "paper"){
results.textContent = "It is a win";
my_score++;
}else if (computerChoice=="scissors"){
results.textContent = "It is a tie";
}
you.textContent = my_score;
computer.textContent = pc_score;
});

You are updating the score variables, but not the innerHTML's of the elements showing that score. There surely is a better/cleaner way to do this, but just call computer.innerHTML=pc_score and you.innerHTML= my_score again after changing the value

Related

How to use a while loop to prompt user until they enter 1 of 4 inputs

I'm stuck on how to get this while loop to function properly. I want the program to prompt the user with a question 'Rock, paper, or scissors?' to which they can correctly enter 'rock', 'paper', 'scissors', or 'bomb' (cheat code for auto-win... lol). If they type in anything other than those 4 acceptable inputs, an alert should appear. Then they should be prompted with the same question again. This should repeat until they enter one of those 4 acceptable inputs.
So far, it works if they type in their choice correctly the first time the prompt appears. However, if they type something other than the above 4 acceptable inputs, triggering the alert and the prompt in the while loop, the program does not run correctly even if they enter one of the 4 inputs the next time they are prompted. It gets stuck alternating between the alert and the prompt for eternity.
So how can I get this while loop to work?
function playGame () {
var input = prompt ('Rock, paper, or scissors?').toLowerCase();
// testing 123
// console.log (input);
var jkl = 0;
if (input === 'rock' || input === 'paper' || input === 'scissors' || input === 'bomb') {
jkl++
};
while (jkl === 0) {
alert ('ErRoR eRrOr 3rR0r!!!!11');
prompt ('Rock, paper, or scissors?').toLowerCase();
if (input === 'rock' || input === 'paper' || input === 'scissors' || input === 'bomb') {
jkl++
};
}
console.log (input);
var userChoice = getUserChoice (input);
var computerChoice = getComputerChoice ();
console.log (`You: ${userChoice}`);
console.log (`Computer: ${computerChoice}`);
console.log (determineWinner (userChoice, computerChoice));
};
playGame ();
After the attempted while loop there is more code that pertains to functions appearing earlier in the program. Ignore that I suppose. Unless anyone thinks it's relevant, in which case I can post that too. Just didn't want to paste a massive wall of code in here.
You can change this line
prompt ('Rock, paper, or scissors?').toLowerCase();
to
input = prompt ('Rock, paper, or scissors?').toLowerCase();
Your code is checking the input variable without updating it.
You need to update the input variable in the loop.
const options = ['rock', 'paper', 'scissors', 'bomb']
const getOptionPrompt = () => prompt('Rock, paper, or scissors?').toLowerCase();
const checkOption = (input, options) => options.includes(input)
function playGame() {
let input = getOptionPrompt();
// testing 123
// console.log (input);
var jkl = 0;
if (checkOption(input, options)) {
jkl++
};
while (jkl === 0) {
alert('ErRoR eRrOr 3rR0r!!!!11');
input = getOptionPrompt();
if (checkOption(input, options)) {
jkl++
};
}
console.log(input);
// the functions after this are not defined in the example
/*
var userChoice = getUserChoice(input);
var computerChoice = getComputerChoice();
console.log(`You: ${userChoice}`);
console.log(`Computer: ${computerChoice}`);
console.log(determineWinner(userChoice, computerChoice));
*/
};
playGame();
But I would definitely update the logic a bit:
const options = ['rock', 'paper', 'scissors', 'bomb']
const getOptionPrompt = () => prompt('Rock, paper, or scissors?')?.toLowerCase() || null;
const checkOption = (input, options) => options.includes(input)
function playGame(options) {
const input = getOptionPrompt();
if (!checkOption(input, options) && input != null) {
alert('ErRoR eRrOr 3rR0r!!!!11');
playGame(options)
} else if (input == null) {
console.log("game canceled")
} else {
console.log("result:", input)
}
};
playGame(options);
This way you don't need the jkl variable, no need for the while loop - if an answer is typed in that is not acceptable, then an error alert shows & the game starts anew.

Rock, Paper, Scissors using onclick function to populate player results

I'm currently working through a prep course for a bootcamp and the last assignment is to put some basic JavaScript functions into a rock, paper, scissors game. I'm stuck trying to finish this onclick function.
What is the best way to populate the users choice when they click the buttons?
I've currently got my choices defined and set-up in an array. So, I guess I'm trying to get the defined choices to equal the buttons pushed. If I'm thinking correctly I want ex: choices[1] to also be my "Papyrus" button. I've attempted const () =, but I get a no "initializer" warning.
UPDATED ONCLICK FUNCTION. Everywhere I looked and on my lessons it had function(e) with e.target.id and I changed the querySelector to querySelectorAll to grab all the buttons. But still not seeing the console.log output nor seeing the compareChoice results on the screen.
const firstChoice = "Lapis";
const secondChoice = "Papyrus";
const thirdChoice = "Scalpellus";
const choices = ['Lapis', 'Payrus', 'Scalpellus'];
player.currentChoice = document.querySelectorAll('button').onclick = function(e) {
console.log(e.target.id);
}
//Example of on of the choice outcomes
else if(computer.currentChoice === choices[0]){
if(player.currentChoice === choices[1]){
displayResults("The player wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
}else{
displayResults("The computer loses! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
I assume you have player Obj and multiple buttons where user can pick from
let player = {
currentChoice: ''
},
computer = {
computerSelection: ['Lapis', 'Payrus', 'Scalpellus'],
currentChoice: ''
};
const allButtons = document.querySelectorAll('button')
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', getUserSelection);
}
function compare() {
let playerChoice = player.currentChoice,
computerChoice = computer.currentChoice,
outcome = '';
if (playerChoice === computerChoice) {
outcome = 'draw';
} else if (playerChoice === 'Lapis' && computerChoice === 'Scalpellus' || (playerChoice === 'Papyrus' && computerChoice === 'Lapis') || (playerChoice === 'Scalpellus' && computerChoice === 'Papyrus')) {
outcome = 'You win';
} else {
outcome = 'You lose'
}
displayResults(outcome)
displayResults(`You picked ${playerChoice}`)
displayResults(`Computer picked ${computerChoice}`)
}
function getUserSelection(e) {
player.currentChoice = this.id;
// From here trigger a function that compares
// User slection against computers random selection
startTheFight();
}
function setComputerChoice() {
let random = Math.floor(Math.random() * (computer.computerSelection.length - 1)) + 1;
computer.currentChoice = computer.computerSelection[random];
}
function startTheFight() {
// Get a random selection
setComputerChoice();
compare();
}
function displayResults(result) {
const resultText = document.createElement('p');
resultText.innerText = result;
document.body.appendChild(resultText);
}
<button id="Lapis">
Lapis
</button>
<button id="Papyrus">
Papyrus
</button>
<button id="Scalpellus">
Scalpellus
</button>
Edit:In your case, can show the result ultimatium like in the example
The first thing I can see from your code is that you are not defining your onclick callback correctly.
You should use the addEventListener function instead, with the first parameter being the event you want to listen to ( "click" in your case ) and the second being your callback.
Note that the callback can take a parameter, which is the event.
document.querySelectorAll('button').addEventListener("click", function(event) {
// do something once the button is clicked.
});
A callback is just a function that will be executed at some point. And since you seams to be using the "Return value" of the callback in the rest of the code, it is not going to be executed properly. Take the example bellow.
const myButton = document.querySelector('#button');
let myVariable;
// proper way to define an event listener.
myButton.addEventListener('click', function(event) {
myVariable = "Some string";
});
console.log(myVariable); // will always be undefined.
<button id="button">Click me !</button>
Notice how the console always output undefined when you run the code ?
This is because, the callback and the rest of the code are not executed at the same time. Even though the console.log part comes after the callback, it is run at with the rest of the code, not when the callback is trigger. Only the code in the callback will be run when the event we listen to is triggered.
That being said, you can define variable outside the callback and use it inside. This could be useful to keep track of what each player has chosed.
With that in mind, you need to move the logic that check whether or not the player has won, in your callback.
document.querySelectorAll('button').addEventListener("click", function(event) {
if(player.currentChoice === choices[1]){
// player wins
} else {
// computer wins.
}
});
As for the populate the users choice part, you don't really need an external variable. You can simply listen to the click and get the player's choice using the event.target.id like you did previously. Then compare that with a predefined computer move.
Here is a somewhat working example.
const choices = ['Lapis', 'Payrus', 'Scalpellus'];
const allButtons = document.querySelectorAll('button');
// we register the listener on the `click` event, for each buttons.
for(let i = 0; i < allButtons.length; i ++) {
allButtons[i].addEventListener('click', function(event){
// we retrieve the player's choice from the id of the clicked button.
const playerChoice = event.target.id;
// we get a random id for the computer's move.
const randomChoiceId = Math.floor(Math.random() * choices.length);
const computerChoice = choices[randomChoiceId];
// we check if the player wins.
// I don't know the logic and comparing each element might
// not be the more efficient way to achieve this. But it works for now.
if(playerChoice === "Lapis" && computerChoice === "Payrus") {
console.log('Player Wins ! ');
} else {
console.log('Computer wins... ');
}
});
}
<button id="Lapis">Lapis</button>
<button id="Payrus">Payrus</button>
<button id="Scalpellus">Scalpellus</button>
Hopefully, this brief overview of callback was clear enough to help you go forward in your project. Good luck !

Javascript basic loop help - basic

Im learning Javascript now and I got a question that's been bugging me!
So, all I needed to do here is to type a color on this input box, click the button and change the headline to the color typed only if that typed color is in the array specified in the variable.
My code is half working... it does check if whatever color typed is inside the array, but the alert button pops up each time, is there a way to make the alert pop up only if the color typed isn't in the array please?
Working code: https://codepen.io/anon/pen/ddPWLP
Javascript code:
const myHeading = document.getElementById('myHeading');
const myButton = document.getElementById('myButton');
const myTextInput = document.getElementById('myTextInput');
var colors = ["red", "black", "blue"];
myButton.addEventListener('click', () => {
for (var i=0; i<colors.length; i++){
if (myTextInput.value === colors[i]){
myHeading.style.color = myTextInput.value
} else {
alert("no color")
}
}
});
Don't do it inside the loop. Use a variable to flag when you find a match, and then after the loop check that flag and display the alert accordingly. Try this:
myButton.addEventListener('click', () => {
var found = false;
for (var i = 0; i < colors.length; i++) {
if (myTextInput.value === colors[i]) {
myHeading.style.color = myTextInput.value
found = true;
}
}
if (!found)
alert("no color");
});
By the way, you don't need a loop for that. You can simply use the indexOf() methods. If the value exists in the array, it returns its index, otherwise it returns -1. Try this:
myButton.addEventListener('click', () => {
if (colors.indexOf(myTextInput.value) > -1)
myHeading.style.color = myTextInput.value
else
alert("no color");
});

Local variables giving global trouble

I'm a JS super n00b.
I asked about an aspect of this problem in this post (Puzzling behavior from IF ( ) statement) on IF statements but it looks like the actual issue is related to the scope of a variable I've created. It seems that after declaring (what I think is) a global variable, other functions in the code cannot access the variable.
I'm doing JS project/program that prompts a user to input a word and the program reverses the word input.
In the previous post (PP) a user correctly determined that I was getting the 'false' console message (see code) no matter what the length of the word input because I was assigning value the variable when the page loads but not reading it again when the user clicks the button on the page.
If the variable 'word' is local I'm only able to get a 'false' console message and when the variable 'word' is global I'm only able to get a 'ReferenceError.'
Any ideas anyone has are greatly appreciated.
See JS code below:
var word = document.getElementById('wordChoice').value;
var lttrs = [];
function flipFail () {
alert("Please enter a word of at least two characters.");
console.log(false);
var inputErrArr = ['has-error', 'has-feedback'];
var inputErrFdbk = ['glyphicon', 'glyphicon-remove'];
wordChoice.style.backgroundColor = "#FFDBAA";
for (var i = 0; i < inputErrArr.length; i ++) {
addClass(wordInput, inputErrArr[i]);
}
for (var i = 0; i < inputErrFdbk.length; i ++) {
addClass(glyph, inputErrFdbk[i]);
}
document.getElementById('wordChoice').value = " ";
} // END flipFail()
function flipSuccess (){
for (var i = 0; i < word.length; i ++) {
lttrs.push(word.charAt(i));
}
lttrs.reverse();
var reversedWord = lttrs.join('')
alert("Your reversed word is: " + reversedWord);
console.log(true);
document.getElementById("flip").innerHTML = "Flip Again!";
document.getElementById('wordChoice').value = " ";
} // EN flipSuccess ()
function flipChk () {
if (word.length < 2) {
flipFail ();
} else {
flipSuccess ();
}
}
See fully implemented code here: http://supsean.com/supsean/flipr/flipr.html
You need to set word in flipChk(). You're setting it when the page is first loaded, before the user has entered anything into the form, not when the user clicks on the Flip button.
Then, instead of using a global variable, pass it as an argument to the function. In general, avoid using global variables unless you really have to.
function flipChk () {
var word = document.getElementById('wordChoice').value;
if (word.length < 2) {
flipFail ();
} else {
flipSuccess (word);
}
}
function flipSuccess (word){
var lttrs = [];
for (var i = 0; i < word.length; i ++) {
lttrs.push(word.charAt(i));
}
lttrs.reverse();
var reversedWord = lttrs.join('')
alert("Your reversed word is: " + reversedWord);
console.log(true);
document.getElementById("flip").innerHTML = "Flip Again!";
document.getElementById('wordChoice').value = " ";
} // EN flipSuccess ()

JavaScript exercise issue

i'm a novice in this world...so trying to begin, I started with an online tutorial. The exercise it's simple, but i can´t get the "empate" text on screen if the condition exists. Can you help me to know whats wrong?:
var usuarioElige = prompt("piedra, papel o tijera?");
var computadoraElige = Math.random();
if (computadoraElige <= 0.34) {
computadoraElige = "piedra";
} else if(computadoraElige <= 0.67) {
computadoraElige = "papel";
} else {
computadoraElige = "tijera";
}
var comparar = function (usuarioElige,computadoraElige) {
if (usuarioElige === computadoraElige) {
return "¡Es un empate!";
}
};
You never call the function that prints out the "enpate" message. Try this version:
var usuarioElige = prompt("piedra, papel o tijera?");
var computadoraElige;
var d = Math.random();
if (d <=0.34){
computadoraElige = "piedra";
}else if(d <=0.67){
computadoraElige = "papel";
}else{
computadoraElige = "tijera";
}
var comparar = function (x,y){
if (x===y){
alert("¡Es un empate!");
}
};
comparar(usuarioElige, computadoraElige)
Note the added call to the function at the end and that I renamed the parameters of the comparar function to "x" and "y" to avoid confusion (it also works if you stay with the old name).
Another thing is that I put the random number for the computer in a separate variable. It can be confusing if the same variable means two different things depending on what part of the program you are on.
I also improved the whitespace indentation of your program. Programs are easier to understand if they are well indented :)
You're missing:
comparar(usuarioElige, computadoraElige);
At the end of the code

Categories

Resources