I am having trouble with a few javascript do while loops - javascript

I am writing a code guessing program to test the security of some iPhone passwords (This is not in anyway connected to anything illegal or is used to break into actual iPhones). The do/while loops just end all response once they occur and the last two lines don't print to the console.
print("Hi!");
print("I am a password security tester.");
var tries = 0
var guess1 = 0
var guess2 = 0
var guess3 = 0
var guess4 = 0
var guess = (guess1 * 1000) + (guess2 * 100) + (guess3 * 10) + guess4;
var password1 = (Math.floor(Math.random()*9));
var password2 = (Math.floor(Math.random()*9));
var password3 = (Math.floor(Math.random()*9));
var password4 = (Math.floor(Math.random()*9));
var password = (password1 * 1000) + (password2 * 100) + (password3 * 10) + password4;
print("This is the randomly genorated password: " + password);
print("And now begins the guessing");
do{
guess1 + 1;
tries + 1;
}while (password1 != guess1);
do{
guess2 + 1;
tries + 1;
}while (password2 != guess2);
do{
guess3 + 1;
tries + 1;
}while (password3 != guess3);
do{
guess4 + 1;
tries + 1;
}while (password4 != guess4);
print("Complete in " + tries + " tries");
print("The answer is: " + guess);

Jacob Ewing's answer is correct, but another problem is that guess will still be 0 at the end, because it doesn't automatically update. You'll need to do:
var guess = (guess1 * 1000) + (guess2 * 100) + (guess3 * 10) + guess4;
Before:
print("Complete in " + tries + " tries");
print("The answer is: " + guess);

You need to be using a += operator instead of just +
Saying guess1 + 1 returns the value of guess1 + 1, but does not increment that value directly, so you get an infinite loop.

Related

error shows on using && operator in chrome snippets

prompt("Enter your name");
var lifeExpectancy = Math.random() ;
lifeExpectancy = Math.floor(lifeExpectancy * 100) + 30;
// if (lifeExpectancy > 100){alert(lifeExpectancy + " Years, as old as Dinosaurs")}
if (lifeExpectancy <= 100 && > 75 ){
alert(lifeExpectancy + " Years , Many more birthdays to come !!!")
} else{
alert(lifeExpectancy + " Years.")
}
Shows error on using && and <= operators
You need to mention the name of variable again for the second comaprison
prompt("Enter your name");
var lifeExpectancy = Math.random() ;
lifeExpectancy = Math.floor(lifeExpectancy * 100) + 30;
if (lifeExpectancy <= 100 && lifeExpectancy > 75 ){
alert(lifeExpectancy + " Years , Many more birthdays to come !!!")
} else{
alert(lifeExpectancy + " Years.")
}

How to improve this code, transforming string

I am currently working on a project where I need to convert string in specific way. So, the idea is that string like this:
r[10,55]r will be converted to (Math.floor(Math.random() * (55 - 10 + 1)) + 10) - making it js value that is random from 10 to 55 (including).
and string like this: %[50;w]% will be be converted to (canvas.width / 100 * 50) - making it 50% of canvas width (w; stands for width, h; stands for height).
You can also combine these two 'functions' like this: %[r[0,50]r;h]% making it (canvas.height / 100 * (Math.floor(Math.random() * (50 - 0 + 1)) + 0)), meaning you will get from 0% to 50% of canvas height.
So, they way I'm doing it right now looks like this:
transform = function(i){
var i = i;
while(i.indexOf('r[') > -1){
var part1 = i.substring(i.indexOf('r['));
var part2 = i.substring(i.indexOf(']r') + 2);
var r = part1.substring(0,part1.length - part2.length);
var partBefore = i.substring(0,i.indexOf('r['));
var firstNumber = r.substring(r.indexOf('r[') + 2);
var comma = r.substring(r.indexOf(','));
var secondNumber = r.substring(r.indexOf(',') + 1);
firstNumber = firstNumber.substring(0,r.length - comma.length - 2);
secondNumber = secondNumber.substring(0,secondNumber.length - 2);
while(firstNumber.indexOf('%[') > -1){
var part1A = firstNumber.substring(firstNumber.indexOf('%['));
var part2A = firstNumber.substring(firstNumber.indexOf(']%') + 2);
var p = part1A.substring(0,part1A.length - part2A.length);
var partBeforeA = firstNumber.substring(0,firstNumber.indexOf('%['));
var firstNumberA = p.substring(p.indexOf('%[') + 2);
var commaA = p.substring(p.indexOf(';'));
var secondNumberA = p.substring(p.indexOf(';') + 1);
firstNumberA = firstNumberA.substring(0,p.length - commaA.length - 2);
secondNumberA = secondNumberA.substring(0,secondNumberA.length - 2);
if(secondNumberA == 'w'){ secondNumberA = 'canvas.width'; }
else if(secondNumberA == 'h'){ secondNumberA = 'canvas.height'; }
var partAfterA = firstNumber.substring(firstNumber.indexOf('%[') + p.length,firstNumber.length);
firstNumber = partBeforeA + '(' + secondNumberA + ' / 100 * ' + firstNumberA + ')' + partAfterA;
}
var partAfter = i.substring(i.indexOf('r[') + r.length,i.length);
i = partBefore + '(Math.floor(Math.random() * (' + secondNumber + ' - ' + firstNumber + ' + 1)) + ' + firstNumber + ')' + partAfter;
}
while(i.indexOf('%[') > -1){
var part1 = i.substring(i.indexOf('%['));
var part2 = i.substring(i.indexOf(']%') + 2);
var p = part1.substring(0,part1.length - part2.length);
var partBefore = i.substring(0,i.indexOf('%['));
var firstNumber = p.substring(p.indexOf('%[') + 2);
var comma = p.substring(p.indexOf(';'));
var secondNumber = p.substring(p.indexOf(';') + 1);
firstNumber = firstNumber.substring(0,p.length - comma.length - 2);
secondNumber = secondNumber.substring(0,secondNumber.length - 2);
if(secondNumber == 'w'){ secondNumber = 'canvas.width'; }
else if(secondNumber == 'h'){ secondNumber = 'canvas.height'; }
while(firstNumber.indexOf('r[') > -1){
var part1A = firstNumber.substring(firstNumber.indexOf('r['));
var part2A = firstNumber.substring(firstNumber.indexOf(']r') + 2);
var r = part1A.substring(0,part1A.length - part2A.length);
var partBeforeA = firstNumber.substring(0,firstNumber.indexOf('r['));
var firstNumberA = r.substring(r.indexOf('r[') + 2);
var commaA = r.substring(r.indexOf(','));
var secondNumberA = r.substring(r.indexOf(',') + 1);
firstNumberA = firstNumberA.substring(0,r.length - commaA.length - 2);
secondNumberA = secondNumberA.substring(0,secondNumberA.length - 2);
var partAfterA = firstNumber.substring(firstNumber.indexOf('r[') + r.length,firstNumber.length);
firstNumber = partBeforeA + '(Math.floor(Math.random() * (' + secondNumberA + ' - ' + firstNumberA + ' + 1)) + ' + firstNumberA + ')' + partAfterA;
}
var partAfter = i.substring(i.indexOf('%[') + p.length,i.length);
i = partBefore + '(' + secondNumber + ' / 100 * ' + firstNumber + ')' + partAfter;
}
return i;
};
and it has some problems..
I don't know how to identify where the , ends so I'm using ; in the %[...;...]% function instead, but that's not really a good solution, because I want to add more functions like these in the future. And I can't think of a new 'divider' every time like , ; . : obviously.
Is there a better way to do it?
let conversion = 'r[10,55]r'
let reg = /r\[([0-9]{0,3}),([0-9]{0,3})]r/
let format = (string, match1, match2) => {
return `(Math.floor(Math.random() * (${match2} - ${match1} + 1)) + ${match2})`
}
let res = conversion.replace(reg, format)
console.log(res)
let conversion = '%[50;w]%'
let reg = /%\[([0-9]{0,3});([a-z])]%/
let format = (string, match1, match2) => {
let dimension = match2 === 'w' ? 'width' : 'height'
return `(canvas.${dimension} / 100 * ${match1})`
}
let res = conversion.replace(reg, format)
console.log(res)
Here is my work around the two individual scenarios, currently working on a combined conversion scenario.
As chrisz mentions in the comments regular expressions can help out a lot. Here's how you might approach the first two (uncombined) strings using template literals to produce the output from the matched elements.
const regex1 = /r\[(\d+),(\d+)\]r/;
const str = 'r[10,55]r';
const match = str.match(regex1).slice(-2);
const out = `(Math.floor(Math.random() * (${match[1]} - ${match[0]} + 1)) + ${match[0]})`;
console.log(out);
const regex2 = /%\[(\d+);(h|w)\]%/;
const str2 = '%[50;w]%';
const match2 = str2.match(regex2).slice(-2);
const out2 = `(canvas${match[1] === 'h' ? '.height' : '.width'} / 100 * ${match2[0]})`;
console.log(out2);

While loop ignores initial condition and the browser crashes

So long story short - I'm trying to build a simple tennis match simulation (code below). Unfortunately, something is wrong with my code, because the while loop I created ignores the condition put in brackets and starts to make infinite number of itinerations (browser crashes). Could you please have a look at my code and tell me where the error lies?
var gamesPlayerOne = Math.floor(Math.random() * 8);
var gamesPlayerTwo = Math.floor(Math.random() * 8);
var tiebreak = Math.floor(Math.random() * 10);
var setsPlayerOne = 0;
var setsPlayerTwo = 0;
var scoreline = [];
function playTheGame(g1, g2) {
while (setsPlayerOne < 2 && setsPlayerTwo < 2) {
if (g1 === 6 && g2 < 5) {
var result = g1.toString() + ":" + g2.toString();
setsPlayerOne += 1;
scoreline.push(result);
} else if (g1 < 5 && g2 === 6) {
var result = g1.toString() + ":" + g2.toString();
setsPlayerTwo += 1;
scoreline.push(result);
} else if (g1 === 6 && g2 === 7) {
var result = g1.toString() + ":" + g2.toString() + "(" + tiebreak + ")";
setsPlayerTwo += 1;
scoreline.push(result);
} else if (g1 === 7 && g2 === 6) {
var result = g1.toString() + ":" + g2.toString() + "(" + tiebreak + ")";
setsPlayerTwo += 1;
scoreline.push(result);
}
}
}
playTheGame(gamesPlayerOne,gamesPlayerTwo);
console.log(scoreline);
If the random numbers that you pass into your function don't match any of the if or else if conditions then none of your variables is ever updated so the while loop's condition remains true forever.
If you are trying to simulate the entire tennis match, it would make more sense not to pass the function any arguments, and instead on each iteration of the while loop decide randomly which player just won the current game and then test if either player has won a set yet, perhaps something like this:
function playTheGame() {
var g1 = 0;
var g2 = 0;
var setsPlayerOne = 0;
var setsPlayerTwo = 0;
var scoreline = [];
while (setsPlayerOne < 2 && setsPlayerTwo < 2) {
// determine a random winner for the current game
if (Math.random() < 0.5)
g1++;
else
g2++;
// has one of the players just won a set?
if (g1 >= 6 && g2 < g1 - 1) {
var result = g1 + ":" + g2;
setsPlayerOne += 1;
scoreline.push(result);
g1 = g2 = 0;
} else if (g1 < g2 - 1 && g2 >= 6) {
var result = g1 + ":" + g2;
setsPlayerTwo += 1;
scoreline.push(result);
g1 = g2 = 0;
}
}
return scoreline;
}
console.log(playTheGame());
Note that you don't need to call .toString() on g1 and g2, because concatenating them with the string ":" implicitly converts the numbers to strings.
You could extend this to make one or the other player more likely to win (simulating different skill levels) by changing if (Math.random() < 0.5) to use a variable instead of hardcoding 0.5.
P.S. I couldn't be bothered to look up the rules for tennis to confirm how you win a set, but my vague recollection is that you have to get at least 6 games and be at least two games ahead of the other player, so that's what the code I've shown tries to implement...
For example... you didn't specify any condition to increase setsPlayer[One/Two] when g1 is equals to 0 and g2 is equals to 7.
So you should add some condition to check it.

Dice Game - need to roll more dice based upon circumstances

I am developing a game idea. Weapons can be equipped on your character. Different weapons have different amounts of damage dice and critical hit dice. I have it working currently so that the program rolls the appropriate amount of dice based on your equipped weapon.
However, the program only rolls one critical dice, despite whether the equipped weapon contains two critical roll dies.
var WepEquipped = { "name": "Broken Sword", "attack_dice": "2", "critical_dice": "1", "min_base_dmg": "2", "max_base_dmg": "12", "max_total_dmg": "24", "weapon_type": "Slash" };
function Attack(rolls) {
var total = 0;
var dice = [];
for (var i = 1; i <= rolls; i++) {
var d6 = Math.floor((Math.random() * 6) + 1);
$("#dice_container").append("<div class='die_roll'><p class='atk-roll'>" + d6 + "</p></div>");
dice.push(d6);
total += d6;
}
// Needs to be able to roll for multiple critical dice
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
$('#attack_button').off('click').on('click', function(){
$('.die_roll').hide();
Attack(WepEquipped.attack_dice);
// Attack(WepEquipped.attack_dice);
});
I can explain much more, but I hope this is enough code to grasp what I'm asking. Something here needs to change but I cannot figure out what:
// Needs to be able to roll for multiple critical dice
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
your grep returns the number of elements in the dice array that equal to your first roll and if the length of that array equals the number of rolls that were made you roll the critical dice once.
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
If you're trying to roll as many times as the grep returns you need something like this.
var crits = $.grep(dice, function (elem) {return elem === dice[0];});
if( crits.length == rolls ){
for( var x=0;x<crits.length;x++){
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
}
Sorry for the double post, was on an abandoned account.

javascript "less than" if statement failing

Here is my function:
function reCalculate(i) {
document.getElementById("Q" + i).value = document.getElementById("C" + i).value - document.getElementById("QA" + i).value;
if (document.getElementById("Q" + i).value < 0) {
document.getElementById("Q" + i).value = 0;
}
if (document.getElementById("Q" + i).value < document.getElementById("E" + i).value && document.getElementById("Q" + i).value != 0) {
alert(document.getElementById("Q" + i).value + " is less than " + document.getElementById("E" + i).value + "?");
document.getElementById("Q" + i).value = document.getElementById("E" + i).value;
}
document.getElementById("Q" + i).value = Math.ceil(document.getElementById("Q" + i).value);
}
It checks Q, if it's less than 0, it makes it 0. Then, if it's not 0, but it's less than E, it makes it E. For some reason this function works UNLESS Q is a double digit number.
For example, if Q is 7 and E is 2, then it will leave Q at 7. However, if Q is 10 and E is 2, for some reason it thinks that 10<2, and it changes Q to 2!
Am I missing something here??
When you pull the .value of an element it returns a string. '10'<'2' will return true.
You can simply do a parseInt/parseFloat on the value, ala
var q = parseInt(document.getElementById("Q"+i).value,10)
Thats because it is considering your Q as a string while comparing.
Try the following instead:
function reCalculate(i){
var Z = document.getElementById, P = parseInt;
var qElem = Z("Q"+i);
var q = P(qElem.value, 10);
var c = P(Z("C"+i).value, 10);
var qa = P(Z("QA"+i).value, 10);
var e = P(Z("E"+i).value, 10);
q = c - qa;
if (q < 0) qElem.value = 0;
if (q < e && q != 0){
alert(q+" is less than "+e+"?");
qElem.value = e;
}
qElem.value = Math.ceil(q);
}
May be you should do a
parseFloat(document.getElementById("Q"+i).value)
to make sure you are comparing numbers
You are comparing strings not numbers. Use the unary + to convert to a number:
if (+document.getElementById("Q" + i).value < +document.getElementById("E" + i).value ...)
You should use variables by the way:
var input_one = document.getElementById("Q" + i).value,
input_two = document.getElementById("E" + i).value;
if (+input_one < +input_two) {
}

Categories

Resources