Cycler tutorial (Array-based Letter randomizer)

Hey, this is my first tutorial!
Here it goes.

Just recently, I wanted to make my hit counter on my website display random characters before eventually showing the actual hit count. I read the two great tutorials on how to do this, but I didn’t want to quite do it the way they did. The difference with my method is that I don’t use ascii code, and there’s no movie clip duplication. I use strictly arrays of the letters, and randomize it there. My method also offers minimum and maximum number of times to randomize for each letter.

I call this: Cycler.

Attached is the .fla. I would suggest downloading it, but if you’re like me and would rather see the code right here; here it is. At the bottom, after the snippet, I have explanations of various critical parts of it.

At this point, it can get rather long, so if you have the patience, please read on.

<Start Snippet>

// Constants, as function literals (so they can’t be modified from the outside)
// However, the actual variables used during the cycle CAN still be modified :frowning:
getDefaultRandomChars = function(){return “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890”;};
getDefaultMinCycles = function(){return 5;};
getDefaultMaxCycles = function(){return 45;};

// Don’t change any of these from the outside
var cycleName = “”;
var randomChars = getDefaultRandomChars();
var minCycles = getDefaultMinCycles();
var maxCycles = getDefaultMaxCycles();
var clipInitialized = false;
var cycleInitialized = false;
var cycling = false;
var aNameOriginal = new Array();
var aNameCycled = new Array();
var aCycles = new Array();

onEnterFrame = function(){
if (!clipInitialized){
// Add any intialization here

	clipInitialized = true;
	return;
}

if (cycling){
	if (!cycleInitialized){
		// Initialize letter arrays
		aNameOriginal = String(cycleName).split("");
		aNameCycled = String(cycleName).split("");
		
		// Initialize the cycle counter
		aCycles = new Array(aNameCycled.length);
		for (i=0; i &lt; aCycles.length; i++){
			aCycles* = 0;	
		}
		
		cycleInitialized = true;
	}
	
	for(i=0; i &lt; aNameCycled.length; i++){
		// Goal: 	Cycle through each letter and randomize it
		//			Must randomize at least n times defined by minCycles
		//			Must stop randomizing after n times defined by maxCycles
		if (aCycles* &lt; minCycles){
			aNameCycled* = randomChars.charAt(random(randomChars.length));
			aCycles*++;
		}
		else{
			if (aCycles* &gt; maxCycles)
				aNameCycled* = aNameOriginal*;
			else
				if (aNameCycled* != aNameOriginal*){
					aNameCycled* = randomChars.charAt(random(randomChars.length));	
					aCycles*++;
				}
		}
	}
	
	// Output
	mainText.text = aNameCycled.join("");
	
	if (mainText.text == cycleName){
		// Reset and do a little cleanup
		cycling = false;
		cycleInitialized = false;
		cycleName = "";
		aNameOriginal = null;
		aNameCycled = null;
		aCycles = null;
	}
}

}

function Cycle(pcycleName, prandomChars, pminCycles, pmaxCycles){
// Apply defaults if necessary
if (pcycleName == undefined || pcycleName == “”) return;
if (prandomChars == undefined || prandomChars == “”) prandomChars = getDefaultRandomChars();
if (pminCycles == undefined || pminCycles < 1) pminCycles = getDefaultMinCycles();
if (pmaxCycles == undefined || pmaxCycles < 2) pmaxCycles = getDefaultMaxCycles();

// Validate
if (pminCycles &gt;= pmaxCycles){
	// user error, use defaults	
	pminCycles = getDefaultMinCycles();
	pmaxCycles = getDefaultMaxCycles();
}

cycleName = pcycleName;
randomChars = prandomChars;
minCycles = pminCycles;
maxCycles = pmaxCycles;

cycling = true;

}

<End Snippet>

Usage:
The main occurrence is for the parent to call the Cycle function. The first parameter (required) is the String you want to cycle on. The second Parameter (optional), is the list of random characters you want the cycle to use. The third and fourth Parameters (optional) define how many times you want random characters to cycle (min and max, respectively). That’s it, just call that function.

Explanation:
The first 3 lines are function literals, serving as my Constants. Not really sure why there isn’t away to define constants and/or protected variables :frowning: unless I’m missing something.

The next set of lines are just simple variable declarations. The most important of which are the arrays. I have arrays that hold the original and altered letters, as well as, an array to hold how many times each letter has been randomized.

The first function is another function literal. This is the onEnterFrame function. I use this quite a bit, as I try my best to “blackbox” all my movie clips. And in order to “blackbox” it, any initialization of variables and whatnot should be done inside the clip instead by the parent. In this function, this is where most the logic is. As the function is entered x number of frames per second (defined by your frames per second value), it loops through the array of letters (further down, I’ll explain how this is set) and randomizes them via randomCharacters variable. It will only randomize if it has not exceeded the maxCycles variable, and if it does, it simply uses the correct letter (from aNameOriginal array). After all characters have been randomized inside the aNameCycled array, it is then outputted to the mainText dynamic text control by calling the join() String function. The join() function joins all elements in the array into a string. The parameter passed in, is what delimits the elements. In this case, we want the characters contiguous; that’s why we pass in an empty string (""). After mainText is updated, the function needs to determine whether the next instance of the function still needs to randomize. If mainText equals what you want to be displayed, it turns off the cycling variable.

The next function is Cycle. This is what the parent clip should be calling. Usage is described above. This function takes the parameters, validates them, and applies default values if necessary. If everything is cool, the main variables (cycleName, minCycles, maxCycles) are set, and the cycling flag is turned back on.

Please email me on any comments or questions about this tutorial. When my site is up, you’ll be able to access this tutorial there, as well, and hopefully, in a better format than this.

Thanks.
JGo

Hmm, if it is the effect I am thinking of, this site already has two letter cycling tutorials…

http://www.kirupa.com/developer/flash5/randomlettercycling.asp

http://www.kirupa.com/developer/flash5/randomlettercycling2.asp

But there’s none for Flash MX. And no offence, JGo, but the code looks very long for such a small effect, doesn’t it? :slight_smile:

Hey Ilyas, the code in the Random Cycler tutorial 2 (went by that one because I like it better) looks pretty straightfoward. Is there an easier way in Flash MX to do the same thing? If so, that would be great because the amount of lines used in the first place isn’t a lot.

The only difference I can spot right now is random(), but its not like its that much harder to go from random() to Math.random()*x

But then again, I have never done the tutorial, didn’t even read it, and I didn’t examine the code that closely.

Yep, but with the new Flash MX tools (text creation and such), you could create everything with AS. I don’t know if this is covered in the new tute, but it could be interesting (even though it doesn’t bring anything groundbraking, you’re right :))

Yeah, you could dynamically create the text box inside a dynamically created movie clip, then apply the code through an onEnterFrame, all in actionscript.

But, yeah, theres not that much of a difference :P…lol.

:crazy:

Yep, it is exactly the same effect, just a different method of doing so. The first documented method generated the random letters using random numbers to represent the different ascii codes. Nothing wrong with that approach at all, except it’s harder to specify which random characters to use. For example, if you only want random characters to be purely numeric, then, you’d have to add extra code to only pick from a range of ascii codes. The second documented tutorial and mine improves on that method by allowing you to specify any characters to randomly pick from.

So now, the difference between my method and the 2nd documented method is that my method uses array variables versus the use of duplicated movie clips to represent each character.

The other unique difference between the two is the location of the onEnterFrame event handler. Kirupa’s method uses a pure function, while mine uses a function literal. This allows the function to exist inside my movie clip. This is purely my preference, as I like to keep functionality of each movie clip inside the movie clip itself, instead of outside of it. By doing so, my method allows you to simply drag n’ drop the movie clip, and simply call the Cycle function with the correct parameters. The parent doesn’t have to be cluttered up with the scripts that you really don’t care about (as long as it works).

Lastly, the difference between my method, and the other two, is that it allows you to further optimize the effect by allowing you to set how many times you want it to generate the random characters by allowing you to specify mininum and maximum cycles.

Example snippets of different possible scenarios:
(this assumes you have an instance of the movie clip and called it Cycler1)

  1. If you want to randomize the word “Hello”
    Cycler1.Cycle(“Hello”);

  2. If you want to randomize the word “Hello”, using random characters of “abcdefghij”
    Cycler1.Cycle(“Hello”,“abcdefghij”);

  3. If you want to randomize the word “Hello”, using random characters of “abcdefghij”, and randomizing at least 10 times and a maximum number of times of 60
    Cycler1.Cycle(“Hello”, “abcdefghij”, 10, 60);

p.s. I don’t know a whole lot of the workings behind the Flash engine, but it seems to me using arrays would be more efficient than using a duplicated movie clips. I’m certainly not knocking on any of the other methods at all, in fact, I give them credit for helping me come up with this method.

Thanks
Jayson

Yeah, it’s a bit long, and nothing ground-breaking…and of course no offense taken :cool:

In fact, a lot of the code in there could possibly be removed like the clipInitialized bit, which is in there, just for future things; or the validations done in the Cycle function, which is there for general data integrity protection, and same with the literal functions that I created for the default values.

I just thought I’d share. I certainly haven’t delved into AS, although I’ve read some about it and have planned on moving a lot of my common functions into it.

Thanks all.
Jayson

Oh, I see. That’s very interesting, JGo. I think we should keep it, but not necessarily as a tute. [SIZE=1]A commented fla, maybe?[/SIZE]