I've just started learning Java Script and I was having trouble with loops. I'm trying to make a program that rolls a die 100 times and prints out the results. When I run this program, it prints out one roll 100 times, instead of printing out each roll once. Could anyone tell me what i'm doing wrong?
function start(){
var roll = Randomizer.nextInt(1 , 6);
for(var i = 0; i < 100; i++ ){
roll;
println("you rolled a " + roll);
}
}
Thanks for the help guys!
You'll need to run "roll" each time the loop is happening, so instead of just roll; you'll need to have roll = Randomizer.nextInt(1 , 6); inside the loop as well.
Or a better practice (since you're learning, it could help better your understanding), create a function called roll() and save what the function returns to a result variable, then print result out.
function roll () {
return Randomizer.nextInt(1 , 6);
}
function start () {
var result;
for (var i = 0; i < 100; i++ ) {
result = roll();
println('you rolled a ' + result);
}
}
Hope that helps you understand how to call a function to roll the dice again.
var dice = function() {
var roll = 1,
counter = 0,
LIMIT = 100,
DIE_TOP = 6,
result = [];
for (; counter < LIMIT; counter++, roll = Math.floor((Math.random() * DIE_TOP) + 1)) result.push(roll);
return result;
};
var test = dice();
document.write(test);
Related
I'm creating a game, and once the two scores match I want it to show "You won" but I can't get the two scores to compare.
I tried the parseInt method and .val method, no go.
var numberFour = Math.floor(Math.random() * 3 + 10);
$("#four").on("click", function() {
playerScore = playerScore + numberFour
$("#score").text(playerScore);
})
console.log(numberFour);
for (var i = 0; i < 121; i++) {
var goalNumber = Math.floor(Math.random() * 100 + 9);
$("#goal").text(goalNumber);
};
if (playerScore == goalNumber) {
console.log("You won!");
}
else {
console.log("You suck!")
}
I'm not sure why you're running through such a large loop for goalNumber, but try this code out. I changed your loop so you're not re-declaring goalNumber 120+ times and put your comparison inside your onclick call so it's continuously called every time you update your playerScore. I don't know how you've got your game setup, but I think it'll be tough for them to ever be equal when you're using random numbers.
Also, it helps to know when you're calling portions of your code. Omitting event handlers makes it difficult to debug your code. How else do we know when things are being used?
var playerScore = 0;
var goalNumber = 0;
var numberFour = Math.floor(Math.random() * 3 + 10);
for (var i = 0; i < 121; i++) {
goalNumber = Math.floor(Math.random() * 100 + 9);
$("#goal").text(goalNumber);
};
$("#four").on("click", function() {
playerScore += numberFour;
$("#score").text(playerScore);
if (playerScore == goalNumber) {
console.log("You won!");
}
else {
console.log("You suck!")
}
});
I'm trying to create a sort of ecosystem where objects spawn over time. However, when I try using setInterval to increase the amount it doesn't work. It works when I call the function on its own, but not when I use setInterval.
var plantSpawn = 5;
function createPlants() {
setInterval(reproducePlants, 5000);
for(var i=0; i<plantSpawn; i++){
var plant = new Object();
plant.x = Math.random() * canvas.width;
plant.y = Math.random() * canvas.height;
plant.rad = 2;
plant.skin = 'green';
myPlants[i] = plant;
}
}
function reproducePlants() {
plantSpawn += 5;
}
My goal for this is for every 5 seconds, 5 new plants appear. However, when I use the reproducePlants function with setInterval it does not work.
Note: I am calling createPlants() later in my code which makes the first 5 plants show up, but the next 5 won't show up. I am just showing the code that I'm trying to fix
The creation code must be moved inside the function that is repeatedly called.
NOTE: This is not an efficient way if you are going to call reproducePlants infinitely many times, since the myPlants array is reconstructed every time.
// Init with 0, because we increment it inside reproduce Plants
var plantSpawn = 0;
var myPlants = [];
function createPlants() {
reproducePlants();
setInterval(reproducePlants, 5000);
}
function reproducePlants() {
const canvas = document.getElementsByTagName('canvas')[0];
plantSpawn += 5;
for(var i = 0; i < plantSpawn; i++) {
var plant = new Object();
plant.x = Math.random() * canvas.width;
plant.y = Math.random() * canvas.height;
plant.rad = 2;
plant.skin = 'green';
myPlants[i] = plant;
}
}
You don't necessarily need to call the createPlants function from the reproducePlants function. You could add a call after both the functions. If I understand what you are trying to achieve that should do it.
You need to move the code that creates the plants (the for() chunck) inside the function that is called every 5 seconds (reproduce plants). So each time the function is called it will create the plants.
If you are trying to add only the 5 new plants every 5 seconds to your plants array you shouldn't recreate the array each time. It's better to keep track of the last index you have added and then continue right after that.
I created a variable called lastCreatedIndex so you can understand better what is going on. So the first time the code will run plants[i] from 0 to 4, the second 5 to 9...
var myPlants = [];
var lastCreatedIndex;
var plantSpawn;
function createPlants() {
plantSpawn = 5; //Initialize with 5 plants
lastCreatedIndex = 0; // Starts from index 0
reproducePlants();
setInterval(reproducePlants, 5000);
}
function reproducePlants() {
for(var i = 0 + lastCreatedIndex; i < plantSpawn; i++) {
var plant = new Object();
plant.x = Math.random() * canvas.width;
plant.y = Math.random() * canvas.height;
plant.rad = 2;
plant.skin = 'green';
myPlants[i] = plant;
console.log(i); // Output the number of the plant that has been added
}
lastCreatedIndex = i; //Update the last index value
plantSpawn += 5;
}
I'm trying to make a faux loading screen, and I need delays between loading messages of about 20-50ms or so so that people can actually see what's going on before it cuts to the initialized screen. The button that activates this goes to the following function:
function gameinit() {
for (k = 0; k <=1; k += 0.125) {
setTimeout(function () {
var nexttxt = "Loading... " + toString(100 * k) + "%"
}, 20);
displayupdate(nexttxt);
}
}
However this comes up as an incorrect syntax (on JSfiddle - https://jsfiddle.net/YoshiBoy13/xLn7wbg6/2/) when I use JShint - specifically lines four and five. I've looked at the guides for this and everything seems to be in order. What am I doing wrong?
(Note: displayupdate(nexttxt) updates the <p> tags with the next line of text)
When executing the script, nothing happens - the sixteen lines of text on the HTML move up as normal, the top eight being replaced with the eight generated by the gameinit() function, but the gameinit() only generates blank. If the script is executed again, it just outputs eight lines of 112.5% (as if it was the 9th iteration of the for loop).
I'm almost certain it's something elementary that I've missed, could someone please tell me what I've done wrong?
Use setInterval() instead, you can clear interval using clearInterval()
function gameinit() {
displayupdate("Loading... 0%");
var k = 0;
var inter = setInterval(function() {
if (k < 1) {
k += .25;
displayupdate("Loading... " + 100 * k + "%")
} else {
clearInterval(inter);
}
}, 2000);
}
function displayupdate(d) {
console.log(d);
}
gameinit();
here is another function can do this better ---- setInterval
var txt = '';
var time = 0;
var id = setInterval(function(){
console.log("loading..."+time/8*100+"%");
if(time++>7)
clearInterval(id);
},1000);
setTimeout doesn't work as you would expect it to work inside loops. You have to create a closure for each loop variable passed on to setTimeout, or create a new function to execute the setTimeout operation.
function gameinit() {
for (var k = 0; k <= 1; k += 0.125) {
doSetTimeOut(k);
}
}
function doSetTimeOut(k) {
setTimeout(function() {
var nexttxt = "Loading... " + toString(100 * k) + "%"
}, 20);
displayupdate(nexttxt);
}
My Javascript timer is for people with a rubiks cube with generates a scramble (nevermind all this, but just to tell you I'm generating after each solve a new scramble will be generated) and my scrambles do actually have a while (true) statement. So that does crash my script, but it 95/100 times stops just before the script crashes but I don't wanna have any times.
Let me explain a bit more detailed about the problem.
Problem: javascript crashes because my script takes too long to generate a scramble.
Below you have 3 functions I use.
This function generates a scramble with the Fisher-Yates shuffle.
Timer.prototype.generateScramble = function(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
This function validates the input e.g. I receive an array as the following:
Here I only have to check the first character. That's why I use the seconds [ ] notation. I don't want people get an F with an F2 e.g.
var scr = ["F","R","U","B","L","D","F2","R2","U2","B2","L2","D2","F'","R'","U'","B'","L'","D'"]
Timer.prototype.validateScramble2 = function(array) {
var last = array.length-1;
for (var i = 0; i < array.length-1; i++) {
if (array[i][0] == array[i+1][0]) {
return false;
}
}
for (var i = 0; i < array.length-2; i++) {
if (array[i][0] == array[i+2][0]) {
return false;
}
}
if (array[0][0] == [last][0]) {
return false;
}
return true;
};
The above functions are just waiting to be called. Well in the function below I use them.
Timer.prototype.updateScramble2 = function(scrambleArr, len, type) {
var self = this;
var scramble = '', j, updatedArr = [];
while (updatedArr.length < len) {
j = (Math.floor(Math.random() * scrambleArr.length));
updatedArr.push(scrambleArr[j]);
}
while (!self.validateScramble2(updatedArr)) {
updatedArr = self.generateScramble(updatedArr);
}
for (var i = 0; i < updatedArr.length; i++) {
scramble += updatedArr[i] + ' ';
}
scrambleDiv.innerHTML = scramble;
};
I assume you guys understand it but let me explain it briefly.
The first while-loop adds a random value from the given array(scrambleArr) into a new array called updatedArr.
The next while-loop calls the validateScramble2() function if there isn't in an array F next to an F2.
The for-loop adds them into a new variable added with a whitespace and then later we show the scramble in the div: scrambleDiv.innerHTML = scramble;
What do I need know after all this information?
Well I wanna know why my updateScramble2() functions lets my browser crash every time and what I do wrong and how I should do it.
I'm not entirely sure I understand the question, but from the way your code looks, I think you have an infinite loop going on. It appears as if validateScramble2 always returns false which causes your second loop in updateScramble2 to perpetually run.
I suggest you insert a breakpoint in your code and inspect the values. You could also insert debugger; statements in your code, works the same way. Open dev tools prior to doing these.
A suggestion is instead of using loops, use a timer. This breaks up your loop into asynchronous iterations rather than synchronous. This allows the browser breathing space for other operations. Here's an example of a forEachAsync:
function forEachAsync(array, callback){
var i = 0;
var timer = setInterval(function(){
callback.call(null, array[i]);
if(++i >= array.length) clearInterval(timer);
}, 0);
}
forEachAsync([1,2,4], function(item){
console.log(item);
});
You can take this further and use Promises instead of callbacks.
Here is my code and I am trying to practice making a for and a while loop with the while loop making use of a random number.
for(var i=0;i<5;i++){
console.log("This is a for loop");
}
var random= Math.random();
while(random<0.5){
console.log("This is a while loop");
random =Math.random();
}
It seems to not display the number however when I change the penultimate line to be:
var random =Math.random();
Sorry I'm quite new to coding so if this question is stupid I apologise in advance
There is a 50% chance that the while condition will be false on the first attempt. In such cases you will never see the loop's body being run.
var random = Math.random();
console.log('Initial value of random is', random);
if (random >= 0.5) console.warn('the while loop will not run');
while(random < 0.5) {
console.log("This is a while loop");
random = Math.random();
}
In your case, you may have wanted to write a do..while loop
var random;
do { // go into this block
console.log("This is a while loop");
random = Math.random();
} while (random < 0.5); // if condition true, go back to the `do`
If you're just starting with loops, it may be useful to consider how to re-write for loops as while loops
var i = 0;
while (i < 5) {
console.log("This is a while loop");
i++;
}
This isn't so you use while instead of for when a for is more natural, but so you get a feel for while loops, how they work and how sometimes they will suit the code you're trying to write.
for(var i=0;i<5;i++){
console.log("this is a for loop. the variable is:" + i);
}
var random= Math.random();
while(random<0.5){
console.log("This is a while loop the variable is:" + random);
random =Math.random();
}