Generate and compare random numbers(in a game) - javascript

**I'm stuck on this part of my code, I want to generate a random number and compare it to the number who selected the player and depending on the result give a message **
this is a picture of the program
let butons=document.querySelectorAll(".btn");
let result=document.getElementById('result');
let eleccionPc=document.getElementById('elP');
let eleccionPlayer=document.getElementById('elPlayer');
butons.forEach((button)=>{
button.addEventListener('click',()=>{
eleccionPc.textContent=Math.floor(Math.random()*3)+1;
if(button.textContent==='1' < eleccionPc.textContent) {
eleccionPlayer.textContent='1';
result.textContent='You are Loser';
}
else if (button.textContent==='3' > eleccionPc.textContent) {
eleccionPlayer.textContent='3';
result.textContent='You win MotherFucker';
}
/*else if (button.textContent=="2" > eleccionPc.textContent ){
}*/
})
})
PD:I still don't know how to make a decent publication

The problem is in the if statement, you need to use && in the if statement
if(button.textContent === '1' && button.textContent < eleccionPc.textContent)
else if (button.textContent === '3' && button.textContent > eleccionPc.textContent)
This will solve the problem, If you have any question just ask me

this doesn't make any sense:
button.textContent==='1' < eleccionPc.textContent
the first half of the statement returns with "true" or "false" and then tries to see if that is less than a number?
Maybe you mean this?
button.textContent < eleccionPc.textContent

Related

check if an input is of this form

I have a code where the user enters multiple strings and I store them in an array, then I want to check if all the inputs are valid.
An input valid is a number with the same character repeated 3 times.
For example : '333', '999', '222', ...
What I have tried :
let valid = true;
inputs.forEach((input) => {
if (input.length !== 3 || isNaN(input)) {
valid = false;
} else {
const first = input[0];
for (let i = 1; i < 3; i++) {
console.log(first,input[i])
if (input[i] !== first) {
valid = false;
}
}
}
});
console.log(valid);
this code is working and I want to know if can I do better it seems like I used too much code for this simple task and I want to know if there is a simpler code when I searched in the interned they suggest rejex but this is so complicated for me thank you for helping me
First of all for a beginner your solution is good and correct congrats however you can optimize it and make it simpler
you can use every instead of forEach there is no need to check all the inputs once you find an invalid one
instead of loop through the input you can check if it is not divisible by 111 ;)
if(parseInt(input) % 111 !== 0) valid = false;
You could use Array#every.
let valid = inputs.every(s => s.length === 3 && !isNaN(s)
&& [...s].every(c => c === s[0]));
This could be shortened with a regular expression:
let valid = inputs.every(s => /^(\d)\1{2}$/.test(s));

How to give "No more tries left" in a password-guessing loop

I've just started learning JS and I got stuck here.
What I need to do:
If you don't enter the correct password, you get the message "Try again".
If you don't enter the password 3 times, you get the message "No more tries left".
If you enter the correct password, you get the message "You may enter".
Here's my code:
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
if ( password.toUpperCase() !== "BINGO" ) {
alert("Try again")
} else if ( i = 0 ) {
alert("No more tries left")
} else {
alert("You may enter")
}
}
I can't get it work properly as the message "No more tries left" doesn't show up. I know ( i = 0 ) is wrong but I don't know how to make it work.
Firstly, make sure that you're not using an assignment operator when you check if i == 0. You're currently using i = 0, which doesn't check if the two are equal as much as it assigns the left to the right. No bueno.
Secondly, your for loop is off just by a bit. It'll never get to 0 because you've asked it to loop while i > 0, not i >= 0. But wait - if you use i >= 0, it'll loop four times. That's not what you want either. We'll compromise and loop three times, but check if i == 1 instead of 0.
Here's my corrected code that works:
// loop three times
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
// if it's the correct answer then alert and break the loop
if ( password.toUpperCase() == "BINGO" ) {
alert("You may enter")
break
// if it's not, and the tries has elapsed, then alert and break the loop
} else if ( i == 1 ) {
alert("No more tries left")
break
// if it's not but the tries have not elapsed, then loop again
} else {
alert("Try again")
}
}
Try this.
for ( let i = 3; i >= 0; i-- ) {
if (i===0){
alert("No more tries left");
break;
}
let password = prompt("What is the password?")
if ( password.toUpperCase() !== "BINGO" ) {
alert("Try again")
} else {
alert("You may enter")
}
}
Give the user chance to enter the password 3 times but loop 4 times and check if the loop runs for 4th times(i === 0). if prompt No more tries left and break the loop.
You are using an assignment operator instead of a comparison operator.
Change this:
else if ( i = 0 ) {
alert("No more tries left")
}
To this :
else if ( i == 0 ) {
alert("No more tries left")
}
Try this. It will run the loop until they have entered the password correctly or the number of attempts is 3.
After the loop you can then just check if valid is true or false.
let valid = false;
let attempts = 0;
do
{
const password = prompt('What is the password');
valid = password.toUpperCase() === 'BINGO';
if (!valid && attempts < 2)
{
alert('Try again');
}
attempts++;
} while (!valid && attempts < 3)
if (valid)
{
alert('You may enter');
} else
{
alert('No more tries left');
}
You are asking the user to enter the password in each iteration
using a loop. So, showing that "you don't have anymore attempt left"
is useless here. Because if the value is greater than 3, the
instruction inside the loop will not be executed.
Do not use JavaScript for authentication. It is a client side
programming language and any one who knows how things work can
extract the password. Instead use a back-end language for
authentication such as PHP, Node.js
But if you only want to know about it just for the learning purpose
not because you wanna implement it, the below code will help you
for (let i=0; i<3; i++){
let password = prompt("what is the password: ");
if (password.toUpperCase() != "BINGO"){
alert("Try Again!");
}else{
alert("You may enter!");
i=3;
}
}
There are several ways you can do the "No more attempt left" is, one of the simple and basic is:
<input type="button" value="Enter Code" onclick="checkMe()">
<script>
let i=0;
function checkMe(){
if (i<3){
let password = prompt("Enter password!");
if (password.toUpperCase() != "BINGO"){
alert("Try Again! Attempt "+ (++i));
}else{
alert("You may enter!");
i=3;
}
}else alert("No more attempts left");
}
</script>
The above code can be implemented using input field, as i said, there are several ways. Hope it helps!
Your code is fine, what goes wrong is that it does not fall into the if condition (i == 0), because the loop only runs while i > 0,
just need to adjust like this:
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
if (password.toUpperCase() !== "BINGO" && i > 1 ) {
alert("Try again")
} else if (i == 1 && password.toUpperCase() !== "BINGO") {
alert("No more tries left")
} else {
alert("You may enter")
i = 0
}
}

Loops and counting

I want to make it so when someone answers the prompt they can answer a number 1 through 6 and to exit to just enter 0. After that I want them to be able to enter a number and that number will be correlated to an image or a link. Example: I have 3 different kinds of candy and I want 1 to be skittles, 2 to be m&ms, and 3 to be jolly ranchers. When the user enters 1 they will have an image come up that is skittles, and when they enter 2 an image of m&ms will come up. This is the code I have so far. If anyone could help me I would greatly appreciate it!
var stop = '0'
while(true) {
var input = prompt('Give a number 1 through 6. Type 0 to exit.');
if(input === stop){
break;
}
}
You can have an array of image urls and select any of them by the number the user has entered.
var images = ['xxx.jpg','yyy.jpg', 'zzz.jpg']
var stop = '0'
while(true) {
var input = prompt('Give a number 1 through 6. Type 0 to exit.');
if(input === stop){
break;
}
else{
if (!IsNaN(input) && images.length >= input)
showImage(images[input - 1]); //a mock function
}
}
I would approach your problem like this. Just catch the input and process it inside your while loop.
var pictures = [...] // array of pictures
while(true){
var input = prompt('Give a number 1 through 6. Type 0 to exit.');
if(input === '0'){
break;
}else{
if(pictures.length >= input) {
showMyImage(pictures[input - 1])
// or do anything else with your image (e.g. error handling etc.)
}
}
}
Hope this can help!

Text Box Integer Validation

I need to create a code in HTML/Javascript that will allow a user to enter an answer to a maths question and then the site needs to validate whether that answer is correct.
Been playing around for a few hours and researched the web but not found anything close.
Any help is appreciated!!
You could use javascript for validation,
Look at this example.
var value = Number(intfield.value);
if (Math.floor(value) == value) {
// value is an integer, do something based on that
} else {
// value is not an integer, show some validation error
}
checking if value of a textfield is integer in javascript
Javascript validation
function isInteger(number) {
var getVal = parseInt(number);
if (number.length == 0 || getVal == Number.NaN || getVal <= 0) {
return false;
}
return true;
}

My method fires when it shouldn't

This code seems to loop through adding 1 to player1.score untill the score is === to whatever i put in the second if statement. Anyone know why?
pointScored: {
startNextSet: function(Scorer) {
if (gameController.bananasTaken < 3 && Scorer === "player1") {
console.log(gameController.player1.score);
gameController.player1.score += 1;
if (gameController.player1.score === 10 &&
gameController.bananasTaken === 0 &&
gameController.player1.bananaCount === 0) {
console.log(gameController.player1.score);
gameController.updatePlayerStats(gameController.Banana1, 20, gameController.canvas.height
- 20 - gameController.Banana1.height, gameController.player1, "left");
console.log("player 1's first point");
}
I'm currently learning about using a debugger but thought i'd leave this here to see if anyone knows why. Thanks.
There's a chance your values get evaluated as strings. The === operator doesn't do any type conversions, that's why its faster.
Consider changing your evaluation to use ==. The same issue has cropped up in another question.
I have refactored your code a bit & used the == notation I suggest above. Please try running it and tell me if it works.
pointScored:{
startNextSet: function(Scorer) {
gc=gameController; //to save thy fingers from typing ache
if (gc.bananasTaken > 2 || Scorer !== "player1")
return;
console.log(gc.player1.score); // this logs 6 times from 0 to 5
gc.player1.score += 1;
if (gc.player1.score == 5 && gc.bananasTaken == 0) {
alert(gc.player1.score); //*******!
if(gc.player1.bananaCount == 0) {
gc.updatePlayerStats(gc.Banana1, 20, gc.canvas.height - 20 - gc.Banana1.height, gc.player1, "left");
console.log("player 1's first point");
}
}
}
}
As I look at your function, it seems that this logic needs to be INSIDE the gameController object.

Categories