Need Help with Random Events in Actionscript 2

I'm working on a game in flash right now, written in actionscript 2, where bottles fall from above at random speeds, and the object is to shoot the bottles as they fall, and every time you hit a bottle a different message appears on the screen for a brief period of time before disappearing.  So far I'm able to make the bottles fall and I'm able to shoot and break them, but I don't know how to work it so a different message appears each time you shoot a bottle. 
Can anyone help me with this problem?  I'm attaching the file of what I have so far.

My first question would be, when you say "different message appears" each time you hit a bottle.
What are the messages and do you want them to be random, and where will they appear.
After looking at your code, the best place I can see to place your message trigger is within the hit test. From there its a somple case of calling a function to display your message.

Similar Messages

  • Need help with custom event from Main class to an unrelated class.

    Hey guys,
    I'm new to Flash and not great with OOP.  I've made it pretty far with google and lurking, but I've been pulling my hair out on this problem for a day and everything I try throws an error or simply doesn't hit the listener.
    I'm trying to get my Main class to send a custom event to an unrelated class called BigIcon.  The rest of the code works fine, it's just the addEventListener and dispatchEvent that isn't working.
    I've put in the relevant code in below.  Let me know if anything else is needed to troubleshoot.  Thank you!
    Main.as
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        public class Main extends MovieClip
            var iconLayer_mc:MovieClip = new MovieClip();
            public function Main()
                Spin_btn.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler);
                addChildAt(iconLayer_mc,0);
                placeIcons();
            function placeIcons():void
                var i:int;
                var j:int;
                for (i = 0; i < 4; i++)
                    for (j = 0; j < 5; j++)
                        //iconString_array has the names of illustrator objects that have been converted to MovieClips and are in the library.
                        var placedIcon_mc:BigIcon = new BigIcon(iconString_array[i][j],i,j);
                        iconLayer_mc.addChild(placedIcon_mc);
            function fl_MouseClickHandler(event:MouseEvent):void
                dispatchEvent(new Event("twitchupEvent",true));
    BigIcon.as
    package
        import flash.display.MovieClip;
        import flash.events.Event;
        import flash.utils.getDefinitionByName;
        public class BigIcon extends MovieClip
            private var iconImage_str:String;
            private var iconRow_int:int;
            private var iconColumn_int:int;
            public function BigIcon(iconImage_arg:String, iconRow_arg:int, iconColumn_arg:int)
                iconImage_str = iconImage_arg;
                iconRow_int = iconRow_arg;
                iconColumn_int = iconColumn_arg;
                this.addEventListener(Event.ADDED_TO_STAGE, Setup);
            function Setup(e:Event)
                this.y = iconRow_int;
                this.x = iconColumn_int;
                var ClassReference:Class = getDefinitionByName(iconImage_str) as Class;
                var thisIcon_mc:MovieClip = new ClassReference;
                this.addChild(thisIcon_mc);
                addEventListener("twitchupEvent", twitchUp);
            function twitchUp(e:Event)
                this.y +=  10;

    Ned Murphy wrote:
    You should be getting an error for the Main.as class due to missing a line to import the Event class...
    import flash.events.Event;
    My apologies, I should attempt to compile my example code before I ask for help...
    Alright, this compiles, gives me no errors, shows my 'book' and 'flowers' icons perfectly when ran, and prints 'addEventListener' to the output window as expected.  I get no errors when I press the button, 'dispatchEvent' is output (good), but the 'twitchUp' function is never called and 'EventTriggered' is never output. 
    How do I get the 'twitchUp' event to trigger?
    Main.as
    package
        import flash.display.MovieClip;
        import flash.events.MouseEvent;
        import flash.events.*;
        public class Main extends MovieClip
            var iconLayer_mc:MovieClip = new MovieClip();
            var iconString_array:Array = new Array(2);
            public function Main()
                Spin_btn.addEventListener(MouseEvent.CLICK,fl_MouseClickHandler);
                addChildAt(iconLayer_mc,0);
                buildStringArray();
                placeIcons();
            function buildStringArray():void
                var i:int;
                var j:int;
                for (i = 0; i < 2; i++)
                    iconString_array[i] = new Array(3);
                    for (j = 0; j < 3; j++)
                        if (Math.random() > .5)
                            //'flowers' is the name of an illustrator object that has been converted to a MovieClip and is in the library
                            iconString_array[i][j] = "flowers";
                        else
                            //'book' is the name of an illustrator object that has been converted to a MovieClip and is in the library
                            iconString_array[i][j] = "book";
            function placeIcons():void
                var i:int;
                var j:int;
                for (i = 0; i < 2; i++)
                    for (j = 0; j < 3; j++)
                        //iconString_array has the names of illustrator objects that have been converted to MovieClips and are in the library.
                        var placedIcon_mc:BigIcon = new BigIcon(iconString_array[i][j],i*50,j*50);
                        iconLayer_mc.addChild(placedIcon_mc);
            function fl_MouseClickHandler(event:MouseEvent):void
                dispatchEvent(new Event("twitchupEvent",true));
                trace("dispatchEvent");
    BigIcon.as
    package
        import flash.display.MovieClip;
        import flash.events.*;
        import flash.utils.getDefinitionByName;
        public class BigIcon extends MovieClip
            private var iconImage_str:String;
            private var iconRow_int:int;
            private var iconColumn_int:int;
            public function BigIcon(iconImage_arg:String, iconRow_arg:int, iconColumn_arg:int)
                iconImage_str = iconImage_arg;
                iconRow_int = iconRow_arg;
                iconColumn_int = iconColumn_arg;
                this.addEventListener(Event.ADDED_TO_STAGE, Setup);
            function Setup(e:Event)
                this.y = iconRow_int;
                this.x = iconColumn_int;
                var ClassReference:Class = getDefinitionByName(iconImage_str) as Class;
                var thisIcon_mc:MovieClip = new ClassReference;
                this.addChild(thisIcon_mc);
                addEventListener("twitchupEvent", twitchUp);
                trace("addEventListener");
            function twitchUp(e:Event)
                this.y +=  10;
                trace("EventTriggered");
    Output:
    [SWF] Untitled-1.swf - 40457 bytes after decompression
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    addEventListener
    dispatchEvent
    [UnloadSWF] Untitled-1.swf
    Test Movie terminated.

  • First Mac-need help with an "event"

    Hi:
       After 3 days of busy activity with no freeze ups, I was feeling pretty confident.  However, late last night I ran into an "event" that eventually required me to reload Tiger.
       (1) I was working along and for some reason, clicking my mouse did not have any effect on any of the programs--either those running or attempting to start new ones.  
       (2) I was able to tab through those programs running and with a command-Q quit out of those running...still no effect on any mouse clicks....no problem moving the mouse and it would highlight top left corner buttons, but no effect if I attempted to minimize or exit.
       (3) I shut the computer off and restarted a number of times....came up to the same screen each time.    Held the off button both in shutting down and starting up and this time it would go to the log on screen where I was able to type in my password.  Would come up to the same screen as I left it.
       (4) Was able to use the remote control just fine to look at pictures, etc.
       (5) After some reading, did a PRAM reset....same story as above.
       (6) Finally reloaded a new copy of Tiger and was back in business.
    Questions:
      (1) Is this the typical freeze people are getting....with PCs, when it freezes, nothing moves and when you reboot, you have a fresh start?
      (2) Short of reloading Tiger, if this happens again, what remedy (other than sending my new iMac back!) would you suggest?
    Thanks for your help!

    Many thanks for the suggestion and the giving me some hope that this is not the dreaded freeze issue!
    I forgot to mention perhaps one important bit of information: There were two Finder "windows" that were present when my "event" occurred and each time I rebooted, these same two Finder windows reappeared and my mouse was unable to move them or close them or execute any command line operations.
    Not sure if this changes the story about it being a mouse software related error or not, but I found it strange that on hard reboots the machine came back with the same two windows of information.

  • I need help with my event-based cue points with audio

    Im having trouble with my video game project for my action script 3 class at school. Here is what i did, i made a game called Tailgate toss up. I filmed my character and rendered it in Adobe Premiere. I than brought my .mov file into After Effects and I put event-based cue points-
    my first cue point at 0:00:03:13 called "loop"
    my second cue point at 00:00:03:27 called "draw"
    my third cue point at 00:00:05:24 called "bang"
    my fourth cue point at 00:00:13:29 called "dead"
    my fifth cue point at 00:00:14:29 called "You Lose"
    my last cue point at 00:00:19:14 called "End"
    Here is my action script 3 code
    ///first frame:
    start_btn.addEventListener(MouseEvent.CLICK, startGame);
    function startGame(event:MouseEvent){
    gotoAndStop(2);
    SoundMixer.stopAll()
    stop();
    ///second frame:
    stop();
    var loopTime
    var hitHim:Boolean = false;
    var vConnection:NetConnection = new NetConnection();
    vConnection.connect(null);
    var vStream:NetStream = new NetStream(vConnection);
    var client:Object = new Object();
    client.onCuePoint = onCuePoint;
    vStream.client = client;
    var myVideo:Video = new Video(418, 480);
    myVideo.y = 0;  ///this adjusts where the video is, right now it is the size of the canvas which is 418,480
    addChild(myVideo);
    myVideo.attachNetStream(vStream);
    vStream.play("michelle.flv");
    var throw_bottle:Sound
    throw_bottle = new Sound(new URLRequest("audio/throw_bottle.mp3")); //change to button noise, will add sound into ae file
    target_mc.addEventListener(MouseEvent.CLICK, shoot);
    target_mc.buttonMode = true;
    target_mc.visible = false;
    draw_mc.visible = false;
    function onCuePoint(cuePoint:Object):void {
       if(cuePoint.name == "loop"){
    loopTime = cuePoint.time;
        if(cuePoint.name == "draw"){
    var randomLoop:Number = Math.random()*10;
    if(randomLoop > 2){
    vStream.seek(loopTime);
    }else{
    setChildIndex(target_mc, numChildren - 1);  
    setChildIndex(draw_mc, numChildren - 1);    
    target_mc.visible = true;
    draw_mc.visible = true;
    if(cuePoint.time == "5:24"){
    draw_mc.visible = false;
    target_mc.visible = false;
    if(!hitHim){
    vStream.seek(15);    
    if(cuePoint.name == "dead"){
    vStream.close();
    myVideo.clear();
    gotoAndStop(3);
    if(cuePoint.name == "end"){
    gotoAndStop(3);
    function shoot(event:MouseEvent){
    throw_bottle.play();
    hitHim = true;
    ///my third and last frame
    playAgain_btn.addEventListener(MouseEvent.CLICK, playAgain);
    function playAgain(event:MouseEvent){
    gotoAndStop(2);
    SoundMixer.stopAll()
    stop();
    When I have no audio it works perfectly, no problems. When I bring audio in i re-render it as a .mov file and bring it back into After Effects and add the cue points to it. Than i re-render it out again as a flv file. When i bring it into my flash project it will work when the looping variable does just one loop and my target will appear so you can click on it or not. But when the looping variable makes it loop 2 to 10 times it skips over the catching (the part of the clip if you clip the button) and goes directly to the dropping of the can, not giving you the option of clicking the button. So basically it skips the "draw" or second cue point of my game and goes to "You Lose" cue point.
    Any suggestions?

    Hi,
    The latest audio driver for your machine is on the following link.
    http://ftp.hp.com/pub/softpaq/sp59501-60000/sp59649.exe
    Regards,
    DP-K
    ****Click the White thumb to say thanks****
    ****Please mark Accept As Solution if it solves your problem****
    ****I don't work for HP****
    Microsoft MVP - Windows Experience

  • Need help with Buttons/Events

    HI
    Here is what I am doing. I am creating an "operations"
    calendar for my workplace. So far I have been successful with
    creating the page, inserting links, tags, images etc.....
    But now I want to add an Event button - where once the button
    is clicked - it will launch a script on my UNIX server.
    Cant quite figure this one out
    Any help would be greatly appreciated

    Hey man, I 've done some correction, and it seems work, why don't you try the code to see if it is what you want.
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    public class ComplexMenu11 extends Applet implements ActionListener {
    Button open, close;
    MenuFrame f;
    public void init() {
    open = new Button("Open");
    add(open);
    open.addActionListener(this);
    close = new Button("Close");
    add(close);
    close.addActionListener(this);
    f = new MenuFrame("A Complex menu");
    f.setSize(200, 200);
    f.show();
    public void actionPerformed(ActionEvent evt) {
    if(evt.getSource() == open) {
    if(f.isShowing())
    f.show();
    }else{
    if(!f.isShowing())
    f.hide();
    class MenuFrame extends Frame implements ActionListener{  //and implements here too
    Font font;
    Label l;
    int fontsize;
    //MessageDialog md;
    MenuBar mb = new MenuBar();
    Menu m1 = new Menu("Colours");
    MenuFrame(String name) {
    super(name);
    m1.add(new MenuItem("White"));
    m1.add(new MenuItem("Light grey"));
    m1.add(new MenuItem("Yellow"));
    Menu m2 = new Menu("Font");
    m2.add(new MenuItem("10"));
    m2.add(new MenuItem("12"));
    m2.add(new MenuItem("14"));
    m2.add(new MenuItem("16"));
    m2.add(new MenuItem("18"));
    m2.add(new MenuItem("Message"));
    mb.add(m1);
    mb.add(m2);
    setMenuBar(mb);
    m1.addActionListener(this); //Add listener here
    l = new Label("A frame demonstration", Label.CENTER);
    add("South", l);
    //md = new MessageDialog(this,"Name",true);
    public void actionPerformed(ActionEvent evt) {
    if(evt.getSource() instanceof MenuItem) {
    //fontsize = 18;
    String label = evt.getActionCommand();
    if(label.equals("White")) {
    //setBackground(Color.white);
    System.out.println("This is the white point");
    }

  • Need help with random numbers

    hi i need to generate 2 random numbers from array list . and then take out that two numbers from list.
         String[] plcard = { "AC", "KC", "QC", "JC",
              "10C", "9C", "8C", "7C","6C","5C","4C","3C","2C", "AD", "KD", "QD", "JD",
              "10D", "9D", "8D", "7D","6D","5D","4D","3D","2D", "AS", "KS", "QS", "JS",
              "10S", "9S", "8S", "7S","6S","5S","4S","3S","2S", "AH", "KH", "QH", "JH",
              "10H", "9H", "8H", "7H","6H","5H","4H","3H","2H",};
    this is the list if someone can help me i would appreciate
    thanks in advance

    haha, never noticed the .shuffle(List) method!
    maybe java is getting too convenient (just kidding)?
    i never wrote a card game.
    how would the more programmingly gifted of us do this?
    this is my shot at it for what its worth...
    public class Card{
    public Card(int rank, int suit){
    this.rank = rank;
    this.suit = suit;
    int rank (or String i suppose)
    int suit;
    static final club = 1;
    static final spade = 2;
    static final heart = 3;
    static final diamond = 4;
    public class Shuffler{
    public Shuffler(){
    int NumOfDecks = 1;
    Vector ShuffledDeck;
    // num of decks
    for(int i = 0; i < NumOfDecks){
    // 4 suits
    for(int j = 0; j < 4; j++){
    // 13 ranks
    for(int k = 0; k < 13; k++){
    ShuffledDeck.add(new Card(k, j));
    } // suits
    } // num of decks
    Collections.shuffle(ShuffledDeck);
    // Done?
    }

  • Need Help with random numbers, please help

    Hi guys;
    I need your help for a school project. I need to generate a random number from 1.0 to 2.0. How would I do that?
    Regards,

    http://java.sun.com/j2se/1.3/docs/api/java/util/Random.html#nextFloat()

  • I need help with random number in GUI

    hello
    i have home work about the random number with gui. and i hope that you can help me doin this application. and thank you very much
    Q1)
    Write an application that generates random numbers. The application consists of one JFrame,
    with two text fields (see the figures) and a button. When the user clicks on the button, the
    program should generate a random number between the minimum and the maximum numbers
    entered in the text fields. The font of the number should be in red, size 100, bold and italic.
    Moreover, if the user clicks on the generated number (or around it), the color of the background
    should be changed to another random color. The possible colors are red, green blue , black ,cyan
    and gray.
    Notes:
    �&#61472;The JFrame size is 40 by 200
    �&#61472;The text fields size is 10
    this is a sample how should the programe look like.
    http://img235.imageshack.us/img235/9680/outputgo3.jpg
    Message was edited by:
    jave_cool

    see java.util.Random

  • Need help with random string arrays

    Hi, I could really use some specific advice about how to randomize and display strings. I'm trying to create an applet that displays a list of 12 chores and a list of four people for whom the chores should be distributed to. So far I have set up the code to display the chores list in the first column and what I'm tring to do is then randomly assign each persons name 3 times in the second column. I'm not getting any error messages but the problem is that I can't seem to get the names to appear only 3 times.
    // Random generator = new Random();
    // JButton assignChores = new Button("Assign Chores")'
    // JTextArea outputArea = new JTextArea("");
    // ect....
    public void actionPerformed(ActionEvent e) {
    String[] chores = {"Living Room",
    "Dining Room",
    "Kitchen",
    "Boy's Room",
    "Garbage",
    "Backyard",
    "Pets",
    "Front Bathroom",
    "Back Bathroom",
    "Laundry",
    "Computer Room",
    "Parent's Room"};
    String[] person = {"Mom",
    "Dad",
    "Son",
    "Daughter"};
    int[] numIndex = new int[13];
    String output = "Chores" + "\t" + "Person";
    output += "\n________________________________\n";
    // I feel relatively certain that a while statement should go
    // here but I'm lost as to how I should go about this.
    for (int i = 1; i < numIndex.length; i++) {
    int arrayIndex = generator.nextInt(person.length); // generate a random number based on the number of people
    output += "\n" + chores[numIndex[0]++] // display the chores list in column 1
    + "\t" + person[arrayIndex]; // then randomly display the names in column 2
    output += "\n________________________________\n";
    outputArea.setText(output);
    JOptionPane.showMessageDialog (null, outputArea,
    "Chores List", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);

    Hi,
    Here's even a more elegant twist on the problem.
    import java.util.*;
    class FamilyMember
      private String name;
      private ArrayList chores;
      private final int MAX_CHORES = 3;
      public FamilyMember( String name )
        this( name, null );
      public FamilyMember( String name, Collection chores )
        this.name = name;
        setChores( chores );
      public String getName()
        return( name );
      public Collection getChores()
        return( chores );
      private void initArray()
        if( chores == null )
          chores = new ArrayList();
      public void setChores( Collection newChores )
        if( newChores != null )
          initArray();
          if( newChores.size() <= MAX_CHORES )
            Iterator it = newChores.iterator();
            while( it.hasNext() )
              chores.add( it.next() );
      public boolean addChore( String newChore )
        boolean outBool = false;
        initArray();
        if( chores.size() < MAX_CHORES )
          chores.add( newChore );
          outBool = true;
        return( outBool );
      public void setName( String newName )
        name = newName;
    class Chore
      private String name;
      private boolean assigned;
      public Chore( String name )
        this.name = name;
      public String getName()
        return( name );
      public void setName()
        this.name = name;
      public void setAssigned( boolean newAssigned )
        assigned = newAssigned;
      public boolean isAssigned()
        return( assigned );
    public class ChoreLister
      public static void main(String[] args)
        Chore[] chores = { new Chore( "Living Room" ),
                           new Chore( "Dining Room" ),
                           new Chore( "Kitchen" ),
                           new Chore( "Boy's Room" ),
                           new Chore( "Garbage" ),
                           new Chore( "Backyard" ),
                           new Chore( "Pets" ),
                           new Chore( "Front Bathroom" ),
                           new Chore( "Back Bathroom" ),
                           new Chore( "Laundry" ),
                           new Chore( "Computer Room" ),
                           new Chore( "Parent's Room" ) };
        FamilyMember[] fm = { new FamilyMember( "Mom" ),
                              new FamilyMember( "Dad" ),
                              new FamilyMember( "Son" ),
                              new FamilyMember( "Daughter" ) };
        Random generator = new Random();
        System.out.println( "Chores\tPerson" );
        System.out.println( "________________________________" );
        // Loop through all chores assigning them as we go.
        for( int j = 0; j < chores.length; ++j )
          int arrayIndex = generator.nextInt( fm.length );
          while( !chores[j].isAssigned() )
            while( !fm[arrayIndex].addChore( chores[j].getName() ) )
              arrayIndex = generator.nextInt( fm.length );
            chores[j].setAssigned( true );
          System.out.print( chores[j].getName() + "\t" );
          if( chores[j].getName().length() < 8 )
            System.out.print( "\t" );
          System.out.println( fm[arrayIndex].getName() );
        System.out.println( "________________________________" );
    }Enjoy,
    Manfred.

  • I need help with event structure. I am trying to feed the index of the array, the index can vary from 0 to 7. Based on the logic ouput of a comparison, the index buffer should increment ?

    I need help with event structure.
    I am trying to feed the index of the array, the index number can vary from 0 to 7.
    Based on the logic ouput of a comparison, the index buffer should increment
    or decrement every time the output of comparsion changes(event change). I guess I need to use event structure?
    (My event code doesn't execute when there is an  event at its input /comparator changes its boolean state.
    Anyone coded on similar lines? Any ideas appreciated.
    Thanks in advance!

    You don't need an Event Structure, a simple State Machine would be more appropriate.
    There are many examples of State Machines within this forum.
    RayR

  • Need help with codings on generating random words

    hi guys.. i need help with generating random words from a list of array. please help me with the codings.. let me know the other variables that are needed if required as well.. thanks a million..
    private String wordList[] = { "abstraction", "command", "arithmetic", "backslash" };

    Hi,
    You can use the Random class to generate Random number between 0 to the array length and use the generated random number as index in to the Strign array.
    To generate Random number use the following code
    Random r = new Random();
    num = ((r.nextInt() >>> 1) % wordList.length);
    num will have the randomly generated number.

  • I need help with shooting in my flash game for University

    Hi there
    Ive tried to make my tank in my game shoot, all the code that is there works but when i push space to shoot which is my shooting key it does not shoot I really need help with this and I would appriciate anyone that could help
    listed below should be the correct code
    //checking if the space bar is pressed and shooting is allowed
    if(evt.keyCode == 32 && shootAllow){
        //making it so the user can't shoot for a bit
        shootAllow = false;
        //declaring a variable to be a new Bullet
        var newBullet:Bullet = new Bullet();
        //changing the bullet's coordinates
        newBullet.y = tank_mc.y + tank_mc.width/2 - newBullet.width/2;
        newBullet.x = tank_mc.x;
        //then we add the bullet to stage
        addChild(newBullet);
    listed below is my entire code
    import flash.display.MovieClip;
        //declare varibles to create mines
    //how much time before allowed to shoot again
    var cTime:int = 0;
    //the time it has to reach in order to be allowed to shoot (in frames)
    var cLimit:int = 12;
    //whether or not the user is allowed to shoot
    var shootAllow:Boolean = true;
    var minesInGame:uint;
    var mineMaker:Timer;
    var cursor:MovieClip;
    var index:int=0;
    var tankMine_mc:MovieClip;
    var antiTankmine_mc:MovieClip;
    var maxHP:int = 100;
    var currentHP:int = maxHP;
    var percentHP:Number = currentHP / maxHP;
    function initialiseMine():void
        minesInGame = 15;
        //create a timer fires every second
        mineMaker = new Timer(6000, minesInGame);
        //tell timer to listen for Timer event
        mineMaker.addEventListener(TimerEvent.TIMER, createMine);
        //start the timer
        mineMaker.start();
    function createMine(event:TimerEvent):void
    //var tankMine_mc:MovieClip;
    //create a new instance of tankMine
    tankMine_mc = new Mine();
    //set the x and y axis
    tankMine_mc.y = 513;
    tankMine_mc.x = 1080;
    // adds mines to stage
    addChild(tankMine_mc);
    tankMine_mc.addEventListener(Event.ENTER_FRAME, moveHorizontal);
    function moveHorizontal(evt:Event):void{
        evt.target.x -= Math.random()*5;
        if (evt.target.x >= stage.stageWidth)
            evt.target.removeEventListener(Event.ENTER_FRAME, moveHorizontal);
            removeChild(DisplayObject(evt.target));
    initialiseMine();
        //declare varibles to create mines
    var atmInGame:uint;
    var atmMaker:Timer;
    function initialiseAtm():void
        atmInGame = 15;
        //create a timer fires every second
        atmMaker = new Timer(8000, minesInGame);
        //tell timer to listen for Timer event
        atmMaker.addEventListener(TimerEvent.TIMER, createAtm);
        //start the timer
        atmMaker.start();
    function createAtm(event:TimerEvent):void
    //var antiTankmine_mc
    //create a new instance of tankMine
    antiTankmine_mc = new Atm();
    //set the x and y axis
    antiTankmine_mc.y = 473;
    antiTankmine_mc.x = 1080;
    // adds mines to stage
    addChild(antiTankmine_mc);
    antiTankmine_mc.addEventListener(Event.ENTER_FRAME, moveHorizontal);
    function moveHorizontal_2(evt:Event):void{
        evt.target.x -= Math.random()*10;
        if (evt.target.x >= stage.stageWidth)
            evt.target.removeEventListener(Event.ENTER_FRAME, moveHorizontal);
            removeChild(DisplayObject(evt.target));
    initialiseAtm();
    function moveForward():void{
        bg_mc.x -=10;
    function moveBackward():void{
        bg_mc.x +=10;
    var tank_mc:Tank;
    // create a new Tank and put it into the variable
    // tank_mc
    tank_mc= new Tank;
    // set the location ( x and y) of tank_mc
    tank_mc.x=0;
    tank_mc.y=375;
    // show the tank_mc on the stage.
    addChild(tank_mc);
    stage.addEventListener(KeyboardEvent.KEY_DOWN, onMovementKeys);
    //creates the movement
    function onMovementKeys(evt:KeyboardEvent):void
        //makes the tank move by 10 pixels right
        if (evt.keyCode==Keyboard.D)
        tank_mc.x+=5;
    //makes the tank move by 10 pixels left
    if (evt.keyCode==Keyboard.A)
    tank_mc.x-=5
    //checking if the space bar is pressed and shooting is allowed
    if(evt.keyCode == 32 && shootAllow){
        //making it so the user can't shoot for a bit
        shootAllow = false;
        //declaring a variable to be a new Bullet
        var newBullet:Bullet = new Bullet();
        //changing the bullet's coordinates
        newBullet.y = tank_mc.y + tank_mc.width/2 - newBullet.width/2;
        newBullet.x = tank_mc.x;
        //then we add the bullet to stage
        addChild(newBullet);
    if (tank_mc.hitTestObject(antiTankmine_mc))
            //tank_mc.gotoAndPlay("hit");
            currentHP -= 10;
            // remove anti tank mine
            removeChild(antiTankmine_mc);
    if (tank_mc.hitTestObject(tankMine_mc))
            //tank_mc.gotoAndPlay("hit");
            currentHP -= 10;
            // remove anti tank mine
            removeChild(tankMine_mc);
        //var maxHP:int = 100;
    //var currentHP:int = maxHP;
    //var percentHP:Number = currentHP / maxHP;
        //Incrementing the cTime
    //checking if cTime has reached the limit yet
    if(cTime < cLimit){
        cTime ++;
    } else {
        //if it has, then allow the user to shoot
        shootAllow = true;
        //and reset cTime
        cTime = 0;
    function updateHealthBar():void
        percentHP = currentHP / maxHP;
        healthBar.barColor.scaleX = percentHP;
        if(currentHP <= 0)
            currentHP = 0;
            trace("Game Over");
        updateHealthBar();

    USe the trace function to analyze what happens and what fails to happen in the code you showed.  trace the conditional values to see if they are set up to allow a shot when you press the key

  • Need help with a small application

    Hi all, I please need help with a small application that I need to do for a homework assignment.
    Here is what I need to do:
    "Write an application that creates a frame with one button.
    Every time the button is clicked, the button must be changed
    to a random color."
    I already coded a part of the application, but I don't know what to do further.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ColourButton extends JFrame {
         JButton button = new JButton("Change Colour");
         public ColourButton() {
              super ("Colour Button");
              setSize(250, 150);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel panel = new JPanel();
              panel.add(button);
              add(panel);
              setVisible(true);
         public static void main(String[] args) {
              ColourButton cb = new ColourButton();
    }The thing is I'm not sure what Event Listener I have to implement and use as well as how to get the button to change to a random color everytime the button is clicked.
    Can anyone please help me with this.
    Thanks.

    The listener:
    Read this: [http://java.sun.com/docs/books/tutorial/uiswing/components/button.html]
    The random color:
    [Google this|http://www.google.com/search?q=color+random+java]

  • Urgently need help with this

    Hi!!
    I urgently need help with this:
    When I compile this in Flex Builder 3 it says: The element type 'mx:Application' must be terminated by the matching end-tag '</mx:Application>'.
    but I have this end tag in my file, but when I try to switch from source view to desgin view it says, that: >/mx:Script> expected to terminate element at line 71, this is right at the end of the .mxml file. I have actionscript(.as) file for scripting data.
    This is the mxml code to terminate apllication tag which I did as you can see:
    MXML code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundGradientAlphas="[1.0, 1.0]" backgroundGradientColors="[#007200, #000200]" width="1024" height="768" applicationComplete="popolni_vse()">
    <mx:HTTPService id="bazaMME" url="lokalnabaza/baza_MME_svn.xml" showBusyCursor="true" resultFormat="e4x"/>
    <mx:Script source="dajzaj.as"/>
    <mx:states>
    <mx:State name="Galerije">
        <mx:SetProperty target="{panel1}" name="title" value="Galerije MME"/>
        <mx:SetProperty target="{panel2}" name="title" value="opis slik"/>
        <mx:SetProperty target="{panel3}" name="title" value="Opis Galerije"/>   
        <mx:AddChild relativeTo="{panel1}" position="lastChild">
        <mx:HorizontalList x="0" y="22" width="713.09863" height="157.39436" id="ListaslikGalerije"></mx:HorizontalList>
                </mx:AddChild>
                <mx:SetProperty target="{text1}" name="text" value="MME opisi galerij "/>
                <mx:AddChild relativeTo="{panel1}" position="lastChild">
                    <mx:Label x="217" y="346" text="labela za test" id="izbr"/>
                </mx:AddChild>
                <mx:SetProperty target="{label1}" name="text" value="26. November 2009@08:06"/>
                <mx:SetProperty target="{label1}" name="x" value="845"/>
                <mx:SetProperty target="{label1}" name="width" value="169"/>
                <mx:SetProperty target="{Gale}" name="text" value="plac za Galerije"/>
            </mx:State>
            <mx:State name="Projekti"/>
        </mx:states>
    <mx:MenuBar id="MMEMenu" labelField="@label" showRoot="true" fillAlphas="[1.0, 1.0]" fillColors="[#043D01, #000000]" color="#9EE499" x="8" y="24"
             itemClick="dajVsebino(event)" width="1006.1268" height="21.90141">
           <mx:XMLList id="MMEmenuModel">
                 <menuitem label="O nas">
                     <menuitem label="reference podjetja" name="refMME" type="check" groupName="one"/>
                     <menuitem label="reference direktor" name="refdir" type="check" groupName="one"/>
                  <menuitem label="Kontakt" name="podatMME" groupName="one" />
                  <menuitem label="Kje smo" name="lokaMME" type="check" groupName="one" />
                 </menuitem>           
                 <menuitem type="separator"/>
                 <menuitem label="Galerija">
                     <menuitem label="Slovenija" name="galSvn" type="check" groupName="one"/>
                     <menuitem label="Nemčija" name="galDeu" type="check" groupName="one" />
                 </menuitem>
                 <menuitem type="separator"/>
                 <menuitem label="projekti">
                     <menuitem label="Slovenija" name="projSvn" type="check" groupName="one"/>
                     <menuitem label="Nemčija" name="projDeu" type="check" groupName="one" />
                     <menuitem label="Madžarska" name="projHun" type="check" groupName="one"/>
                 </menuitem>
             </mx:XMLList>                       
             </mx:MenuBar>
        <mx:Label x="845" y="10" text="25. November 2009@08:21" color="#FFFFFF" width="169" height="18.02817" id="label1"/>
        <mx:Label x="746" y="10" text="zadnja posodobitev:" color="#FFFFFF"/>
        <mx:Panel x="9" y="57" width="743.02814" height="688.4507" layout="absolute" title="Plac za Vsebino" id="panel1">
            <mx:Text x="0" y="-0.1" text="MME vsebina" width="722.95776" height="648.4507" id="Gale"/>
        </mx:Panel>
        <mx:Label x="197.25" y="748.45" color="#FFFFFF" text="Copyright © 2009 MME d.o.o." fontSize="12" width="228.73239" height="20"/>
        <mx:Label x="463.35" y="748.45" text="izdelava spletnih strani: FACTUM d.o.o." color="#FBFDFD" fontSize="12" width="287.60565" height="20"/>
        <mx:Panel x="759" y="53" width="250" height="705.07043" layout="absolute" title="Plac za hitre novice" id="panel3">
            <mx:Text x="0" y="0" text="MME novice" width="230" height="665.07043" id="text1"/>
            <mx:Panel x="-10" y="325.35" width="250" height="336.61972" layout="absolute" title="začasna panela" color="#000203" themeColor="#4BA247" cornerRadius="10" backgroundColor="#4B9539" id="panel2">
                <mx:Label x="145" y="53" text="vrednost" id="spremmen"/>
                <mx:Label x="125" y="78" text="Label"/>
                <mx:Label x="125" y="103" text="Label"/>
                <mx:Label x="0" y="53" text="spremenljivka iz Menuja:"/>
                <mx:Label x="45" y="78" text="Label"/>
                <mx:Label x="45" y="103" text="Label"/>
            </mx:Panel>
        </mx:Panel>
        <mx:Label x="9.9" y="10" text="plac za naslov MME vsebine" id="MMEnaslov" color="#040000"/>
         </mx:states></mx:Application>

    I know it's been a while but… did you fix this?
    It looks to me like you are terminating the <mx:Application> tag at the top. The opening tag should end like this: resultFormat="e4x">, not resultFormat="e4x"/> (Remove the /).
    Carlos

  • Please I really need help with this video problem.

    Hi!
    Please I need help with this app I am trying to make for an Android cellphone and I've been struggling with this for a couple of months.
    I have a main flash file (video player.fla) that will load external swf files. This is the main screen.When I click the Sets Anteriores button I want to open another swf file called sets.swf.The app is freezing when I click Sets Anteriores button
    Here is the code for this fla file.
    import flash.events.MouseEvent;
    preloaderBar.visible = false;
    var loader:Loader = new Loader();
    btHome.enabled = false;
    var filme : String = "";
    carregaFilme("home.swf");
    function carregaFilme(filme : String ) :void
      var reqMovie:URLRequest = new URLRequest(filme);
      loader.load(reqMovie);
      loader.contentLoaderInfo.addEventListener(Event.OPEN,comeco);
      loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,progresso);
      loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completo);
      palco.addChild(loader); 
    function comeco(event:Event):void
              preloaderBar.visible = true;
              preloaderBar.barra.scaleX = 0;
    function progresso(e:ProgressEvent):void
              var perc:Number = e.bytesLoaded / e.bytesTotal;
              preloaderBar.percent.text = Math.ceil(perc*100).toString();
              preloaderBar.barra.scaleX =  perc;
    function completo(e:Event):void
              preloaderBar.percent.text = '';
              preloaderBar.visible = false;
    btHome.addEventListener(MouseEvent.MOUSE_DOWN,onHomeDown);
    btHome.addEventListener(MouseEvent.MOUSE_UP,onHomeUp);
    btSets.addEventListener(MouseEvent.MOUSE_DOWN,onSetsDown);
    btSets.addEventListener(MouseEvent.MOUSE_UP,onSetsUp);
    btVivo.addEventListener(MouseEvent.MOUSE_DOWN,onVivoDown);
    btVivo.addEventListener(MouseEvent.MOUSE_UP,onVivoUp);
    btHome.addEventListener(MouseEvent.CLICK,onHomeClick);
    btSets.addEventListener(MouseEvent.CLICK,onSetsClick);
    function onSetsClick(Event : MouseEvent) : void
              if (filme != "sets.swf")
                          filme = "sets.swf";
                          carregaFilme("sets.swf");
    function onHomeClick(Event : MouseEvent) : void
              if (filme != "home.swf")
                          filme = "home.swf";
                          carregaFilme("home.swf");
    function onHomeDown(Event : MouseEvent) : void
              btHome.y += 1;
    function onHomeUp(Event : MouseEvent) : void
              btHome.y -= 1;
    function onSetsDown(Event : MouseEvent) : void
              btSets.y += 1;
    function onSetsUp(Event : MouseEvent) : void
              btSets.y -= 1;
    function onVivoDown(Event : MouseEvent) : void
              btVivo.y += 1;
    function onVivoUp(Event : MouseEvent) : void
              btVivo.y -= 1;
    Now this is the sets.fla file:
    Here is the code for sets.fla
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    var video:Video;
    var nc:NetConnection;
    var ns:NetStream;
    var t : Timer = new Timer(1000,0);
    var meta:Object = new Object();
    this.addEventListener(Event.ADDED_TO_STAGE,init);
    function init(e:Event):void{
    video= new Video(320, 240);
    addChild(video);
    video.x = 80;
    video.y = 100;
    nc= new NetConnection();
    nc.connect(null);
    ns = new NetStream(nc);
    ns.addEventListener(NetStatusEvent.NET_STATUS, onStatusEvent);
    ns.bufferTime = 1;
    ns.client = meta;
    video.attachNetStream(ns);
    ns.play("http://www.djchambinho.com/videos/segundaquinta.flv");
    ns.pause();
    t.addEventListener(TimerEvent.TIMER,timeHandler);
    t.start();
    function onStatusEvent(stat:Object):void
              trace(stat.info.code);
    meta.onMetaData = function(meta:Object)
              trace(meta.duration);
    function timeHandler(event : TimerEvent) : void
      if (ns.bytesLoaded>0&&ns.bytesLoaded == ns.bytesTotal )
                ns.resume();
                t.removeEventListener(TimerEvent.TIMER,timeHandler);
                t.stop();
    The problem is when I test it on my computer it works but when I upload it to my phone it freezes when I click Sets Anteriores button.
    Please help me with this problem I dont know what else to do.
    thank you

    My first guess is you're simply generating an error. You'll always want to load this on your device in quick debugging over USB so you can see any errors you're generating.
    Outside that, if you plan on accessing anything inside the SWF you should be loading the SWF into the correct context. Relevant sample code:
    var context:LoaderContext = new LoaderContext();
    context.securityDomain = SecurityDomain.currentDomain;
    context.applicationDomain = ApplicationDomain.currentDomain;
    var urlReq:URLRequest = new URLRequest("http://www.[your_domain_here].com/library.swf");
    var ldr:Loader = new Loader();
    ldr.load(urlReq, context);
    More information:
    http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9 b90204-7de0.html
    If you're doing this on iOS you'll need to stripped SWFs if you plan on using any coding (ABC) inside the files. You mentioned iOS so I won't get into that here, but just incase, here's info on stripping external SWFs:
    http://blogs.adobe.com/airodynamics/2013/03/08/external-hosting-of-secondary-swfs-for-air- apps-on-ios/

Maybe you are looking for