-3

I have an array of words in my code. What I'm hoping to do is display, at random, one word from the array onto the stage. How is this achievable?

Wirlly
  • 1
  • Create a `TextField` on the stage, and use `text` property to fill with a random word of yours. Simple. – Vesper May 18 '16 at 09:08

2 Answers2

0

For this you can use Math.random().

Returns a pseudo-random number n, where 0 <= n < 1.

function getRandomWord(array:Array):String
{
    var wordIndex:int=Math.floor(Math.random() * array.length);
    return array[wordIndex:int];
}

This function can be used to dynamically set the value of the text box on the stage:

myTextField_txt.text = getRandomWord(wordArray);

You can read more about Math.Random() here in the documentation: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Math.html#random()

Smittey
  • 2,475
  • 10
  • 28
  • 35
  • This is what I have var myArray:Array = new Array("Carrot", "Apple", "Grape", "Bannana"); function getRandomWord(myArray:Array):Object { var wordIndex:int=Math.floor(Math.random() * array.length)); return array[wordIndex:int]; } myTextField_txt.text = getRandomWord(wordArray); – Wirlly May 18 '16 at 09:56
  • You haven't changed the variable names in the function to match yours. It seems that you aren't feeding in the correct array, it should be `myTextField_txt.text = getRandomWord(myArray);`. You also need to change to `array.length` to `myArray.length`, and `return array[wordIndex:int]` to `return myArray[wordIndex:int];`. Your variables aren't consistent. Just a note, the function return type should probably be changed from `Object` to `String`. – Smittey May 18 '16 at 10:21
0
var myWords: Array = ["DOG", "CAT", "RABBIT", "HORSE", "COW"]
var randomNumber: int = (Math.Random() * myWords.length);

stage.addEventListener(MouseEvent.CLICK, getRandom);

function getRandom(e: MouseEvent) {
  myTextField.text = myWords[randomNumber].toString();
  randomNumber = (Math.Random() * myWords.length);
}

You'll need a dynamic text field with the instance name of "myTextField". Also, in the properties of the text field embed the font to ensure it doesn't cause any issues. Then add this code to the frame. Ctrl + Enter to test the movie. Then click anywhere on the stage.

Good luck!

withayk
  • 134
  • 2
  • 10