Generate number in sequence insted of Random number in Java Script - javascript

On click I want to access the keyData array but on click random number is generated how can I access elements of array keyData in the sequence not in random Like on first click first element is accessed and on sthe econd click the second element is accessed ,and so on. AThiscode is from Paper js lib.
I want to change this randomNumber with sequence of numbers as mentioned above. I think using loop is not the solution.
function onKeyDown(event) {
var maxPoint = new Point(view.size.width, view.size.height);
var randomPoint = Point.random();
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point, 250);
var randomNumber = Math.floor(Math.random() * 27);
newCircle.fillColor = keyData[randomNumber].color;
keyData[randomNumber].sound.play();
circles.push(newCircle);
}

You could define a variable called number outside the function, replace randomnumber in the function with number and increment number on each click.
Note, it appears that keyData has entries with index 0-26 so you need to ensure number does not go above that, hence the % in the click event. Also, the color and sound will be non-random but the center point of the circle still is.
<button onclick="onKeyDown(event);">Click me to go to create the next circle</button>
<script>
var number=0;
function onKeyDown(event) {
var maxPoint = new Point(view.size.width, view.size.height);
var randomPoint = Point.random();
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point, 250);
newCircle.fillColor = keyData[number].color;
keyData[number].sound.play();
circles.push(newCircle);
//set up for the next time
number = (number + 1)%27;
}
</script>

As stated in the previous answer, you have to use a counter.
Here is a sketch demonstrating a simplified solution.
let counter = 0;
const keyData = [
{ color: 'red' },
{ color: 'yellow' },
{ color: 'blue' }
];
function onKeyDown(event) {
const index = counter % keyData.length;
const newCircle = new Path.Circle(Point.random() * view.size, 50);
newCircle.fillColor = keyData[index].color;
counter++;
}

Related

setInterval won't call function

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;
}

JavaScript - Random numbers and variables between functions

I am new to JavaScript, I have two roll functions for each roll of a frame. I am unable to get the values of each of those rolls into a frame function to call on and use. If someone could help this would be great! thanks in advance, My code is below.
var Bowling = function() {
var STARTING_TOTAL = 0;
ROLL_ONE = Math.floor(Math.random() * 11);
ROLL_TWO = Math.floor(Math.random() * 11);
this.score = STARTING_TOTAL;
var firstScore;
var secondScore;
var totalScore;
Bowling.prototype.firstRoll = function() {
firstScore = ROLL_ONE
return firstScore;
};
Bowling.prototype.secondRoll = function() {
secondScore = Math.floor(Math.random() * 11 - firstScore);
return secondScore;
};
Bowling.prototype.frameScore = function () {
totalScore = firstScore + secondScore
return totalScore;
};
};
I can only guess what you're trying to achieve. I refactored you code a little bit:
var Bowling = function () {
var STARTING_TOTAL = 0;
this.score = STARTING_TOTAL; // remains unused; did you mean "totalScore"?
this.firstScore = 0;
this.secondScore = 0;
};
Bowling.prototype.firstRoll = function () {
this.firstScore = Math.floor(Math.random() * 11);
return this.firstScore;
};
Bowling.prototype.secondRoll = function () {
this.secondScore = Math.floor(Math.random() * 11 - this.firstScore);
return this.secondScore;
};
Bowling.prototype.frameScore = function () {
this.totalScore = this.firstScore + this.secondScore
return this.totalScore;
};
// now use it like this:
var bowling = new Bowling();
console.log(bowling.firstRoll());
console.log(bowling.secondRoll());
console.log(bowling.frameScore());
In my approach however, firstScore and secondScore are public properties.
To address the question of why the second roll can be negative: as your code currently stands, if the second roll is smaller than the first roll, the result will be negative. If you want it so that if the first roll is 6, the second roll will be a number between 0 and 4, try something like:
function randomInt(maxNum) {
return Math.floor(Math.random() * maxNum)
}
var maxRoll = 11
var rollOne = randomInt(maxRoll)
var rollTwo = randomInt(maxRoll - rollOne)
console.log(rollOne)
console.log(rollTwo)
Press "Run Code Snippet" over and over again to see it work.
Changes I've made:
I made a function, randomInt that gives a random number from 0 to some max number. This saves you from needing to write the same code twice.
I created a variable maxRoll that keeps track of what the highest possible roll is.
I subtract maxRoll from the first roll to determine what the max number for the second roll should be (maxRoll - rollOne). That's then given to randomInt.

JavaScript won't change my color when it should, and also weird log. appears

So I wanted to code a simple project. When a button is clicked, the program generates a random number between 1 and 50 and then prints it inside my DIV.
I wanted a little feature that if the number happens to be 18, the background color changes to red.
So I've tried do do this many times, but the background changing randomly. No order or whatsoever.
I've tried to log the numbers, to see is there any connection between the them when it changing to red, but no luck.
However, in the console, a little grey 2 appears. Also at random times.
function getRandomNumber(){
var randomNumber = Math.floor(Math.random()*50) + 1;
return randomNumber;
}
myButton.addEventListener('click', ()=>{
para.innerHTML = getRandomNumber();
console.log(getRandomNumber());
if(getRandomNumber() === 18){
para.style.backgroundColor = "red";
}
});
Everytime you call getRandomNumber() it's generating a new number. Call it once, save it to a variable, and everything should work as you expect.
function getRandomNumber() {
var randomNumber = Math.floor(Math.random() * 50) + 1;
return randomNumber;
}
myButton.addEventListener('click', () => {
let number = getRandomNumber();
para.innerHTML = number;
console.log(number);
if (number === 18) {
para.style.backgroundColor = "red";
}
});
Set return value of getRandomNumber() as a variable. Toggle backgroundColor between "red" and "unset" or empty string ""
function getRandomNumber(){
var randomNumber = Math.floor(Math.random()* 4) + 1;
return randomNumber;
}
var para = document.querySelector("p");
var myButton = document.querySelector("button");
myButton.addEventListener("click", () => {
const rand = getRandomNumber();
para.innerHTML = rand;
para.style.backgroundColor = rand === 1 ? "red" : "unset";
});
<button>click</button>
<p></p>
Your issue is that you are calling getRandomNumber twice, which will get you two different random numbers. Save the random number to a variable var randomNumber = getRandomNumber() and then use this variable to set the innerHTML of your para and check if it's eighteen to see if the background should change.
The grey number 2 just means that the same number is being printed twice in a row.

Javascript : generate random number function and push into array

I'm trying to push a random number of bunnies into a canvas from 1~10 in Javascript.
However, the Math.random() method doesn't seem to be working. It just gives me one bunny. What am I doing wrong?
var field = [];
var randomNum = Math.floor(Math.random() * 10);
field.push(randomNum * new Bunny());
function Bunny() {
...
}
It won't give you any bunnies at all. randomNum * new Bunny() will be NaN1, because you're trying to multiply an object with a number.
If you want multiple bunnies, you have to create them, probably in a loop:
var field = [];
var randomNum = Math.floor(Math.random() * 10);
for (var n = 0; n < randomNum; ++n) { // Loop
field.push(new Bunny()); // creating and pushing
} // multiple bunnies
function Bunny() {
// ...
}
1 Or a number, if you've overridden valueOf on Bunny.prototype, which seems unlikely.
var field = [];
var randomNum = Math.floor(Math.random() * 10);
for (k=0; k<randomNum; k++)
{
field.push(new Bunny());
}

Get same values with Math.random

In the below code, I want to function 2 to change the text in text to complete the cycle. Unfortunately var rand will not change text into being a different word. Rather it will always remain same the whole time.
var x = 0;
function function1() {
document.getElementById("text").textContent = rand;
}
function function2() {
if (document.getElementById("text").innerHTML === "Red") {
x += 1;
document.getElementById("text2").textContent = x;
function1();
}
}
//I have got the equivalent functions for blue, green and gold as well
var randomarray = ['Red', 'Blue', 'Green', 'Gold', ];
var rand = randomarray[Math.floor(Math.random() * randomarray.length)];
Can someone please show me how to fix this.
Move the declaration of rand to inside function1. That way it does indeed chose
a again a color each time function1 is called
function function1() {
var rand = randomarray[Math.floor(Math.random() * randomarray.length)];
document.getElementById("text").textContent = rand;
}
and comment out (or remove) the declaration you have outside both functions as it becomes irrelevant.
//var rand = randomarray[Math.floor(Math.random() * randomarray.length)];

Categories