samedi 31 décembre 2016

Math.random in nested "for" loop not being random on each iteration in AS3

I have a function that takes a color and returns a similar color using Math.random

function randomizeColor(c:uint, off:int):uint{
    return Math.random() * off + c;

I have a Sprite that I construct instances of 26*8 times using a nested set of for loops. I have two different but similar methods for assigning a color to these Sprites. The first, which doesn't work, is to have the randomizeColor function be a function in the Sprites class .as file. Looks like this:

public function MySprite (w,h,color):void {
    var c:uint = colorRandomizer(color,15);
    // draw shape using new color "c"

private function colorRandomizer(c:uint,off:int):uint {
    // same function as above 

This strangely gives me 8 random colors repeated 26 times! 8 unique colors every time I restart the app.

However, if I instead pass an already randomized color to the constructor, I get a random color each of the 26*8 times the constructor is called. I've even followed the playhead through in debug mode and it iterates through the inner loop 8 times, getting random colors, and then increments the outer loop one time and then proceeds to return the same 8 colors on the inner loop. What gives?

Oh and here is what my for loops like ok like when it doesn't work

for (var i: int = 0; i < 26; i ++){
    for (var i: int = 0; i < 8; i ++){
        var s:mySprite = new MySprite(10,20,colorArray[i]);

So this should pass 8 preset colors 8*26 times (one preset color each time, 8 presets total) and then that color gets passed to the randomizing function in the class which then draws the shape filled with the returned randomized color. If instead I do

for (var i: int = 0; i < 26; i ++){
    for (var i: int = 0; i < 8; i ++){
        var randColor:uint = randomizeColor(colorArray[i],15);

var s:mySprite = new MySprite(10,20,randColor); } }

and change the constructor to just accept and use the color passed to it. When I do that, I get unique colors in each and every mySprite, not just for the inner for loop which then gives me 8 repeating colors. I'm probably over explaining at this point. Let me know if it's not clear. My code is simple enough you should be able to implement it easily in your own quick project to see it working and not working.

So even though I have a solution already, I want to know what is wrong with my understanding of the Math.random function or nested for loops or whatever my misunderstanding is. Do you see where my error in thinking or coding is?

Aucun commentaire:

Enregistrer un commentaire