I am trying to use Math.random to draw an image.
Though I know I haven't got it right.
I know I need a loop to go through the Math.random function, but don't know how to implement it. I also know I my spawnRock function isn't correct but do not know how to fix it. Any help?
This code also breaks my current drawImages.
var num;
function mathRock() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("num").innerHTML = x;
}
function spawnRock() {
if (num = 2, 4, 8){
context.drawImage(rock, 1500, 450);
} else {
}
var rock = new Image();
rock.src = "rock.png";
Here's a quick primer on Math.random
Math.random() * X will generate a random floating point number between zero up to (but not including) X. So Math.random*10 will generate, for example, 0.22, 1.56, 7.92 up to 9.9999999999.
If you need random integers, you can strip off the non-integer portion of the random number with parseInt( Math.random()*10 ) which will generate 0,1,2,3,4,5,6,7,8,9.
If you just want a random "coin-flip" (true or false) you can do that like this:
var randomTrueFalse=(Math.floor(Math.random()*2)==0);
If you need to do something randomly 3 out of 10 times then you can do that like this:
var thirtyPercentSuccess=( (Math.random()*10-7)>=0 );
Then use your desired version of the random number to choose whether to draw or do something else:
if (thirtyPercentSuccess){
context.drawImage(rock, 1500, 450);
}else{
// something else
}
mathRock is working fine, but I guess you should assing x to num variable: num = x then in spawnRock change the if condition to num == 2 || num == 4 || num==8 since == or === are used to compare and = to assign.
Related
My code below is supposed to draw a picture of a rock on the canvas at random times. But the code I currently have doesn't draw anything even after many refreshes. I also could do with loop round the mathRock function so that I get constant new random rocks without having to refresh the page, but I don't know which loop to use.
My code for the rock spawn is below:
var num;
var rock = new Image();
rock.src = "rock.png";
mathRock();
spawnRock();
function mathRock() {
var x = parseInt(Math.random()* 10);
document.getElementById("num");
}
function spawnRock() {
if (num == 2|| num == 4 || num == 6 || num == 8){
context.drawImage(rock, 500, 450);
} else {
}
}
Your mathRock function is a no-op: It assigns to a local variable and does a DOM query, but it doesn't do anything with that local variable or the result of the DOM query.
spawnRock will only ever see undefined for num, as you've declared it but never assigned a value to it.
It might be that mathRock was meant to assign to num rather than x, but it's unclear what (if anything) it was meant to do with the DOM query, or where context in spawnRock is meant to come from.
The document.getElementById("num") will look for an element with id="num", it doesn't do anything with the global variable num.
To make that work, you would assign the value to the variable. For calculating the random number, use the Math.floor method rather than parsing the number to a number:
function mathRock() {
var x = Math.floor(Math.random() * 10);
num = x;
}
However, you should rather return the value than using a global varible, and pass the value into the next function.
You can't use a regular loop to repeatedly change the image, you need a timer. Use the setInterval method for that.
var rock = new Image();
rock.src = "rock.png";
window.setInterval(function(){
var num = mathRock();
spawnRock(num);
}, 5000);
function mathRock() {
return Math.floor(Math.random() * 10);
}
function spawnRock(num) {
if (num == 2|| num == 4 || num == 6 || num == 8){
context.drawImage(rock, 500, 450);
} else {
}
}
My assignment for Intro to Javascript is to: "Write a function that accepts two numbers and returns a random number between the two values." It seems easy enough until I attempt to prompt the variables to input, at which point the output seems incorrect.
This is code that is most recommended for finding a random number between two ints, in this case 1 and 6:
function getRandomizer(bottom, top) {
return function() {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
}
var rolldie = getRandomizer(1, 6);
document.write(rolldie());
The output I get is what it should be, a random integer between 1 and 6. However my assignment is to prompt for the numbers, which can be anything. So I do this, using 10 and 1 as example numbers:
var max = prompt("input 10");
var min = prompt("input 1");
function getRandomizer(bottom, top) {
return function() {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
}
var rolldie = getRandomizer(min, max);
document.write(rolldie());
The output: 961. Second try: 231. etc. If I set the variables max and min directly to 10 and 1, the code works perfectly, returning numbers between 1 and 10. But for some reason, prompting input and then entering the exact same numbers gives completely different output. Why does this happen and how can I fix it?
The reason this happens is that the prompts are being treated as strings. So you're actually getting numbers between 1101 and 1.
You can ensure the vars min and max are numbers by using parseInt:
var max = parseInt(prompt("input 10"));
Try this Code below:
var max = Number(prompt("input 10"));
var min = Number(prompt("input 1"));
This is probably basic math that I don't seem to remember.
I'm trying to get from 0 to 5,000,000 in 10 seconds while having all the numbers ticking. I don't have to have the number reach exactly 5,000,000 because I can just do a conditional for it to stop when it's over.
Right now I have this:
count+= 123456
if (count > 5000000) {
count = 5000000;
}
It gives the sense of number moving you know? But It really starts off too high. I wanted to gradually climb up.
You could do something like this:
function timedCounter(finalValue, seconds, callback){
var startTime = (new Date).getTime();
var milliseconds = seconds*1000;
(function update(){
var currentTime = (new Date).getTime();
var value = finalValue*(currentTime - startTime)/milliseconds;
if(value >= finalValue)
value = finalValue;
else
setTimeout(update, 0);
callback && callback(value);
})();
}
timedCounter(5000000, 10, function(value){
// Do something with value
});
Demo
Note that with a number as big as 5000000 you won't see the last couple digits change. You would only see that with a small number like 5000. You could fix that; perhaps by adding in some randomness:
value += Math.floor(Math.random()*(finalValue/10000 + 1));
Demo with randomness
You can tween:
import fl.transitions.Tween;
import fl.transitions.easing.Regular;
var count = 0;
var tween:Tween = new Tween(this, "count", Regular.easeInOut,0,5000000,10, true);
This will tween you variable count from 0 to 5000000 in 10 seconds. Read about these classes if you want to expand on this code.
Tween
TweenEvent
Good luck!
This is my intent,
Generate random number
Store in variable
Clear variable
Generate new number greater than previous
Store in variable
I understand
(Math.floor(Math.random()*100)+1)
For 1-100 but not sure how to accomplish what I want exactly.
The following will generate a random number and then find the next random number it finds that is greater than it (or equal to it if it is greater than or equal to 99):
var num = Math.floor(Math.random()*100)+1;
alert(num); //current number
var newNum;
while((newNum = Math.floor(Math.random()*100)+1) < num && newNum < 100);
alert(newNum); //new number > num (or == num if num >= 99)
use
var ran_val = 1;
// ... some code goes here
ran_val = (Math.floor(Math.random()*100) + ran_val)
if you have no upper limit on the random numbers,
ran_val = (Math.floor(Math.random()*(100-ran_val)) + ran_val)
otherwise.
fwiw, the random numbers you emulate this way are no longer uniformly distributed.
var numb1 = Math.floor(Math.random()*100)+1, //Generate random number
numb2 = 0;
while (numb2<numb1) {
numb2 = Math.floor(Math.random()*100)+2; // Generate new number greater than previous
}
FIDDLE
You need to have a global variable and a function that handles the random number generation.
You can do something like this:
var num = 1;
function generaterandom(){
num = Math.floor(Math.random()*100)+num;
}
I'm creating a slider with 6 slides, and I want to randomly move between them, making sure that neither of the previous two slides are shown as the next slide. The functionality doesn't really matter, since what I'm really doing is generating random numbers and keeping track of the previous two. The first slide is always numbered 1, so for the first two iterations that'll be one of the previous numbers that can't be used.
Here's what I have so far, and it works fine for generating the random numbers in the range, but 'caching' the last two values doesn't work reliably:
var rand = Math.floor(Math.random() * 6) + 1;
var prev1 = 1;
var prev2;
function randomSlide() {
// 5 second interval between slides
// Don't show either of previous two slides next
random = setInterval(function() {
prev2 = prev1;
prev1 = rand;
do {
rand = Math.floor(Math.random() * 6) + 1;
} while (rand == prev1 || rand == prev2);
prev1 = rand;
$('#slider').anythingSlider(rand);
//console.log(prev1,prev2);
}, 5000);
}
function firstSlide() {
firstTime = setTimeout(function() {
randomSlide();
}, 5000);
}
firstSlide();
randomSlide();
It's quite simple I think but my brain's getting frazzled trying to parse the values of the two 'cache' variables at the first, and then each subsequent, iteration.
I'm executing a single iteration at the beginning because if randomSlide() executes on load then the first (welcome) slide doesn't get a chance to display.
When you do the prev1 = rand the second time after you've changed the value of rand, you're assigning the new slide's number to it. The next time you enter the loop you do prev2 = prev1, and since prev1 == rand it means that now all three variables prev1, prev2 and rand are the same. Just remove the second prev1 = rand.
Another issue is that you set the interval twice: first you call firstSlide() which executes randomSlide() after a 5 second delay (which sets one interval), then right after you call randomSlide() again which sets another interval.
Here's another (simpler?) approach to getting the result:
<script>
// Return a random number from 1 to 6, exclude
// the last two numbers.
var getRandom = (function() {
var a = [1,2,3,4,5,6];
return function() {
var i = (Math.random() * 4 ) | 0;
a[5] = a.splice(i,1);
return a[5];
}
}());
function writeRandom() {
document.getElementById('d0').innerHTML += getRandom() + '<br>';
}
setInterval(writeRandom, 100)
</script>
<div id="d0"></div>
Not exactly random for the first 2 iterations, but you can fix that by randomising the array when it's initialised. But likely it doesn't matter for a slide show.
It's less code, but the splice part makes it slower in the browsers I tested. My version of the OP is:
var getRandom2 = (function() {
var r0 = r1 = r2 = 1;
return function() {
r0 = r1;
r1 = r2;
do {
r2 = Math.floor(Math.random() * 6) + 1;
} while (r2 == r0 || r2 == r1);
return r1;
}
}());