Why wont the randomization in this code work? - javascript

Thank you for answering my original question, and the reason i am simply editing this post for my second question about this code is because the site wont let me make very many questions. my question is why isnt makesjump1 randomly true or false? it always seems to come out true. please help #Yhlas and #codeConcussion
var isjumping1 = true;
while(isjumping1) {
var makesjump1 = Math.random()
if(makesjump1 => .51) {
makesjump1 = true }
else if(makesjump1 <= .50) {
makesjump1 = false }
var jump1 = prompt("Do you choose to JUMP, or let the fairies help you FLY").toUpperCase()
switch(jump1) {
case 'JUMP':
if(makesjump1 = true) {
console.log("You made the jump on your own, so the fairies reward you with a steel sword(9 DMG)")
damage = 9;
weapon = 'steel sword(9 DMG)'; }
else if(makesjump1 = false) {
console.log("You attempt the jump but miss it, and are hanging on by a thread")
console.log("The fairies rescue you, but you got scratched up, doing 3 damge to you.")
health = health - 3; }
isjumping1 = false;
break;
case 'FLY':
console.log("The fairies help you over the pit")
isjumping1 = false;
break;
default:
alert("That was not a choice!")
break; }
}

You're assigning it to true with every loop. Use == instead or just...
while(isjumping1)

while(isjumping1==1) - comparison
while(isjumping1=1) - assignment(always returns true)

The way that you're assigning the random value to makesjump1 is incorrect. It would fail if Math.random() returned a value in the range (0.50,0.51). Instead, try this:
var makesjump1 = Math.random()<0.5;

Related

Goto somewhere based on a variable, JavaScript

Ok so I'm a kinda new to the whole JavaScript thing but I was just trying something Some kind of yes/no quiz thingy and I want to skip certain questions and stuff I came up with the following but the whole "continue Q + question_nr;" doesn't work like I hoped it would. How am I supposed to do this? :)
var question_nr = 1;
Q1:
function q1() {
var a1 = prompt("Wanna skip the next question?", "y/n");
switch(a1) {
case "y":
alert("k");
question_nr = question_nr + 2;
continue Q + question_nr;
break;
case "n":
alert("oki");
question_nr = question_nr + 1;
break;
default:
alert("please enter y or n.");
break;
}
}
Q2:
alert("test2");
//<insert question 2>
break;
Q3:
alert("test3");
//<insert question 3>
break;
<button onclick="q1()">test</button>
p.s. any good sites to help me learn JS are appreciated so I don't have to ask (probably really stupid) questions like this one in the future
I don't want to teach you, go to the code academy, but if you at least "don't know" how to implement something that works as you want, I can tell you how to do something that works somehow near how goto worked. Listen:
You can declare execution of your questions (let's call that "goto targets") as:
const QUESTIONS = {
Q1: function () {
someLogicThere();
},
Q2: function () {
someLogicThere();
}
};
And execute it in some way like this (this will throw an error if you don't define any of required questions):
switch(lastPrompt) {
case "y":
alert("k");
question_nr = question_nr + 2;
QUESTIONS["Q" + question_nr]();
break;
case "n":
alert("oki");
question_nr = question_nr + 1;
break;
default:
alert("please enter y or n.");
break;
}
}
But I assume that a bad code. You should wrap everything inside IIFE/module and use more html/angular/react to keep this organised.
I understand that you are still learning, but you should not use labels to do this. The following is a more simple way to accomplish this goal.
(function () {
var questions = [
'How much wood can a wood chuck chuck?',
'How many fish in the sea?',
'How does this JavaScript work?'
];
var index = -1;
window.askQuestion = function () {
var answer = prompt("Wanna skip the next question?", "y/n");
if(answer === 'y' || answer === 'n') {
index = (index + 1) + (answer === 'y');
if(questions[index]) {
alert(questions[index]);
} else {
alert("No more questions to ask.");
index = -1;
}
} else {
alert("please enter y or n.");
}
};
}());
A few things to note. The function above wraps its code in what is called a self-executing anonymous function. This makes it so that the variables declared inside it are within a private scope. Next, we store questions inside of an array while keeping in mind that the array index always begins at 0. This is why when we declare the variable for index that it begins at -1. If the answer given by the user is y or n, then we add one to the index plus true or false whether or not the answer is y. This conditionally increments index by 1 if n or 2 if y. Then check whether or not a question exists at the calculated index. If it does, trigger the alert for the question, or if not alert that there are no more questions and reset the index to -1.

How to reduce "if statement" conditions? [reduce the conditions inside the if statement]

after days of hard thinking i choose to ask that question. I have if statement with multiple conditions:
//var current is array of arrays of integers
if((current[rot][0] + x)<blocks.length
&& (current[rot][1] + x)<blocks.length
&& (current[rot][2] + x)<blocks.length
&& (current[rot][3] + x)<blocks.length
&& !$(blocks[current[rot][0]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][1]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][2]+x]).hasClass("blockLand")
&& !$(blocks[current[rot][3]+x]).hasClass("blockLand"))
{
//something to happen here ONCE!
}
Because i want something inside to happen just once i think i cant use for loop.
So my question is: is there a possible way to reduce the conditions number? and how?
P.S.: Yes i figured out that i can use flag (true/false) inside and do my stuff outside this if, in another if - but i think that not always gonna work, because for every loop the flag will be different.
var b = true;
for (var i = 0; i <= 3; i++) {
// In two lines for being clear, but it's possible just in one
b = b && (current[rot][i] + x)<blocks.length
b = b && !$(blocks[current[rot][i]+x]).hasClass("blockLand");
// You could speed it up this way.
if(!b) break;
}
if (b) {
//something to happen here ONCE!
}
I think I understand what you are asking but let me know if there is anything else I can do.
JavaScript has a ternary (conditional operator) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
This operator allows you to assign true/false values based on an internal if/else condition.
Here is some code for you to explain this...
window.onload = function() {
var one = 1;
var two = 2;
console.log(one > two ? "greater" : "not greater");
};
You can also use a Switch statement which you can read about here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch.
Here is an example of a switch statement.
window.onload = function() {
var string = "testing this out";
switch (string) {
case "testing this out":
console.log('testing this out found in condition one');
break;
case "testing":
console.log('found testing');
break;
default:
console.log('not found');
break;
}
};
Let me know if I can improve this.

Function that randomly returns one of three options, where all options have the exact same chance?

I know this may have been asked before, but I'm trying to have a Javascript function return one of three options. The problem is the chance for each option should be completely equal.
This is what I have so far:
var choice = Math.random();
if (choice <= 0.34) {
choice = "option1";
} else if (choice <= 0.67) {
choice = "option2";
} else {
choice = "option3";
}
This is already pretty accurate, however the probability of "option3" is slightly lower. How can I reformulate this to have each option have the same chance of occuring? I would prefer a solution that doesn't involve using "0.3333333333333333..." in the if condition or something like that.
I think it would be cleaner and simpler to do something like this:
var options = ["option1", "option2", "option3"];
var choice = options[Math.floor(Math.random()*options.length)];
Multiplying the random number by 3 will allow you to do this without using decimals or fractions:
var choice = Math.random() * 3;
if (choice <= 1) {
choice = "option1";
} else if (choice <= 2) {
choice = "option2";
} else {
choice = "option3";
}
basicaly its your + Alex´s solution but i find that more beautiful
options=['option1','option2','option3']
choice = options[Math.floor(Math.random()*options.length)]
Try this hard style:
var choice = ['first', 'second', 'third'][Math.floor(Math.random()*3)]

JavaScript Help (Loops and Arrays in Particular)

So I am doing an assignment for a required javascript class and am stuck on a couple of parts specifically. We are supposed to create a guessing game with an array where we prompt the user to guess names and if they match anything in the array to tally it up as points.
Anyway here is the main code, the part that I am stuck on is figuring out how to loop the code so when the user is prompted 3 times for a guess and each guess is taken into account
var sportsArray = ["Football","Basketball","Rollerblading","Hiking","Biking","Swimming"];
var name = prompt("Please enter your name.", "Enter Here");
var arrayGuess = prompt("Guess a sport.", "Enter Here");
var counter;
for (counter = 0; counter < sportsArray.length; counter++) {
if (arrayGuess === "Football"||"Basketball"||"Rollerblading"||"Hiking"||"Biking"||"Swimming"){
alert("Good Job");
} else {
arrayGuess;
}
}
So the goal is to prompt the user to guess a part of the original array and if they do let them know that, but if they don't take points away and make them guess again until they have guessed 3 times.
Anyway if someone could lend a hand it would be appreciated.
You cannot simultaneously compare one item to a whole bunch of things like this:
if (arrayGuess === "Football"||"Basketball"||"Rollerblading"||"Hiking"||"Biking"||"Swimming")
Instead, you have to compare it to each individual item:
if (arrayGuess === "Football"||
arrayGuess === "Basketball"||
arrayGuess === "Rollerblading"||
arrayGuess === "Hiking"||
arrayGuess === "Biking"||
arrayGuess === "Swimming")
Or, there are more effective ways to compare to multiple items such as:
if (" Football Basketball Rollerblading Hiking Biking Swimming ".indexOf(" " + arrayGuess + " ") !== -1)
Or, using an array:
if (["Football","Basketball","Rollerblading","Hiking","Biking","Swimming"].indexOf(arrayGuess) !== -1)
Or, if this comparison happened a lot, you'd build an object ahead of time and use it for a lookup:
var items = {"Football":true,"Basketball":true,"Rollerblading":true,"Hiking":true,"Biking":true,"Swimming":true};
if (items[arrayGuess] === true)
If you want to compare without regards for proper case, then you can lowercase what the user entered and compare that to lower case test values:
var items = {"football":true,"basketball":true,"rollerblading":true,"hiking":true,"biking":true,"swimming":true};
if (items[arrayGuess.toLowerCase()] === true)
FYI, it's also not clear why you're using a loop here at all. No loop is needed to prompt once and test against all the possible sports values.
If you have to cycle through an array with a loop, then you can do this:
var items = ["football","basketball","rollerblading","hiking","biking","swimming"];
var testVal = arrayGuess.toLowerCase();
var match = -1;
for (var i = 0; i < items.length; i++) {
if (testVal === items[i]) {
// found a match
match = i;
break;
}
}
if (match !== -1) {
// items[match] was the match
} else {
// no match
}
I see a couple of things wrong here, as was already mentioned, your comparison in the if statement needs to reference the variable each time it is compared. But additionally, since you are in a loop based on the length of your sportsArray variable, it would be better to not reference strings at all in the if statement, and instead do something more like the following:
if (arrayGuess === sportsArray[counter]) {
// Do stuff here
} else {
// Do other stuff here
}
Additionally, your else clause isn't going to behave quite like you are expecting it to. You are going to have to assign a new value to it, probably by way of another call to prompt. As of now you are only referencing the variable, which will do nothing. If you need to take three guesses, I would add an 'else if' clause into the mix where you get a new value for the variable, an let the else clause display a score and break out of the loop.
if (arrayGuess === sportsArray[counter]) {
// Add to the score
} else if (counter < 2) {
// We prompted for the first guess before the loop,
// so take the second and third here
arrayGuess = prompt("Guess a sport.", "Enter Here");
} else {
// Display score then break to exit the loop
break;
}

Radio Button Validation: I could validate it but I cant figure out the reason

I was stuck trying to validate if a radiobutton was selected or not and, in consequence, show alerts. Well, I found the mistake (I was putting the conditional statement inside the loop).
Even I solved the problem, I can’t figure out yet why my code works correctly outside the loop but doesn’t work inside it. Now I'm stuck with this.
I appreciate if anyone can tell me what’s the reason.
Below you'll see both JS codes, but here you have the fiddles examples:
JSFiddle that doesn't work
JSFiddle that works
This is the JS code that doesn’t work:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
result = true;
break;
}
if(result === false){
alert('Please, choose an option');
return false;
}else{
alert('You\'ve choosen ' + getNames[i].value)
}
}//Loop ends here.
}
And this is the JS code that works without problems:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
result = true;
break;
}
}//Loop ends here.
if(result === false){
alert('Please, choose an option');
return false;
}else{
alert('You\'ve choosen ' + getNames[i].value)
}
}
Maybe the for loop in JS code that doesn’t work has a wrong logic, it means that if the first radiobutton checked, the for loop stops; if the first radiobutton does not checked, it will alert 'Please, choose an option' and stops the for loop. The logic only validates the first radiobutton. Maybe thats the problem.
It's because of your break; line.
When it's inside the loop you're breaking it out on true before it has a chance to hit the following code: if(result === false)
break is breaking out of the entire loop which means it never hit's your if(result===false)
Hope that helps!
Wrong logic inside the loop, try this:
var getForm = document.getElementById('formX');
var putForm = getForm.onsubmit = showIt;
function showIt(){
var getNames = document.getElementsByName('season');
var result = false;
for(var i = 0; i < getNames.length; i++){
if(getNames[i].checked){
alert('You\'ve chosen ' + getNames[i].value)
result = true
}
if (i == getNames.length - 1 && !result)
{
alert('Please, choose an option')
}
}
}
If your question is how do I make it work, there are several good suggestions in the answers.
If you want to know: "Why didn't it work using the first method?" The best answer is that the break; line was causing your loop to terminate immediately, and therefore preventing the alert("You've chosen...") from having the opportunity to trigger.

Categories