dcsimg
A Flash Developer Resource Site

Results 1 to 4 of 4

Thread: Random Array Elements In Dynamic Text Box

  1. #1
    Junior Member
    Join Date
    Sep 2010
    Posts
    22

    Random Array Elements In Dynamic Text Box

    Hi,



    I have an array (named arrayFull), and I want my dynamic text box (named messageText) to display one random element from the array, changing once per second.

    The code I have makes it display all elements of the array at once in random order, changing once per second.

    How do I make it display just one element from the array at any given time?

    This is the code:



    var arrayFull:Array = new Array(1,2,3,4,5);
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    var myTimer:Timer = new Timer(1000, (arrayFull.length));
    myTimer.addEventListener(TimerEvent.TIMER, runOnce);
    myTimer.start();

    function runOnce(e:TimerEvent):void {
    messageText.htmlText="";
    updateText ();
    }

    var maximumMessages:Number = 1;
    var currentMessages:Number = 0;
    function updateText(){

    for (var i = currentMessages; i<maximumMessages; i++) {
    messageText.htmlText += arrayFull.sort(function () {
    return Math.random() ? true : false;
    });

    for (i = 0; i < 4; i++) {
    this[i].text = arrayFull[i];
    }
    }
    }

    Thank you for your help.

  2. #2
    Mod cancerinform's Avatar
    Join Date
    Mar 2002
    Location
    press the picture...
    Posts
    13,448
    messageText.htmlText += arrayFull[int(Math.random() * (arrayFull.length-1))];
    - The right of the People to create Flash movies shall not be infringed. -
    | www.Flashscript.biz | Flashscript Biz Classes/Components |

  3. #3
    Junior Member
    Join Date
    Sep 2010
    Posts
    22
    Thanks a lot! I've tried the same approach before, and forgot to use the int before the parentheses.

    Is there some way I can prevent it from showing the same element twice in a row?

  4. #4
    ___________________
    Join Date
    May 2004
    Posts
    3,174
    outside your function, create a variable to save the last shown random element:

    PHP Code:
    var lastShown:Number
    then when you assign it, check to make sure it doesn't match that - then set it again until it doesn't match. then set the lastShown variable to that new element:

    PHP Code:
    var randomElement:Number arrayFull[int(Math.random() * (arrayFull.length-1))];
    while(
    randomElement == lastShownrandomElement arrayFull[int(Math.random() * (arrayFull.length-1))];
    messageText.htmlText += randomElement;
    lastShown randomElement

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center