Resetting an array

Hi all.
I have created a game with my trusted AS3 CIB series! Its a simple game that when the user collects or drops 10 pieces of fruit the game ends. And displays if you won or lost. (Code is below)
I have created a button (play_btn) that displays when the game finishes. What i am trying to achieve is when you press the button, the game starts again. I have created a listener and a function "startAgain" that resets the fruitLost and fruitCollected variable that i think i should do. But what i am having problems with is resetting the fruitsOnStage array and executing the for loop to create ten items of the fruitsOnStage array. I know the .splice command removes them from the array but what is the easiest way to add them back. Think i'm on the right lines but have no idea how to achieve this!!!
Any help is greatly appreciated
Cheers
import flash.display.MovieClip;
import flash.events.Event;
var fruitArray:Array=new Array(Apple,Banana,Strawberry,Orange,Pear);
var enemy:Array=new Array(blob);
var fruitsOnStage:Array = new Array();
play_btn.visible=false;
var fruitLost:int=0;
var fruitCollected:int=0;
function startAgain(e:Event):void
fruitLost=0;
fruitCollected=0;
trace("Hello again");
stage.addEventListener(Event.ENTER_FRAME, startGame);
for (var i:int = 0; i <10; i++) {
var pickFruit=fruitArray[int(Math.random()*fruitArray.length)];
var fruit:MovieClip = new pickFruit();
addChild(fruit);
fruit.x=Math.random()*stage.stageWidth;
fruit.y=Math.random()*-500;
fruit.speed=Math.random()*15+5;
fruitsOnStage.push(fruit);
stage.addEventListener(Event.ENTER_FRAME, startGame);
function startGame(e:Event):void
for (var i:int= 0; i <20; i++) {
var currentFruit:MovieClip=fruitsOnStage[i];
currentFruit.y+=currentFruit.speed;
if (currentFruit.y>stage.stageHeight-currentFruit.height) {
currentFruit.y=0-currentFruit.width;
fruitLost++;
field1_txt.text="You lost "+fruitLost+" pieces of fruit you loser";
if (currentFruit.hitTestObject(basket_mc)) {
fruitCollected++;
removeChild(currentFruit);
field2_txt.text="You collected "+fruitCollected+" Bravo";
fruitsOnStage.splice(i,1);
if (fruitsOnStage.length<=0) {
field1_txt.text="You won!!!";
play_btn.visible=true;
stage.removeEventListener(Event.ENTER_FRAME, startGame);
play_btn.addEventListener(MouseEvent.CLICK, startAgain);
if (fruitLost>=10) {
field1_txt.text="You lost, MUPPET";
play_btn.visible=true;
play_btn.addEventListener(MouseEvent.CLICK, startAgain);
stage.removeEventListener(Event.ENTER_FRAME, startGame);
basket_mc.addEventListener(MouseEvent.MOUSE_DOWN, startDragg);
function startDragg(e:Event):void
basket_mc.startDrag();
basket_mc.addEventListener(MouseEvent.MOUSE_UP, stopDragg);
function stopDragg(e:Event):void
basket_mc.stopDrag();

Another thing - you don't remove previous fruits from stage. This code does it in removeAll() function:
import flash.display.MovieClip;
import flash.events.Event;
var fruitArray:Array = new Array(Apple, Banana, Strawberry, Orange, Pear);
var enemy:Array = new Array(blob);
var fruitsOnStage:Array = new Array();
play_btn.visible = false;
var fruitLost:int = 0;
var fruitCollected:int = 0;
basket_mc.addEventListener(MouseEvent.MOUSE_DOWN, startDragg);
basket_mc.addEventListener(MouseEvent.MOUSE_UP, stopDragg);
init();
function init(e:Event = null):void {
     // reset array
     removeAll();
     fruitLost = 0;
     fruitCollected = 0;
     var pickFruit:Class;
     var fruit:MovieClip;
     for (var i:int = 0; i < 10; i++) {
          pickFruit = fruitArray[int(Math.random() * fruitArray.length)];
          fruit = new pickFruit();
          addChild(fruit);
          fruit.x = Math.random() * stage.stageWidth;
          fruit.y = Math.random() * -500;
          fruit.speed = Math.random() * 15 + 5;
          fruitsOnStage.push(fruit);
     stage.addEventListener(Event.ENTER_FRAME, startGame);
function removeAll():void {
     for each(var mc:MovieClip in fruitsOnStage) {
          removeChild(mc);
          mc = null;
     fruitsOnStage = [];
function startGame(e:Event):void {
     var currentFruit:MovieClip;
     for (var i:int = 0; i < fruitsOnStage.length; i++) {
          currentFruit = fruitsOnStage[i];
          currentFruit.y += currentFruit.speed;
          if (currentFruit.y > stage.stageHeight - currentFruit.height) {
               currentFruit.y = 0 - currentFruit.height;
               fruitLost++;
               field1_txt.text = "You lost " + fruitLost + " pieces of fruit you loser";
          if (currentFruit.hitTestObject(basket_mc)) {
               fruitCollected++;
               removeChild(currentFruit);
               field2_txt.text = "You collected " + fruitCollected + " Bravo";
               fruitsOnStage.splice(i, 1);
          if (fruitsOnStage.length == 0) {
               field1_txt.text="You won!!!";
               play_btn.visible = true;
               stage.removeEventListener(Event.ENTER_FRAME, startGame);
               play_btn.addEventListener(MouseEvent.CLICK, init);
          if (fruitLost >= 10) {
               field1_txt.text="You lost, MUPPET";
               play_btn.visible = true;
               play_btn.addEventListener(MouseEvent.CLICK, init);
               stage.removeEventListener(Event.ENTER_FRAME, startGame);
function startDragg(e:Event):void {
     basket_mc.startDrag();
function stopDragg(e:Event):void {
     basket_mc.stopDrag();

Similar Messages

  • Clearing, Reset, Removing Array Int.

    I'm having a problem with a small class exersize. So far I am able to find the max, min, and average of the grades. As well as have them being entered. My teacher recently wanted us to add a try/catch methods so in case a user enters a negative grade it will catch it.
    Ok...so that works. But now when the user enters new grades, and then decides to select the average, it averages some of the grades from the previous entries. Then the max, min cannot be found either.
    This program is based on a switch method with cases. Here is the first case. where the grades are entered and the try and catch method is use.
    I know, or at least I think I know that I need to clear or reset the array so that new entries can be entered successfully. I looked all over the net. I saw methods such as these:
    gradebook.clear()
    gradebook.remove()
    removeAll()I played around with them for a bit to see what I can get out of it, but nothing is working. These methods are not recognized. Any suggestions guys/gals?
    If I cant find a solution I will have the user select case 5 and exit the program and start it over. No biggy.
    Thanks !
    Mike
    public class GradeBookSolution2
      public static void main(String[] args)
        Scanner keyboard = new Scanner(System.in);
        int[] gradebook = new int[11];
        int grade = 0;
        int choice = 0;     
        while(choice != 5)
             Menu();
             choice = keyboard.nextInt();
             switch(choice)
                case 1:
                System.out.println("Please enter 10 class grades followed by any number.");
                try
                    for (int i = 0; i < 11; i++)
                         gradebook[i] = grade;                          grade = keyboard.nextInt();
                         if(grade < 0)                     
                              throw new IOException("Exception: YOU CANNOT HAVE A NEGATIVE GRADE");                    
              catch(IOException e)           
            removeAll(); //  <-- This is where and when I want to clear the array?
           System.out.println(e.getMessage());
           //System.out.println("Please exit the program and start over");
    break;

    The methods you are trying to use are part of the Collections API. arrays do not have these methods you would need to use a Collection like an array that would have these methods... like an ArrayList for example.

  • Reset Array element when i run the program once

    Hi every body , i have seem many topic about reset the array element.but i can't do that well
     I want to reset all the element inside the array to the " gray color " ( the condition when i reopen the VI )
    once i run the program by clicking the buttom.
    Is there any method ?
    I have attached the pic for your reference
    Thank You
    Attachments:
    array.jpg ‏13 KB

    Post your VI with whatever method you did that you say doesn't work for you.  You must have done something wrong and we won't know what until we see the code.  Here is what it should look like.
    Message Edited by Ravens Fan on 03-02-2009 11:00 PM
    Attachments:
    Example_VI_BD.png ‏2 KB

  • DBMS_SQL array processing - ORACLE 8.0.6

    It's been a while since I've used this.
    DEFINE_ARRAY - the last parameter is "lower bound", which is the starting point. If it's set to 1, rows will be placed in the array starting with 1 and ending with the last row fetched. The entire result set from the EXECUTE appears to be loaded into memory using the array. Fetch 1 will retrieve rows 1 - 10, and put them in array loc. 1 - 10, next fetch will return 11 - 20 and put them in array loc 11-20.
    I don't remember it being this way. Why can I not reset the array, load 10 at a time in array locations 1-10, and re-use 1-10 for each fetch? Will I not eventually blow something up if too much is loaded into the array?
    Also, why would I want to set lower bound to anything other than 1? Why would I want to use -10 to 9, or 0 to 20, or other ranges? What purpose does this capability serve?
    (Of course, back then I used host arrays in PRO*COBOL. It must have been different.)
    Thanks.
    KL

    If you do not care about the rows fetched from a prior call to FETCH, you can do a .DELETE on the collection to remove any existing elements and thus freeing the memory.
    The index positions will still start from the next available index position, so you should use .FIRST and .LAST on the collection.
    If you have a set of queries that you run one after the other and these queries produce the end result in the same format as the previous, then you may want to keep the previous rows in the collection, and start from the next available index.

  • How to clear two dimension array and content in JTextArea

    hi all....
    i have a problem to clear the counter in JTextArea..currently i design a program to store all the student details in two dimensian array...when i click "RESET"button..it will only reset the textarea..but can not clear the actual content inside the array..and when i click "Print Button" again..it's supposed nothing to display..but it displayed the thing which i previously entered......
    so i think i need to clear the array...i use append to insert the text...,for this i also can not reset...
    which the code is shown below :
    txtArea.append(msg1);
    the coding for reset area as below :
    txtArea.setText("")
    Anyone can help me?????
    thks...

    How are you trying to reset the array?, you can just creat a new array.
    Noah

  • How to quickly clear an array used in a shift register?

    Hello all,
    I'm sure this is a quick one, but I'm missing the concept.
    I have an array of boolean in a shift register. I have a case where I need to basically 'reset' the array rather than append to it....what is the best way to do this?
    Thank you,
    cayenne
    Solved!
    Go to Solution.

    stevem181 wrote:
    Of course, it is possible that my benchmark program is flawed.
    Yup, disable debugging and you will see that the inner FOR loop is folded in both cases and the time drops to about zero.
    Testing with debugging enabled is potentially unfair, because the reshaping will have more debugging code because there are more potential places to probe a wire, for example. All that said, I don't really know what's more efficient. That would require much more sophisticated testing. My point was just a reminder that there are always many ways to do things.
    (This is under LabVIEW 2012. Constant folding and dead code elimination of course differ between compiler versions)
    Granted, I typically don't use any of these two versions: I also omit the diagram constant, set the tunnel to "use default if unwired" and keep in unwired in the "clear" case. Less diagram clutter and quicker coding.
    Here's how it would look like.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    Folding.png ‏13 KB
    UseDefault.png ‏3 KB

  • Activated Dynamic Array

    I have the following problem:
    In my main loop, i have a signal processing SubVI that generates results only after a few iterations. For example, the loop iterates 1000x and, during the runtime, this SubVI produces 16 numbers (can vary) that need to be stored in a array.
    I have found the solution in attachment, but i fear this isnt a good solution. Is there an alternative?
    Thanks!
    Attachments:
    array dinamica (SubVI).vi ‏9 KB

    While you created a simple LV2 style global, there are several issues (that don't really mattter if you only generate 16 elements, but could be useful in the future).
    Appending an element to the front of the array is significantly more expensive than appending an element to the back, you might want to swap the inputs.
    The code is relatively disfunctional, because it is initialized on first call and you can only ever add elements, never reset the array for re-use, etc. until the program is restarted.
    You did not really explain how this is used? Is it (1) only read out after all elements are in it or is the (2) array monitored asynchronously from a second loop? In the case of (1), you should place the shift register in the main loop instead of a subVI (or inline the subVI). You could also use a queue instead.
    LabVIEW Champion . Do more with less code and in less time .

  • How to empty an array? Just a constant doesn't work.

    Hello,
    for a reset-function I want to "reset" an array. Meaning to empty it completely. I connected the local variable of the array to a zero constant, which seems to work fine, but as soon as I fill in some new elements in this array, the old elements appear too. Then I tried it by getting the array-size and letting a foor-loop set a constant for each element of the array. Didn't work either.
    What can I do? Thanks for the answer.

    If the array control is being set to a zero length array using a local
    variable, that should work. It sounds line the contents of the array are
    being stored in an internal buffer and new elements are appended to this
    buffer, and not to the array defined in the control.
    One possibility- loops with shift registers. This is simple and you should
    know if you've put some in there!
    Second more subtle possibility; if you have a loop and the wire from the
    control passes into the loop from the outside, the point of entry of the
    wire into the loop contains the data that was in the control at the time the
    loop started; subsequent writes to this control by a local will not change
    the data in the loop. You need to move the control terminal inside the loop
    for changes
    in the control data to be picked up by code within the loop. You
    could of course use a local inside the loop, however I believe the terminal
    is a more efficient way of accessing the control than a local is, and the
    point of most frequent access should have the terminal.
    Dennis Knutson wrote in message
    news:[email protected]..
    > Use either Initialize Array or the Delete from Array function. The
    > Initialize Array is probably faster.

  • Read from text file

    Hi, I need little help with the following application. I need to to read the items from the file, process them and save them in other file. I think I am on the right path but now I got stuck with the illegal start of the expression when I am declaring the arrays for the items and prices. Can anyone help me pls.
    public class AlaCarte extends JFrame implements ActionListener
       private JList yourChoices;
       private JTextArea  bill;
       private Container pane;
       public AlaCarte()
          super("Welcome to George's Kiosk");
             //Get the content pane and set its background color
             //and layout manager.
          pane = getContentPane();
          pane.setBackground(new Color(0, 200, 200));
          pane.setLayout(new BorderLayout(5, 5));
              //Create a label and place it at NORTH. Also
              //set the font of this label.
          JLabel yourChoicesJLabel = new JLabel("A LA CARTE MENU");
              //Create a list and place it at WEST. Also
              //set the font of this list.
          yourChoices = new JList(yourChoicesItems);
              //Create a text area and place it at EAST. Also
              //set the font of this text area.
          bill = new JTextArea();
              //Create a button and place it in the SOUTH region and
              //add an action listener.
          JButton selectionButton = new JButton("Selection Completed");
            JButton reportButton = new JButton("Daily Report");
          pane.add(reportButton,BorderLayout.SOUTH);
          reportButton.addActionListener(this);
          setSize(500, 360);
          setVisible(true);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
               //Method to display the order and the total cost.
       private void displayBill()
          int[] listArray = yourChoices.getSelectedIndices();
          double localTax = 0.01;
              double stateTax = 0.06;
          double localTaxes;
              double stateTaxes;
          double subTotal = 0;
          double total;
             //Set the text area to non-edit mode and start
             //with an empty string.
          bill.setEditable(false);
          bill.setText("");
              //Calculate the cost of the items ordered.
          for (int index = 0; index < listArray.length; index++)
              subTotal = subTotal
                         + yourChoicesPrices[listArray[index]];
          localTaxes = localTax * subTotal;
              stateTaxes = stateTax * subTotal;
              total = subTotal + localTaxes + stateTaxes;
              //Display the costs.
          bill.append("           GEORGE'S CAFE A LA CARTE\n\n");
          bill.append("--------------- Welcome ----------------\n\n");
          for (int index = 0; index < listArray.length; index++)
             bill.append(yourChoicesItems[listArray[index]] + "\n");
          bill.append("\n");
          bill.append("SUB TOTAL\t\t$"
                     + String.format("%.2f", subTotal) + "\n");
          bill.append("STATE TAX      \t\t$"
                     + String.format("%.2f", stateTaxes) + "\n");
               bill.append("LOCAL TAX      \t\t$"
                     + String.format("%.2f", localTaxes) + "\n");
          bill.append("TOTAL    \t\t$"
                     + String.format("%.2f", total) + "\n\n");
          bill.append("Thank you - Have a Nice Day\n\n");
              reportFile.println("State tax: " + stateTaxes + "n\n");
              reportFile.println("Local tax: " + localTaxes + "n\n");
              reportFile.println("Total sale: " + total + "n\n");
              reportFile.close();
              //Reset list array.
          yourChoices.clearSelection();
          repaint();
       public void actionPerformed1(ActionEvent event)
          if(event.getActionCommand().equals("Selection Completed"))
             displayBill();
          public void actionPerformed2(ActionEvent event)
          if(event.getActionCommand().equals("Daily Report"))
             displayReport();
         private void displayReport() {
       public static void main(String[] args)throws IOException
              FileReader itemsReader = new FileReader("Items.txt");
              BufferedReader br = new BufferedReader(itemsReader);          
              String itemName;
              double itemPrice;
              String line = br.readLine;
              while (line != null) {
              int blank = line.indexOf(" ");
              String itemName = line.substring(0, blank);
              String itemPrice = line.substring(blank +1, blank + 4);
              static String[] yourChoicesItems = itemName;                      
            static double[] yourChoicesPrices = itemPrice;
              PrintWriter reportFile = new PrintWriter("Report.txt");
              FileReader reportReader = new FileReader("Report.txt");
          AlaCarte alc = new AlaCarte();
         }

    This is what I get from compiler:
    AlaCarte.java:10: AlaCarte is not abstract and does not override abstract method actionPerformed(java.awt.event.ActionEvent) in java.awt.event.ActionListener
    public class AlaCarte extends JFrame implements ActionListener
    ^
    AlaCarte.java:13: cannot find symbol
    symbol : variable itemName
    location: class AlaCarte
         String[] yourChoicesItems = itemName;
         ^
    AlaCarte.java:14: cannot find symbol
    symbol : variable itemPrice
    location: class AlaCarte
    double[] yourChoicesPrices = itemPrice;
    ^
    AlaCarte.java:110: cannot find symbol
    symbol : variable reportFile
    location: class AlaCarte
              reportFile.println("State tax: " + stateTaxes + "n\n");
              ^
    AlaCarte.java:111: cannot find symbol
    symbol : variable reportFile
    location: class AlaCarte
              reportFile.println("Local tax: " + localTaxes + "n\n");
              ^
    AlaCarte.java:112: cannot find symbol
    symbol : variable reportFile
    location: class AlaCarte
              reportFile.println("Total sale: " + total + "n\n");
              ^
    AlaCarte.java:113: cannot find symbol
    symbol : variable reportFile
    location: class AlaCarte
              reportFile.close();
              ^
    7 errors
    I am apparently not passing the strings for itemName and itemPrice to the AlaCarte class. Should I declare it in the AlaCarte class?

  • Accessing the same object from multiple classes.

    For the life of me I can't workout how I can access things from classes that haven't created them.
    I don't want to have to use "new" multiple times in seperate classes as that would erase manipulated values.
    I want to be able to access and manipulate an array of objects from multiple classes without resetting the array object values. How do I create a new object then be able to use it from all classes rather than re-creating it?
    Also I need my GUI to recognize the changes my buttons are making to data and reload itself so they show up.
    All help is good help!
    regards,
    Luke Grainger

    As long as you have a headquarters it shouldn't be to painfull. You simply keep a refrence to your ShipDataBase and Arsenal and all your irrellevant stuff in Headquarters. So the start of your Headquarters class would look something like:
    public class Headquarters{
      public Arsenal arsenal;
      public ShipDatabase db;
    //constructor
      public Headquarters(){
        arsenal = new Arsenal(this, ....);
        db = new ShipDatabase(...);
    //The Arsenal class:
    public class Arsenal{
      public Headquarter hq;
      public Arsenal(Headquarter hq, ....){
        this.hq = hq;
        .Then in your ShipDatabase you should, as good programing goes, keep the arraylist as a private class variable, and then make simple public methods to access it. Methods like getShipList(), addToShipList(Ship ship)....
    So when you want to add a ship from arsenal you write:
    hq.db.addToShipList(ship);
    .Or you could of course use a more direct refrence:
    ShipDatabase db = hq.db;
    or even
    ShipList = hq.db.getShipList();
    but this requires that the shiplist in the DB is kept public....
    Hope it was comprehensive enough, and that I answered what you where wondering.
    Sjur
    PS: Initialise the array is what you do right here:
    //constructor
    shipList = new Ship[6];
    shipList[0] = new Ship("Sentry", 15, 10, "Scout");
    " " " "etc
    shipList[5] = new Ship("Sentry", 15, 10, "Scout");PPS: To make code snippets etc. more readable please read this article:
    http://forum.java.sun.com/faq.jsp#messageformat

  • Is there a way to simplify this? applying functions to 16 channels - software trigger

    hey,
    at first I want to appologize for hurting everybodies eyes.
    Today I ended up with a pretty weird VI and I was wondering if there is any way to do this a littler easier.
    Basicly I want to acquire 16 channels from a device. Unfortunately the device doesn't support analog trigger, so I had to create a software solution. So, I m reading 100 samples on all of the 16 channels in a while loop and compare the first channel, if its value reaches a certain threshold. If it does I end the while loop and enter a for loop, which read 100 samples 10 times. Before exiting the for loop I seperate the 16 channels - so I end up with 16 different arrays of 10 x 100 samples. Then I reshape the Array in order to get a one dimensional array with 1000 samples. At that point I have to do that for every channel seperately. After that I add the 100 samples which I acquired in the while loop in the beginning (which was the trigger) to the 1000 Samples Array. I end up with a array for every channel, which is 1100 samples long.
    As you could see in the attached image, this looks pretty confusing in the end. Is there any way to make that easier and look nicer?
    I know, I could add functions to reshape the arrays in order to end up with an 3 dimensional array (16 channels x 10 x 100 samples) then I could process everything in a for loop - but I guess that would take longer to calculate in the end?!? Any good ideas on that, except buying new hardware with a analog trigger?
    Attachments:
    weirdlabv.jpg ‏131 KB

    as far as I know, my hardware only has memory for 4095 Samples -  when acquiring 16 channels at once, I am able to read chunks not bigger than 256. is this right?
    I am not sure, if I still have some DDT in my latest vi left when converting the sample points as arrays of doubles. I will check that tomorrow, can't remember how I did that in the end. But everything seems to work finde so far. Thank you.
    However, there are still some basic questions:
    I have different parts in my vi, which relate to each other. For example, I have a array which is loaded from a file & edited by the user.  When finishing editing this array the user presses a button and continues with a different part of the vi, which uses the entered data. Therefore a part of the vi should not run before a other is finished. I used a combination of a event structure and a message queue. Is there a simpler way to realize such a construct?
    Just was thinking about creating Sub-VIs - apparently I could get rid of the queues then.. will try that tomorrow..
    If I create an empty array in order to enter values by the user during runtime, the array size increases at the moment I enter a value. In case I entered a value in the wrong field und want to deleted that value again and reset the arrays size to the size it had (before I entered the value)  - how do I do that? There is the right-click-option 'reset to default value', but this only sets the value to 0 in an numeric array, not deletes that field (row, whatever..)

  • PROBLEM IN LOADING XML SECOND TIME

    HI,
    Actually i m loading xml 1st time when the page is loading,then again 2nd time when i m trying to load 2nd xml based on dropdown value then it is loading xml but it is appending the 2nd xml with the 1st xml.i m also unloading xml at first then loading 2nd xml but it is cming like that.the code is for loading and unloading is........
    for loading i m calling---------------load_xml(xml)
    for unloading i m calling------------- unload_xml()
    function unload_xml():void
    trace("in unload")
    this.removeChild( flashmo_item_group );
    function push_array(e:Event):void
    flashmo_xml = XML(e.target.data);
    total = flashmo_xml.item.length();
    for( i = 0; i < total; i++ )
      flashmo_item_list.push( { content: flashmo_xml.item[i].content.toString() } );
    load_css();
    function load_xml(xml_file:String):void
    var xml_loader:URLLoader = new URLLoader();
    xml_loader.load( new URLRequest( xml_file ) );
    xml_loader.addEventListener(Event.COMPLETE, push_array);
    xml_loader.addEventListener(IOErrorEvent.IO_ERROR, io_error);
    function load_css():void
    css_loader.load( new URLRequest(css_file) );
    css_loader.addEventListener(Event.COMPLETE, css_complete);
    css_loader.addEventListener(IOErrorEvent.IO_ERROR, io_error);
    function css_complete(e:Event):void
    var css_format:TextFormat = new TextFormat();
    flashmo_style.parseCSS(css_loader.data);
    create_item_list();
    flashmo_loading.visible = false;
    function io_error(e:IOErrorEvent):void
    flashmo_loading.xml_info.text += "\n\n" + e;
    function create_item_list():void
    for( i = 0; i < total; i++ )
      var flashmo_item = new MovieClip();
      flashmo_item.addChild( create_item_desc( flashmo_item_list[i].content ) );
      flashmo_item.addChildAt( create_item_bg( flashmo_item.height, i ), 0 );
      flashmo_item.y = item_height;
      item_height += flashmo_item.height + item_spacing;
      flashmo_item_group.addChild( flashmo_item );
    this.addChild( flashmo_item_group );
    flashmo_item_group.mask = flashmo_mask;
    flashmo_sb.scrolling("flashmo_item_group", "flashmo_mask", 0.40); // ScrollBar Added
    function create_item_bg( h:Number, item_no:Number )
    var fm_rect:Shape = new Shape();
    fm_rect.graphics.beginFill(0xFFFFFF, 1); // ITEM BACKGROUND COLOR
    fm_rect.graphics.drawRoundRect(0, 0, item_width, h + item_padding * 2, 0);
    fm_rect.graphics.endFill();
    return fm_rect;
    function create_item_desc( item_desc:String )
    var fm_text = new TextField();
    fm_text.x = item_padding;
    fm_text.y = item_padding;
    fm_text.width = item_width - item_padding * 2;
    fm_text.styleSheet = flashmo_style;
    fm_text.htmlText = item_desc;
    fm_text.multiline = true;
    fm_text.wordWrap = true;
    fm_text.selectable = true;
    fm_text.autoSize = TextFieldAutoSize.LEFT;
    return fm_text;
    flashmo_sb.alpha=1;
    so plz give me idea to resolve this problem.

    function push_array(e:Event):void
        flashmo_item_list = [];
    flashmo_xml = XML(e.target.data);
    total = flashmo_xml.item.length();
    for( i = 0; i < total; i++ )
      flashmo_item_list.push( { content: flashmo_xml.item[i].content.toString() } );
    load_css();
    that will reset your array.

  • Flash grinding to a halt because is not unloading media

    hi guys,
    i've a got a huge (relatively) problem ni that i've created a Flash app with a dynamic data structure which ends in 150 different nodes.
    each node (if visited) loads in between 5-10 images and a couple of movies.
    The data for each node and its consequent external media are all displayed in the same visual class that is only instantiated once.
    The display object that contains the jpgs and movies is cleared of all child objects before the next node loaded.
    Yet the size of the flash file (according to windows task manager) never shrinks and very soon reaches 1mb in size at which point it starts to chuc badly.
    It's my understanding - even though i'm using 'removeChild' on each object and resetting any references to the said child objects - that they are not being removed from teh cached memory and for whatever reason not being picked up/emptied by the garbage collector?
    Does this sound about right?
    If so, can anyone suggest HOW i can make it so that the loaded media is removed from memory when it is element is removed (removeChild etc)
    All help greatly recieved as this project is due to be delivered later this week!
    regards, Rich
    Ps.  running on Windows XP SP3, Firefox, FlashPlayer 10, Flash CS4 published for Flash player 9, written in AS3, all external meia is *.jpg and *.flv

    hmm, good article which makes sense.
    i'm using removing the container from the stage using removeChildAt()
    and then reseting the array that stored the references to the items that were within the container.
    there don't seem to be any other references, the loaded objects are not referenced or passed around outside of the container
    if you can't force garbage collection can you adjust the threshhold or what triggers it.
    I am, at this stage, unsure whether the items are marked for collection but it isn't firing or it it's firing but they're somehow (as you say - likely through being referenced) not being marked.
    is there any way to track an objects reference count?

  • Calendar program

    HI All,
    I'm a student of Java and recently stumbled across this site. Its fab, excellent work!
    I am working on a program that just prints out a Calendar of a specified year. I have it working fine except one thing :)
    From the year specified the program works out leap years, the day a month starts on etc.. However,
    Line 117-122 has an error somewhere. It returns an ArrayOutOfBounds error, so i added an if command to reset the array pointer, now the output has changed and i can't work out what i'm doing wrong.
    Any help greatly appreciated.
    Many thanks.
    Ken.
    import java.util.*;
    public class mycal2379122 {
         static void nl(int n) {
              // Procedure for creating new lines, n times on screen.
         for (int j = 0; j < n; j++) {
              System.out.println();
         static String padMonth(String s) {
              // Function to take a string as a parameter and return it with stars appended
              String ch = "--------------------";
              s = s.substring(0,s.length()) + ch.substring(s.length(),ch.length());
              return s;
         static int[] getStartDays(int y) {
              // Function to return an int array holding the start days for each month in y
              // where 0 = Monday ... 6 = Sunday
              int[] startDays = new int[12];
              int[] daysInYear = daysInYear(y);
              int firstDay = ((y - 1900) * 365 + (y - 1901) / 4) % 7;
              for (int i = 0; i < 12; i ++) {
                   if (i == 0) {
                        startDays[i] = firstDay;
                        firstDay = (firstDay + daysInYear) % 7;
                   else {
                        startDays[i] = firstDay;
                        firstDay = (firstDay + daysInYear[i]) % 7;
              return startDays;
         static int[] daysInYear(int y) {
              if (isLeap(y)) {
                   int DaysInMonth[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
                   return DaysInMonth;
              else {
                   int DaysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
                   return DaysInMonth;
         static boolean isSingle(int d) {
              if (d <= 9) {
                   return true;
              else {
                   return false;
         static boolean isLeap(int y) {
              // function to return true if y is a leap year, otherwise false.
              if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
                   return true;
              else {
                   return false;
         static void getMonth(int monthName, int startDay, int numDays) {
              String days[] = { "Mo.", "Tu.", "We.", "Th.",
                   "Fr.", "Sa.", "Su." };
              String months[] = { "JANUARY.", "FEBUARY.", "MARCH.", "APRIL.",
              "MAY.", "JUNE.", "JULY.", "AUGUST.", "SEPTEMBER.",
              "OCTOBER.", "NOVEMBER.", "DECEMBER." };
              String row[] = { "", "", "", "", "", "", "", "" };
              int startPos = 1 - startDay, count = 0, currentRow = 2;
              String buildRow = "";
              // Populate month grid with data
              // The only thing to change here is the month name
              row[0] = padMonth(months[monthName]);
              // This row will never change
              row[1] = "Mo.Tu.We.Th.Fr.Sa.Su";
              // 6 rows by 20 colums left
              for (int i = 2; i < 8; i ++) {
                   row[i] = "....................";
              // loop to build a single row in grid
              for (int d = startPos; d != 42-startPos; d++) {
                   if (d >= 1 && d <= numDays) {
                        if (isSingle(d)) {
                             buildRow = buildRow + " ";
                        buildRow = buildRow + d;
                   else {
                        buildRow = buildRow + " ";
                   count ++;
                   if (count == 7) {
                        count = 0;
                        row[currentRow] = buildRow;
                        buildRow = "";
                        currentRow ++;
                        if (currentRow == 7) { currentRow = 2; }
                   else {
                        buildRow = buildRow + " ";
              //print grid
                   for (int i = 0; i < 7; i ++) {
              System.out.println(row[i]);
         public static void main(String[] args) {
         Scanner input = new Scanner(System.in);
         int year = 0;
         int i = 0;
         String[] monthGrid = new String[8];
         String[] concatGrid = new String[8];
         // Force year within range
         while (year < 1901 || year > 2099) {
              System.out.print("Please enter a year in range of 1901-2099: " );
              year = input.nextInt();
         // At this stage i know the year & can work out the start days for each month.
         int startDays[] = getStartDays(year);
         int daysInYear[] = daysInYear(year);
         while (i != 20) { // testing loop
              i = input.nextInt();
              getMonth(i,startDays[i],daysInYear[i]);

    HI, Sorry i didn't know about the CODE Tags for the forums...
    Here is the code re-posted with the code tag, Thanks for the help guys. Its much appreciated.
    import java.util.*;
    public class mycal2379122 {
         static void nl(int n) {
              // Procedure for creating new lines, n times on screen.
             for (int j = 0; j < n; j++) {
                  System.out.println();
         static String padMonth(String s) {
              // Function to take a string as a parameter and return it with stars appended
              String ch = "--------------------";
              s = s.substring(0,s.length()) + ch.substring(s.length(),ch.length());
              return s;
         static int[] getStartDays(int y) {
              // Function to return an int array holding the start days for each month in y
              // where 0 = Monday ... 6 = Sunday
              int[] startDays = new int[12];
              int[] daysInYear = daysInYear(y);
              int firstDay = ((y - 1900) * 365 + (y - 1901) / 4) % 7;
              for (int i = 0; i < 12; i ++) {
                   if (i == 0) {
                        startDays[i] = firstDay;
                        firstDay = (firstDay + daysInYear) % 7;
                   else {
                        startDays[i] = firstDay;
                        firstDay = (firstDay + daysInYear[i]) % 7;
              return startDays;
         static int[] daysInYear(int y) {
              if (isLeap(y)) {
                   int DaysInMonth[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
                   return DaysInMonth;
              else {
                   int DaysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
                   return DaysInMonth;
         static boolean isSingle(int d) {
              if (d <= 9) {
                   return true;
              else {
                   return false;
         static boolean isLeap(int y) {
              // function to return true if y is a leap year, otherwise false.
              if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
                   return true;
              else {
                   return false;
         static void getMonth(int monthName, int startDay, int numDays) {
              String days[] = { "Mo.", "Tu.", "We.", "Th.",
                   "Fr.", "Sa.", "Su." };
              String months[] = { "JANUARY.", "FEBUARY.", "MARCH.", "APRIL.",
              "MAY.", "JUNE.", "JULY.", "AUGUST.", "SEPTEMBER.",
              "OCTOBER.", "NOVEMBER.", "DECEMBER." };
              String row[] = { "", "", "", "", "", "", "", "" };
              int startPos = 1 - startDay, count = 0, currentRow = 2;
              String buildRow = "";
              // Populate month grid with data
              // The only thing to change here is the month name
              row[0] = padMonth(months[monthName]);
              // This row will never change
              row[1] = "Mo.Tu.We.Th.Fr.Sa.Su";
              // 6 rows by 20 colums left
              for (int i = 2; i < 8; i ++) {
                   row[i] = " ";
              // loop to build a single row in grid
              for (int d = startPos; d != 42-startPos; d++) {
                   if (d >= 1 && d <= numDays) {
                        if (isSingle(d)) {
                             buildRow = buildRow + " ";
                        buildRow = buildRow + d;
                   else {
                        buildRow = buildRow + " ";
                   count ++;
                   if (count == 7) {
                        count = 0;
                        row[currentRow] = buildRow;
                        buildRow = "";
                        currentRow ++;
                        if (currentRow == 7) { currentRow = 2; }
                   else {
                        buildRow = buildRow + " ";
              //return row;
                   for (int i = 0; i < 7; i ++) {
              System.out.println(row[i]);
         public static void main(String[] args) {
         Scanner input = new Scanner(System.in);
         int year = 0;
         int i = 0;
         String[] monthGrid = new String[8];
         String[] concatGrid = new String[8];
         // Force year within range
         while (year < 1901 || year > 2099) {
              System.out.print("Please enter a year in range of 1901-2099: " );
              year = input.nextInt();
         // At this stage i know the year & can work out the start days for each month.
         int startDays[] = getStartDays(year);
         int daysInYear[] = daysInYear(year);
         while (i != 20) {
              i = input.nextInt();
              getMonth(i,startDays[i],daysInYear[i]);

  • As2 fullscreen gallery

    Hi!
    I want to create a simple but sweet flash portfolio like:http://www.jeanmalek.com/
    That one is a bit over the top for me though, with al the transitions and stuff.
    I want it to start with a menu with btns calling different xmls showing infullscreen my photographs.
    I want the gallery to be controlled with next and prev btns on top of the picture. It would be nice to have the cursor changing to arrows when hovering over each side.
    Layout jpgs:
    http://wimmerman.se/portfolio/layout1.jpg
    http://wimmerman.se/portfolio/layout2.jpg
    I guess the first step is to make the "menu btns" calling each xml gallery.
    Its based on Noponies tutorial:
    example: http://www.noponies.com/dev/fullscreen/
    files: http://www.noponies.com/dev/fullscreen/xmlFullCrossXML.zip
    What code do I import.
    Cheers!

    Furianaxus wrote:
    Hi There,
    http://gotoandlearn.com/play.php?id=22
    Watch that video tutorial. It should cover absolutely everything you need to get this done.
    oh sweet thanks!
    Ive been trying to implement the code but im not getting it to work right.
    For the moment its working as a slideshow and I think there is something with:
    bitmapFadeInterval = setInterval(_root, "loadRandomBitmap", imageTime);
    That launghes the loadRandomBitmap function.
    thanks for your help
    Here is my code:
    Terms and Conditions of use
    http://www.blog.noponies.com/terms-and-conditions
    //init
    import flash.display.BitmapData;
    Stage.scaleMode = "noscale";
    import gs.TweenLite;
    stop();
    //load in background images XML details
    var backImage:XML = new XML();
    backImage.ignoreWhite = true;
    var bgImages:Array = new Array();
    var p:Number = 0;//track pos in arrays
    //Variables pulled in from XML
    var minHeight:Number;
    var minWidth:Number;
    var crossFadeTime:Number;
    var imageTime:Number;
    var order:String;
    backImage.onLoad = function(success:Boolean) {
         if (success) {
              //get vars from XML file
              minHeight = this.firstChild.attributes.minHeight;
              minWidth = this.firstChild.attributes.minWidth;
              crossFadeTime = this.firstChild.attributes.crossFadeTime;
              imageTime = this.firstChild.attributes.imageTime;
              imageTime = (1000*60)*imageTime;
              order = String(this.firstChild.attributes.order);
              p = 0;
              bgImages = [];//reset the array var, should for some reason you want to load in a different set of images
              xmlNodes = this.firstChild;
              largeImages = xmlNodes.childNodes.length;
              for (i=0; i<largeImages; i++) {
                   bgImages[i] = xmlNodes.childNodes[i].childNodes[0].firstChild.nodeValue;
              //load random image when we successfully parse XML
              loadRandomBitmap();
         } else {
              trace("Fatal Error - Loading background image XML failed");
    //name of your xml file
    backImage.load("backimages.xml");
    /*create an empty mc to act as the background smoothed bitmap holder
    change the depth etc here should you need to..Note that this is created inside the
    small mc on the stage*/
    bgHolder_mc.createEmptyMovieClip("bg_mc",1);
    //var to track the fading, we use this to try to resize the temp bitmap with a resize, should the user be resizing the window when we fade in out
    var fadingComplete:Boolean = true;
    var firstRun:Boolean = true;
    //BITMAP BACKGROUND LOADING///
    function loadRandomBitmap():Void {
         if (order == "random") {
              //create the temp loader mc that we load our unsmoothed bitmap into
              //a limitation of this approach is that as this top image fades in/out it looks a little jagged for 2 seconds or so..
              bgHolder_mc.createEmptyMovieClip("bg_loader",2);
              //random function for loaded images
              randomImg = Math.floor(Math.random(bgImages.length)*bgImages.length);
              bitLoader.loadClip(bgImages[randomImg],bgHolder_mc.bg_loader);
         } else {
              //sequential loading of images
              bgHolder_mc.createEmptyMovieClip("bg_loader",2);
              bitLoader.loadClip(bgImages[p],bgHolder_mc.bg_loader);
              p++;
              if (p == bgImages.length) {
                   p = 0;
    //MovieClipLoader for bitmap image loading
    var bitLoader:MovieClipLoader = new MovieClipLoader();
    var bitlistener:Object = new Object();
    bitlistener.onLoadStart = function(target:MovieClip):Void  {
         //alpha out our image we load our bitmap into
         target._alpha = 0;
    bitlistener.onLoadProgress = function(target:MovieClip, bytesLoaded:Number, bytesTotal:Number):Void  {
         //amountLoaded = Math.floor((bytesLoaded/bytesTotal)*100);//calulate a loading percentage!
         //do something with this data if you want
    /*here we both draw our bitmap to our offscreen MC and handle the cross fading in and out -
    First we load our bitmap into our temp mc which is set to alpha 0, then we resize and fade our
    temp mc in so that we achieve the cross fading effect. When the temp MC is at 100% alpha we
    attach our bitmap object to our smoothed background MC and then quickly fade out and remove the temp MC.*/
    bitlistener.onLoadInit = function(target:MovieClip):Void  {
    /*clear the timer interval each time. We do this so that each new iteration of the timer
    starts from when the bitmap is loaded, this stops us from trying to fade images etc that have not loaded
    and ensures that each bitmap is displayed for the required amount of time on screen. Essentially it negates
    download time*/
         clearInterval(bitmapFadeInterval);
         //create the bitmap object, each time this is reset, keeping memory footprint fairly low..
         var bitmap:BitmapData = new BitmapData(target._width, target._height, true);
         //draw the bitmap
         bitmap.draw(target);
         //we are starting to fade, so set our var to false and let the temp resize functions run
         fadingComplete = false;
         //resize the temp bitmap to match the size of the bg bitmap
         this.resizeTemp = function() {
              if (Stage.height/Stage.width>target._height/target._width) {
                   img_propa = target._width/target._height;
                   target._height = Stage.height;
                   target._width = Stage.height*img_propa;
                   target._y = 0;
                   target._x = 0;
              } else {
                   img_propa = target._height/target._width;
                   target._width = Stage.width;
                   target._height = Stage.width*img_propa;
                   target._y = 0;
                   target._x = 0;
         this.resizeTemp();
         //fade in the temp bitmap
         TweenLite.to(target,crossFadeTime,{_alpha:100, onComplete:fadedIn, onCompleteParams:[this], onUpdate:this.resizeTemp});
         function fadedIn(ref):Void {
              ref.resizeTemp
              //attach our loaded bitmap to our background mc when the temp totally obscures it
              //this is the smoothed bitmap
              bgHolder_mc.bg_mc.attachBitmap(bitmap,0,"auto",true);
              //make the bg resize
              fullScreenBg();//This is  abit of a hack to catch user resizes
              TweenLite.to(target,.1,{_alpha:0, onComplete:cleanUpTemp});
              function cleanUpTemp():Void {
                   //remove the temp mc
                   removeMovieClip(bgHolder_mc.bg_loader);
                   //we are done fading..
                   fadingComplete = true;
              //reset the timer
              bgHolder_mc.bg_mc.attachBitmap(bitmap,0,"auto",true);
              bitmapFadeInterval = setInterval(_root, "loadRandomBitmap", imageTime);
              //resize the bg image
              fullScreenBg();
              //add the stage listener, which fixes an issue with the image being scaled out to
              //some crazy size if a user is resizing as the image loads in for the first time.
              if (firstRun) {
                   Stage.addListener(catchStage);//stage resize listener, added here after first image load.
                   firstRun = false;
    bitLoader.addListener(bitlistener);
    //stage listener to handle resizing images
    var catchStage:Object = new Object();
    catchStage.onResize = function() {    
         /*simple "OR" conditional to set a min size, if we are below that we don't do any more scaling
         note that we wrap this in a if/else so that the function that we actually use to to the bg
         resizing can be called independently of this check, for instance when we are below the resize
         min but we are fading in a new image, obviously we would want that new image to scale*/
         //**IF YOU WANT TO SCALE AT ALL STAGE SIZES, SET THE MIN HEIGHT ETC TO 0 IN THE XML
         if (Stage.width<minWidth || Stage.height<minHeight) {
              return;
         } else {
              //call the resize function
              fullScreenBg();
    //screen resize function
    function fullScreenBg() {
         if (Stage.height/Stage.width>bgHolder_mc.bg_mc._height/bgHolder_mc.bg_mc._width) {
              img_prop = bgHolder_mc.bg_mc._width/bgHolder_mc.bg_mc._height;
              bgHolder_mc.bg_mc._height = Stage.height;
              bgHolder_mc.bg_mc._width = Stage.height*img_prop;
              bgHolder_mc.bg_mc._y = 0;
              bgHolder_mc.bg_mc._x = 0;
         } else {
              img_prop = bgHolder_mc.bg_mc._height/bgHolder_mc.bg_mc._width;
              bgHolder_mc.bg_mc._width = Stage.width;
              bgHolder_mc.bg_mc._height = Stage.width*img_prop;
              bgHolder_mc.bg_mc._y = 0;
              bgHolder_mc.bg_mc._x = 0;

Maybe you are looking for

  • Animated GIF in interactive PDF

    Hi all, I was wondering if someone could help me with the following; I want to add some animated GIF images to my interactive PDF document in InDesign (also with hyperlinks and video's) How do I need to save the document, in order to see an animation

  • How to update my library and copy images to replace current linked ones?

    I've decided that I want to update my iPhoto library. Currently, most images that have been imported are just using links to images in their actual location. I want to change that so that all images are actually copied into the iPhoto library and no

  • Use of Case in Select statement

    Hi All, Can anyone tell me whats wrong im doing in the following select statement. I am selecting most this fields from Global Temperory Table and few from normal DB tables. select h.Taskid,h.Flowid,fd.DESCRIPTION Flowname,h.Stepid, sd.DESCRIPTION St

  • While copy into return sales order from sales invoice.

    I am creating one sales document assign one pricing procedure for that(eg. zpos) same way I am creating another return sales order which have I assign return sales order pricing procedure(zposr). Every time client want to create return sales order wi

  • Connecting laptop (XP) to Yoigo with 6310i (open)

    From a Bluetooth DUN icon I can get the phone to start to access the network. In 'Navegador' mode (wap browsing, I think, this is a Spanish service) it works fine, so I have money on the SIM card and can connect via my phone without Bluetooth. So Blu