actionscript Storing a value after a button is clicked - actionscript-3

I don't program a lot. Sometimes I program a bit of Actionscript 3. Now I wanted to create an flash enviroment where people can click on buttons and play a video. I think I almost figured it out with the following script:
public class main extends MovieClip
{
private var drukknop1:knopje;
private var drukknop2:knopje;
private var drukknop3:knopje;
private var drukknop4:knopje;
private var drukknop5:knopje;
private var drukknop6:knopje;
private var drukknop7:knopje;
private var drukknop8:knopje;
private var drukknop9:knopje;
private var drukknop10:knopje;
private var videoclip:FLVPlayback = new FLVPlayback();
private var buttonClicked:Number = 0;
public function main()
{
// plaatsen van buttons on stage
drukknop1 = new knopje();
drukknop1.name = "inst_knop1";
drukknop1.x = 50;
drukknop1.y = 70;
addChild(drukknop1);
drukknop1.buttonMode = true;
drukknop1.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop1.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
drukknop2 = new knopje();
drukknop2.name = "inst_knop2";
drukknop2.x = 150;
drukknop2.y = 70;
addChild(drukknop2);
drukknop2.buttonMode = true;
drukknop2.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop2.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
drukknop3 = new knopje();
drukknop3.name = "inst_knop3";
drukknop3.x = 250;
drukknop3.y = 70;
addChild(drukknop3);
drukknop3.buttonMode = true;
drukknop3.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop3.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
drukknop4 = new knopje();
drukknop4.name = "inst_knop4";
drukknop4.x = 350;
drukknop4.y = 70;
addChild(drukknop4);
drukknop4.buttonMode = true;
drukknop4.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop4.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
drukknop5 = new knopje();
drukknop5.name = "inst_knop5";
drukknop5.x = 450;
drukknop5.y = 70;
addChild(drukknop5);
drukknop5.buttonMode = true;
drukknop5.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop5.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
drukknop6 = new knopje();
drukknop6.name = "inst_knop6";
drukknop6.x = 550;
drukknop6.y = 70;
addChild(drukknop6);
drukknop6.buttonMode = true;
drukknop6.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop6.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
drukknop7 = new knopje();
drukknop7.name = "inst_knop7";
drukknop7.x = 650;
drukknop7.y = 70;
addChild(drukknop7);
drukknop7.buttonMode = true;
drukknop7.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop7.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
drukknop8 = new knopje();
drukknop8.name = "inst_knop8";
drukknop8.x = 750;
drukknop8.y = 70;
addChild(drukknop8);
drukknop8.buttonMode = true;
drukknop8.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop8.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
drukknop9 = new knopje();
drukknop9.name = "inst_knop9";
drukknop9.x = 850;
drukknop9.y = 70;
addChild(drukknop9);
drukknop9.buttonMode = true;
drukknop9.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop9.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
drukknop10 = new knopje();
drukknop10.name = "inst_knop10";
drukknop10.x = 950;
drukknop10.y = 70;
addChild(drukknop10);
drukknop10.buttonMode = true;
drukknop10.addEventListener(MouseEvent.MOUSE_UP, _flv_component);
drukknop10.addEventListener(MouseEvent.MOUSE_DOWN, ButtonClicked);
}
private function _flv_component(event:MouseEvent):void
{
//plaatsen van de video player door drukken op de knop
drukknop1.buttonMode = false;
drukknop1.removeEventListener(MouseEvent.MOUSE_UP, _flv_component);
videoclip.x = (stage.stageWidth/2)-(videoclip.width/2);
videoclip.y = (stage.stageHeight/2)-(videoclip.height/2);
videoclip.width = 640;
videoclip.height = 400;
videoclip.autoPlay = true;
videoclip.skin = "MinimaSilverPlayBackSeekMute.swf";
if(buttonClicked ==1)
{videoclip.load("Functieomschrijvingscene.flv");}
else if(buttonClicked ==2)
{videoclip.load("2.flv");}
else if(buttonClicked ==3)
{videoclip.load("3.flv");}
else if(buttonClicked ==4)
{videoclip.load("4.flv");}
else if(buttonClicked ==5)
{videoclip.load("5.flv");}
else if(buttonClicked ==6)
{videoclip.load("6.flv");}
else if(buttonClicked ==7)
{videoclip.load("7.flv");}
else if(buttonClicked ==8)
{videoclip.load("8.flv");}
else if(buttonClicked ==9)
{videoclip.load("9.flv");}
else if(buttonClicked ==10)
{videoclip.load("10.flv");}
videoclip.play();
addChild(videoclip);
videoclip.addEventListener(Event.COMPLETE,videoComplete);
}
function videoComplete(event:Event):void
{
//Verwijderen van FLVPlayback component
trace ("video is klaar");
removeChild(videoclip);
buttonClicked = 0;
trace (buttonClicked);
}
function ButtonClicked(Event:MouseEvent):void
{
trace ("ButtonClicked functie werkt.");
trace (buttonClicked);
// het opslaan van een nummer van een button
if(event.target.name == drukknop1)
{buttonClicked = 1;}
else if(event.target.name == drukknop2)
{buttonClicked = 2;}
else if(event.target.name == drukknop3)
{buttonClicked = 3;}
else if(event.target.name == drukknop4)
{buttonClicked = 4;}
else if(event.target.name == drukknop5)
{buttonClicked = 5;}
else if(event.target.name == drukknop6)
{buttonClicked = 6;}
else if(event.target.name == drukknop7)
{buttonClicked = 7;}
else if(event.target.name == drukknop8)
{buttonClicked = 8;}
else if(event.target.name == drukknop9)
{buttonClicked = 9;}
else if(event.target.name == "inst_knop10")
{buttonClicked = 10;}
}
}
}
In the function "ButtonClicked, I want to check which button is clicked. After that I want to store a value in the private var "Buttonclicked" So that based on this number I know which FLV needs to be loaded. But when I export I get an error "Access of Undefined property event". This probably has got to do with my "If" statement in the functions but I have no clue on how to solve this.
Could someone please help me out? I know programming with classes would be much neater, but I have to little experience in this.
Thanks in advance,
Harold

You got that error because for your ButtonClicked() function you've declared an MouseEvent object called Event and inside the function you've used event, I think it's just a typing mistake.
So your function can be like this :
function ButtonClicked(event:MouseEvent):void
{
// ...
}
Also, I remarked in your code that you've written a lot of code to do something really easy and don't need all that code. Don't forget that when you are repeating the same thing n times (10 times for your case), that you are doing something wrong and that you should (can) optimize that. You can use a function, for example, to do that repeated task ...
For that, take this example :
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
public class Main extends MovieClip {
private const BUTTONS_NUM:int = 10;
private const BOTTONS_Y:int = 70;
private const BUTTONS_SUFFIX:String = 'inst_knop';
private const VIDEOS:Array = ['1.flv', '2.flv', '3.flv', '4.flv', '5.flv', '6.flv', '7.flv', '8.flv', '9.flv', '10.flv'];
public function Main()
{
// initialize the FLVPlayback component inserted in the stage
videoclip.width = 640;
videoclip.height = 400;
videoclip.autoPlay = true;
videoclip.addEventListener(Event.COMPLETE,videoComplete);
createButtons();
}
private function createButtons(): void
{
for(var i:int = 0; i < BUTTONS_NUM; i++){
var button:knopje = new knopje();
button.name = BUTTONS_SUFFIX + (i+1);
button.x = i*100 + 50;
button.y = BOTTONS_Y;
button.buttonMode = true;
button.addEventListener(MouseEvent.CLICK, playVideo);
addChild(button);
}
}
private function playVideo(event:MouseEvent):void
{
// get button's index, for example : 7 for the button called "inst_knop7"
var button_index:int = int((event.currentTarget.name).substr(BUTTONS_SUFFIX.length)) - 1;
// play the video
videoclip.play('video/' + VIDEOS[button_index]);
}
private function videoComplete(event:Event):void
{
trace('end of the video.');
}
}
}
Hope that can help.

Related

Is anyone interested in looking at my code for a game? I'm getting strange errors

I'm trying to make my first real, simple shooter game. I've read through tutorials online and instead of directly copying code, I tried to take things the next level to actually understand the code and add my own twists. With this in mind, I've recently been learning arrays and not sure if I am using them correctly.
I'm getting strange, intermittent
Error #2025 DisplayObject must be a child of the caller
messages in the output window, not the compiler window.
So, I don't know what line of code is generating this problem. By commenting out blocks of code I have narrowed it down to the modules labeled "CLEANUP MISSED ENEMIES" and "BULLET RATE OF SHOOTING", but the 'why' is beyond my understanding.
I am sure there will be many great comments pointing out conventions I get wrong and errors I am making. I value every chance to learn so please give your input as you see fit! I bet there are way better methods to do the things I am doing!
package{
import flash.events.Event;
import flash.display.MovieClip;
import flash.media.Sound;
import flash.media.SoundChannel;
import com.greensock.*;
import com.greensock.easing.*;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.ColorTransform;
import fl.motion.Color;
import flash.display.DisplayObject;
public class chopper extends MovieClip{
public function chopper(){
boot();
}
public function boot():void{
/////////VARS
var coptr:MovieClip = new copter();
var bulit:MovieClip = new bullit();
var mouseIsDn = false;
var speed = 0;
var PEW = false
var meter:MovieClip = new meters();
var bltArray:Array = new Array();
var airArray:Array = new Array();
var gndArray:Array = new Array();
var gameTIMERa:Timer = new Timer(5000);
var gameTIMERb:Timer = new Timer(10000);
stage.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
stage.addEventListener(MouseEvent.MOUSE_UP, unclicked);
function clicked(e:Event):void{
mouseIsDn = true;
}
function unclicked(e:Event):void{
mouseIsDn = false;
}
/////////INTRO SCREEN
var titl:MovieClip = new title();
addChild(titl);
var strt:MovieClip = new start();
addChild(strt);
var govr:MovieClip = new gOVER();
var ctINTRO:Color = new Color();
ctINTRO.setTint(Math.random()*0xFFFFFF, 0.5);
BG.transform.colorTransform = ctINTRO;
/////////MUSIC
var ChanAB:SoundChannel = new SoundChannel();
var Amusic:Sound = new musicA();
var Bmusic:Sound = new musicB();
ChanAB = Amusic.play(0, 9999);
/////////SFx
var ChanSFx:SoundChannel = new SoundChannel();
var Ashoot:Sound = new shootA();
var SFx:Array = new Array();
var Asuck:Sound = new suckA();
SFx.push(Asuck);
var Bsuck:Sound = new suckB();
SFx.push(Bsuck);
var Csuck:Sound = new suckC();
SFx.push(Csuck);
var gOver:Sound = new over();
/////////START
strt.startBTN.addEventListener(MouseEvent.CLICK, str);
function str(e:Event):void{
removeChild(titl);
removeChild(strt);
ChanAB.stop();
BG.transform.colorTransform = new ColorTransform;
////////////
ChanAB = Bmusic.play(0, 9999);
addChild(coptr);
TweenLite.to(coptr, 3, {x:157, y:316});
addChild(meter);
meter.x = 861;
meter.y = 9;
TweenLite.to(meter, 1, {x:735});
meter.life.gotoAndPlay(2);
gameTIMERa.addEventListener(TimerEvent.TIMER, addAIR);
gameTIMERa.start();
gameTIMERb.addEventListener(TimerEvent.TIMER, addGND);
gameTIMERb.start();
}
/////////ADDING ENEMIES
function addAIR(e:TimerEvent):void{
var Aair:MovieClip = new airA();
Aair.x = 805;
Aair.scaleX = .25
Aair.y = Math.random() * stage.stageHeight - Aair.height;
Aair.scaleY = .25
airArray.push(Aair);
addChild(Aair);
}
function addGND(e:TimerEvent):void{
var Agnd:MovieClip = new gndA();
Agnd.x = 805;
Agnd.scaleX = .25
Agnd.y = 430 + Math.floor(Math.random() * 36);
Agnd.scaleY = .25
gndArray.push(Agnd);
addChild(Agnd);
}
addEventListener(Event.ENTER_FRAME, startLoop);
function startLoop(e:Event):void{
if(coptr.x == 157 && coptr.y == 316){
speed = 10;
meter.life.gotoAndStop(10);
removeEventListener(Event.ENTER_FRAME, startLoop);
addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN, shoot);
}
}
/////////COPTER SHOOTING
function shoot(e:Event):void{
if(PEW == false){
ChanSFx = Ashoot.play();
bulit.x = coptr.x + 5;
bulit.y = coptr.y;
bltArray.push(bulit);
addChild(bulit);
PEW = true;
}
}
/////////LIFE METER
function lifeMeterA(e:Event = null):void{
if(meter.life.width > 59){
meter.life.scaleX -= .04;
}
else if(meter.life.width < 59 && meter.life.width > 29){
meter.life.gotoAndStop(11);
meter.life.scaleX -= .04;
}
else if(meter.life.width < 29 && meter.life.width > 15){
meter.life.gotoAndStop(12)
meter.life.scaleX -= .04;
}
else if(meter.life.width < 15 && meter.life.width > 1.5){
meter.life.gotoAndPlay(2);
meter.life.scaleX -= .04;
}
}
function lifeMeterB(e:Event = null):void{
if(meter.life.width > 59){
meter.life.scaleX -= .01;
}
else if(meter.life.width < 59 && meter.life.width > 29){
meter.life.gotoAndStop(11);
meter.life.scaleX -= .01;
}
else if(meter.life.width < 29 && meter.life.width > 15){
meter.life.gotoAndStop(12)
meter.life.scaleX -= .01;
}
else if(meter.life.width < 15 && meter.life.width > 1.5){
meter.life.gotoAndPlay(2);
meter.life.scaleX -= .01;
}
}
////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////MAIN LOOP
function gameLoop(e:Event) {
////////////////////////COPTER MOVEMENT
trace(bltArray);
trace(airArray);
trace(gndArray);
coptr.y += speed;
if(mouseIsDn){
if(speed > -5){
speed -= 1;
}
}else{
if(speed < 10){
speed += .25;
}
}
////////////////////////BULLET MOVEMENT
if(bulit){
bulit.x += 10;
}
if(coptr.y > stage.stageHeight - coptr.height*.5){
coptr.y = stage.stageHeight - coptr.height*.5;
}
else if(coptr.y < 0 + coptr.height*.5){
coptr.y = 0 + coptr.height*.5;
}
////////////////////////COLLISIONS
for(var i = 0; i<numChildren; i++){
if(getChildAt(i) is airA){
var b = getChildAt(i) as airA;
if(b.hitTestObject(coptr)){
lifeMeterA();
}
if(b.hitTestObject(bulit)){
airArray.shift();
removeChild(b);
removeChild(bltArray[0]);
PEW = false;
var m:uint = uint(Math.random() * 3);
ChanSFx = SFx[m].play();
}
}
else if(getChildAt(i) is gndA){
var c = getChildAt(i) as gndA;
if(c.hitTestObject(coptr)){
lifeMeterB();
}
if(c.hitTestObject(bulit)){
gndArray.shift();
removeChild(c);
removeChild(bltArray[0]);
PEW = false;
var n:uint = uint(Math.random() * 3);
ChanSFx = SFx[n].play();
}
}
}
if(coptr.y > stage.stageHeight - coptr.height){
lifeMeterA();
}
////////////////////////CLEANUP MISSED ENEMIES
if(airArray[0] && airArray[0].x < 0){
airArray.shift();
}
if(gndArray[0] && gndArray[0].x < 0){
gndArray.shift();
}
////////////////////////BULLET RATE OF SHOOTING
if(bltArray[0] && bltArray[0].x > stage.stageWidth){
PEW = false;
bltArray.shift();
}
////////////////////////END GAME
if(meter.life.width < 1.5){
removeEventListener(Event.ENTER_FRAME, gameLoop);
gameTIMERa.stop();
gameTIMERb.stop();
meter.life.gotoAndStop(13);
TweenLite.to(meter, .5, {x:861});
gameO();
}
}
function gameO(e:Event = null):void{
addChild(govr);
govr.x = 0;
govr.y = 0;
ChanAB.stop();
ChanSFx = gOver.play();
ChanSFx.addEventListener(Event.SOUND_COMPLETE, restart);
}
function restart(e:Event):void{
removeChild(govr);
removeChild(coptr);
boot();
}
}
}
}
Thanks in advance!
It means you're using removeChild() somewhere on an object whose parent is not the container you are trying to remove it from.
For example, this code would cause that error:
var shape:Shape = new Shape();
stage.removeChild(shape);
It's likely that you are calling removeChild() more than once somewhere in your code.

ActionScript 3.0 AddChild Function Not Working

I have tested out my code and the addchild won't work. No errors are outputted.
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.text.*;
public class Game extends flash.display.MovieClip{
public static const STATE_INIT:int = 10;
public static const STATE_PLAY:int = 20;
public static const STATE_END_GAME:int = 30;
public var gameState:int = 0;
public var score:int = 0;
public var chances:int = 5;
public var bg:MovieClip;
public var enemies:Array;
public var player:MovieClip;
public var level:Number = 0;
public var scoreLabel:TextField = new TextField
public var levelLabel:TextField = new TextField
public var chancesLabel:TextField = new TextField
public var scoreText:TextField = new TextField
public var levelText:TextField = new TextField
public var chancesText:TextField = new TextField
public const SCOREBOARD_Y:Number = 380
public function Game(){
addEventListener(Event.ENTER_FRAME, gameLoop);
bg = new BackImage();
addChild(bg);
scoreLabel.text = "Score:";
levelLabel.text = "level:";
chancesLabel.text = "Misses:";
scoreText.text = "0";
levelText.text = "1";
chancesText.text = "5";
scoreLabel.y = SCOREBOARD_Y;
levelLabel.y = SCOREBOARD_Y;
chancesLabel.y = SCOREBOARD_Y;
scoreText.y = SCOREBOARD_Y;
levelText.y = SCOREBOARD_Y;
chancesText.y = SCOREBOARD_Y;
scoreLabel.x = 5;
scoreText.x = 50;
chancesLabel.x = 105;
chancesText.x = 155;
levelLabel.x = 205;
levelText.x = 260
addChild(scoreLabel);
addChild(levelLabel);
addChild(chancesLabel);
addChild(scoreText);
addChild(levelText);
addChild(chancesText);
gameState = STATE_INIT;
}
public function gameLoop(e:Event):void{
switch(gameState){
case STATE_INIT:
initGame();
break;
case STATE_PLAY:
playGame();
break;
case STATE_END_GAME:
endGame();
break;
}
}
public function initGame():void{
score = 0;
chances = 5;
player = new playerImage();
enemies = new Array();
level = 1;
levelText.text = level.toString();
addChild(player);
player.startDrag(true,new Rectangle(0,0,550,400))
gameState = STATE_PLAY
}
public function playGame():void{
player.rotation += 15;
makeEnemies();
moveEnemies();
testCollisions();
testForEnd();
}
public function makeEnemies():void{
var chance:Number = Math.floor(Math.random()*100);
var tempEnemy:MovieClip;
if (chance < 2 + level) {
tempEnemy = new EnemyImage()
tempEnemy.speed = 3 + level;
tempEnemy.gotoAndStop(Math.floor(Math.random()*5)+1);
tempEnemy.y = 435;
tempEnemy.x = Math.floor(Math.random()*515)
addChild(tempEnemy);
enemies.push(tempEnemy);
}
}
public function moveEnemies():void{
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
tempEnemy.y -= tempEnemy.speed;
if (tempEnemy.y < -35){
chances -= 1;
chancesText.text = chances.toString();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testCollisions():void {
var sound:Sound = new Pop();
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
if(tempEnemy.hitTestObject(player)){
score++;
scoreText.text = score.toString();
sound.play();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testForEnd():void{
if(chances == 5){
gameState = STATE_END_GAME;
}
else if(score > level*20) {
level++;
levelText.text = level.toString();
}
}
public function endGame():void{
for(var i:int = 0; i< enemies.length; i++) {
removeChild(enemies[i]);
}
enemies = [];
player.stopDrag()
}
}
}
I have already tried adding this. and stage. in front of addchild and it still doesn't work.
This inside a file called Game.as
When you create your Game instance you need to add it as a child to the stage:
// I would probably rename the variable to 'game'
// 1st character of a variable name is conventionally lower-case
// var game:Game = new Game();
var Script:Game = new Game();
this.addChild(Script);

Action Script 3.0 The public attribute can only be used inside a package

The code below are inside a file called Script_1.as
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.text.*;
public class Game extends flash.display.MovieClip{
public static const STATE_INIT:int = 10;
public static const STATE_PLAY:int = 20;
public static const STATE_END_GAME:int = 30;
public var gameState:int = 0;
public var score:int = 0;
public var chances:int = 5;
public var bg:MovieClip;
public var enemies:Array;
public var paly:MovieClip;
public var level:Number = 0;
public var scoreLable:TextField = newTextField
public var levelLable:TextField = newTextField
public var chancesLable:TextField = newTextField
public var scoreText:TextField = newTextField
public var levelText:TextField = newTextField
public var chancesText:TextField = newTextField
public const SCOREBOARD_Y:Number = 380
public function Game(){
addEventListener(Event.ENTER_FRAME, gameLoop);
bg = new BackImage();
addChild(bg);
scoreLable.text = "Score:";
levelLable.text = "level:";
chancesLable.text = "Misses:";
scoreText.text = "0";
levelText.text = "1";
chancesText.text = "5";
scoreLable.y = SCOREBOARD_Y;
levelLablel.y = SCOREBOARD_Y;
chancesLabel.y = SCOREBOARD_;
scoreText.y = SCOREBOARD_Y;
levelText.y = SCOREBOARD_Y;
chancesText.y = SCOREBOARD_Y;
scoreLabel.x = 5;
scoreText.x = 50;
chancesLabel.x = 105;
chancesText.x = 155;
levelLabel.x = 205;
levelText.x = 260
addChild(scoreLabel);
addChild(levelLabel);
addChild(chancesLabel);
addChild(scoreText);
addChild(levelText);
addChild(chancesText);
gameState = STATE_INIT;
}
public function gameLoop(e:Event):void{
switch(gameState){
case STATE_INIT:
initGame();
break;
case STATE_PLAY:
playGame();
break;
case STATE_END_GAME:
endGame();
break;
}
//public function initGame():void{
score = 0;
chances = 5;
player = new playerImage();
enemies = newArray();
level = 1;
levelText.text = leveltoString();
addChild(player);
player.startDrag(true,newRectangle(0,0,550,400))
gameState = STATE_PLAY
}
//public function playGame():void{
player.rotation += 15;
makeEnemies();
moveEnemies();
testCollisions();
testForEnd();
}
//public function makeEnemies():void{
var chance:Number = Math.floor(Math.random()*100);
var tempEnemy:MovieClip;
if (chance < 2 + level) {
tempEnemy = new EnemyImage()
tempEnemy.speed = 3 + level;
tempEnemy.gotoAndStop(Math.floor(Math.randome()*5)+1);
tempEnemy.y = 435;
tempEnemy.x = Math.floor(Math.randome()*515)
addChild(tempEnemy);
enemies.push(tempEnemy);
}
}
//public function moveEnemies():void{
/var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
tempEnemy.y -= tempEnemy.speed;
if (tempEnemy.y < -35){
chances -= 1;
chancesText.text = chances.toString();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testCollisions();void {
var sound:Sound = new Pop();
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
if(tempEnemy.hitTestObject(player)){
score++;
scoreText.text = score.toString();
sound.play();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testForEnd():void{
if(chances == 5){
gameState = STATE_END_GAME;
}else if(score > level*20) {
level++;
levelText.text = level.toString();
}
}
public function endGame():void{
for(var i:int = 0; i< enemies.length; i++) {
removeChild(enemies[i]);
}
enemies = [];
player.stopDrag()
}
}
}
The Error Reports are:
The Public Attribute Can Only Be Used In A Package
(I put // before these Error Lines to mark them. They are not in the original code.)
Syntax error: expecting identifier before var.
Syntax error: expecting rightbrace before semicolon.
(I put / before these Errors. they are on the same line and the / is not in the original code either.)
Try rename your file to Game.as.
try to add a } after your switch case to close the function gameLoop().
PS:
Is it really your code ? Math.randome() ? newTextField ? newArray() ? public function testCollisions();void ? (;void)

AS3 Flash CS6 access of undefined properties? Help will be much obliged

Properties such as score1; score2, lives1, lives2 and STAGE seem to be undefined properties. I dont see why? Please help...
e.g.
C:\Users\PC\Desktop\Whack My Mole - Android\Game.as, Line 429 1120: Access of undefined property score1.
C:\Users\PC\Desktop\Whack My Mole - Android\Game.as, Line 430 1120: Access of undefined property score1.
package {
import flash.display.Stage;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.filters.DropShadowFilter;
import flash.text.AntiAliasType;
import flash.text.Font;
public class Game{
//Global Declarations
private var STAGE:Stage;
'Graphics'
private var Title:Title_mc;
private var Score_lbl:Label_Score_txt;
private var Lives_lbl:Label_Lives_txt;
private var holes:MoleHoles_mc;
private var Lives_txt:TextField;
private var Score_txt:TextField;
private var Shadow:DropShadowFilter;
private var Pause_btn:Button_Pause;
'Game Properties'
private var SLEEP:Timer;
private var countdown:Timer;
private var countdownComplete:Timer;
private var countdownDelay:Timer;
private var count:TextField;
private var count_inc:int;
private var Paused:Boolean;
private var moles:int;
public static var mole_spawn_delay:int = 1000;
public static var mole_death_delay:int = 1000;
public static var molePlacable:Boolean = true;
private var unavailableHole:int;
public static var molesName:String;
private var lvl:int = 51;
private var score1:Anim_Score1_mc;
private var score2:Anim_Score2_mc;
private var lives1:Anim_Lives1_mc;
private var lives2:Anim_Lives2_mc;
'Player Properties'
public static var Score:int = 0;
public static var Lives:int = 3;
public static var incrementer:int = 1;
public function Game(STAGE:Stage) {
this.STAGE = STAGE;
//Enable Touch Events
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
//Instantiate Objects
Shadow = new DropShadowFilter();
//Handle new frames
STAGE.addEventListener(Event.ENTER_FRAME, handle_ENTER_FRAME);
//Draw Graphics
'Menu Title'
Title = new Title_mc();
Title.x = 250.5;
Title.y = 62.35;
STAGE.addChild(Title);
'Content'
holes = new MoleHoles_mc();
holes.x = 0;
holes.y = 123.9;
STAGE.addChild(holes);
'Score Label'
Score_lbl = new Label_Score_txt();
Score_lbl.x = 19.65;
Score_lbl.y = 146.75;
STAGE.addChild(Score_lbl);
'Lives Label'
Lives_lbl = new Label_Lives_txt();
Lives_lbl.x = 358.25;
Lives_lbl.y = 141.05;
STAGE.addChild(Lives_lbl);
'Score Value'
Score_txt = new TextField();
Score_txt.x = 19.65;
Score_txt.y = 209.95;
Score_txt.width = 100;
Score_txt.defaultTextFormat = new TextFormat("Balloonist", 40, 0xFFFFFF);
Score_txt.selectable = false;
Score_txt.text = String(Score);
STAGE.addChild(Score_txt);
'Lives Value'
Lives_txt = new TextField();
Lives_txt.x = 410;
Lives_txt.y = 204.70;
Lives_txt.defaultTextFormat = new TextFormat("Balloonist", 40, 0xFFFFFF);
Lives_txt.selectable = false;
Lives_txt.text = String(Lives);
STAGE.addChild(Lives_txt);
'Pause Button'
Pause_btn = new Button_Pause();
Pause_btn.x = 22.40;
Pause_btn.y = 772.85;
STAGE.addChild(Pause_btn);
Pause_btn.buttonMode = true;
Pause_btn.addEventListener(TouchEvent.TOUCH_BEGIN, handle_Pause);
//Start Countdown
countDown();
}
//Pause/resume game
private function handle_Pause(e:TouchEvent):void
{
//...
}
//Sleep Method
private function sleep(seconds:int):void
{
SLEEP = new Timer(seconds, 1); // 1 second
SLEEP.addEventListener(TimerEvent.TIMER_COMPLETE, sleep_end);
SLEEP.start();
STAGE.frameRate = 0;
}
//Sleep Method Complete
private function sleep_end(e:TimerEvent):void
{
SLEEP.removeEventListener(TimerEvent.TIMER_COMPLETE , sleep_end);
STAGE.frameRate = 24;
}
//Count Down Timer
private function countDown():void
{
Paused = true;
count_inc = 5;
count = new TextField();
count.x = 213.9;
count.y = 158.05;
count.height = 150;
count.width = 150;
count.defaultTextFormat = new TextFormat("Balloonist", 150, 0xFFFFFF);
count.filters = [Shadow];
count.antiAliasType = AntiAliasType.ADVANCED;
count.sharpness = 400;
count.text = String(count_inc);
STAGE.addChild(count);
countdownComplete = new Timer(5000, 1);
countdownComplete.addEventListener(TimerEvent.TIMER, coutdown_Complete);
countdownDelay = new Timer(100);
countdownDelay.addEventListener(TimerEvent.TIMER, countDown_Tick);
countdown = new Timer(1000);
countdown.addEventListener(TimerEvent.TIMER, countDown_end);
countdownComplete.start();
countdownDelay.start();
countdown.start();
}
//Handle countdown tick
private function countDown_Tick(e:TimerEvent):void
{
if(count_inc <= 0)
{
countdown.stop();
countdown.removeEventListener(TimerEvent.TIMER, countDown_end);
}else {
countdownDelay.delay = 100;
}
}
//Handle countown complete
private function countDown_end(e:TimerEvent):void
{
if(count_inc <= 0)
{
countdownDelay.stop();
countdownDelay.removeEventListener(TimerEvent.TIMER, countDown_Tick);
}else{
count_inc -= 1;
count.text = String(count_inc);
}
}
//Countdown cleanup
private function coutdown_Complete(e:TimerEvent):void
{
STAGE.removeChild(count);
Paused = false;
}
//Main Game Loop
private function handle_ENTER_FRAME(e:Event):void
{
//Update game stuff
if(!Paused)
{
if(molePlacable)
{
sleep(mole_spawn_delay);
newMole();
}
Score_txt.text = String(Score);
Lives_txt.text = String(Lives);
}
//Clear stage & display game over interface
if(Lives <= 0)
{
STAGE.removeEventListener(Event.ENTER_FRAME, handle_ENTER_FRAME);
STAGE.removeChild(Title);
STAGE.removeChild(holes);
STAGE.removeChild(Score_lbl);
STAGE.removeChild(Lives_lbl);
STAGE.removeChild(Pause_btn);
STAGE.removeChild(Score_txt);
STAGE.removeChild(Lives_txt);
var gameOver:GameOver = new GameOver(STAGE);
}
//Update mole stats
if(moles > 50)
{
lvl = 71;
}
//Dissallow score to go below 0
if(Score < 0)
{
Score = 0;
}
}
//Create new Mole
private function newMole():void
{
'Specify mole hole'
var rnd = Math.ceil(Math.random()*11);
'Ensure mole does not spawn from preceding hole'
while(rnd == unavailableHole)
{
rnd = Math.ceil(Math.random()*11);
}
var X:int;
var Y:int;
switch(rnd)
{
case 0:
X = -14.75;
Y = 293.45;
break;
case 1:
X = 109.25;
Y = 291.35;
break;
case 2:
X = 223.75;
Y = 291.35;
break;
case 3:
X = 337.2;
Y = 291.35;
break;
case 4:
X = 0;
Y = 430;
break;
case 5:
X = 118.7;
Y = 430;
break;
case 6:
X = 226.9;
Y = 430;
break;
case 7:
X = 342.45;
Y = 430
break;
case 8:
X = 0;
Y = 561.35
break;
case 9:
X = 112.4;
Y = 561.35;
break;
case 10:
X = 229;
Y = 561.35;
break;
case 11:
X = 339.3;
Y = 561.35;
break;
}
'Specify molde to add'
rnd = lvl * Math.random();
if(rnd <=40)
{
//Default + 10*incrementer
var mole:Mole_Default_mc = new Mole_Default_mc(STAGE, X, Y);
}else if(rnd <=42){
//Crazy - 5*incrementer
var mole2:Mole_Crazy_mc = new Mole_Crazy_mc(STAGE, X, Y);
}else if(rnd <=43){
//Crazy2 - 10*inrementer
var mole3:Mole_Crazy2_mc = new Mole_Crazy2_mc(STAGE, X, Y);
}else if(rnd <45){
//Lady + 1 life
var mole4:Mole_Lady_mc= new Mole_Lady_mc(STAGE, X, Y);
}else if(rnd <46){
//Ninja - 2*inrementer
var mole5:Mole_Ninja_mc = new Mole_Ninja_mc(STAGE, X, Y);
}else if(rnd <47){
//Zombie + 5 * lives
var mole6:Mole_Zombie_mc = new Mole_Zombie_mc(STAGE, X, Y);
}else if(rnd <48){
//reaper - Lives
var mole7:Mole_Reaper_mc = new Mole_Reaper_mc(STAGE, X, Y);
}else if(rnd <49){
//Snob + 250
var mole8:Mole_Snob_mc = new Mole_Snob_mc(STAGE, X, Y);
}else if(rnd <52){
//Angel + 3 lives
var mole9:Mole_Angel_mc = new Mole_Angel_mc(STAGE, X, Y);
}else if(rnd <54){
//Demon - 3 lives
var mole10:Mole_Demon_mc = new Mole_Demon_mc(STAGE, X, Y);
}else if(rnd <55){
//Creature - 3+incrementer
var creature:Mole_Creature_mc = new Mole_Creature_mc(STAGE, X, Y);
}else if(rnd <56){
//Cyber + 50+incrementer
var cyber:Mole_Cyber_mc = new Mole_Cyber_mc(STAGE, X, Y);
}else if(rnd <57){
//Grumpy + 5
var grumpy:Mole_Grumpy_mc = new Mole_Grumpy_mc(STAGE, X, Y);
}else if(rnd <58){
//Hippie Lives+3 Score+100
var hippie:Mole_Hippie_mc = new Mole_Hippie_mc(STAGE, X, Y);
}else if(rnd<59){
//Hyper 30*incrementer
var hyper:Mole_Hyper_mc = new Mole_Hyper_mc(STAGE, X, Y);
}else if(rnd<60){
//Love timer-100
var love:Mole_Love_mc = new Mole_Love_mc(STAGE, X, Y);
}else if(rnd<61){
//LoveZombie - 20*Lives
var loveZombie:Mole_LoveZombie_mc = new Mole_LoveZombie_mc(STAGE, X, Y);
}else if(rnd<70){
//Sleepy Timer+100
var sleepy:Mole_Sleepy_mc = new Mole_Sleepy_mc(STAGE, X, Y);
}else if(rnd<71){
//Warrior + (10*incrementer)*2
var warrior:Mole_Warrior_mc = new Mole_Warrior_mc(STAGE, X, Y);
}
//Update mole stats
moles += 1;
if(mole_spawn_delay > 20 && mole_death_delay > 20)
{
mole_spawn_delay -= 10;
mole_death_delay -= 5;
}
//Update incrementer
if(moles > 100)
{
incrementer = 50;
}else if(moles > 80)
{
incrementer = 40;
}else if(moles > 60)
{
incrementer = 30;
}else if(moles > 20)
{
incrementer = 20;
}else if(moles > 10)
{
incrementer = 10;
}
}
//Animation
public static function animate(type:int)
{
if(type == 0)
{
score1 = new Anim_Score1_mc();
score1.x = 40;
score1.y = 250.6;
STAGE.addChild(score1);
var anim_timer:Timer = new Timer(2000, 1);
anim_timer.addEventListener(TimerEvent.TIMER, remove_score1);
anim_timer.start();
}else if(type == 1)
{
score2 = new Anim_Score2_mc();
score2.x = 32;
score2.y = 248.6;
STAGE.addChild(score2);
var anim_timer2:Timer = new Timer(2000, 1);
anim_timer2.addEventListener(TimerEvent.TIMER, remove_score2);
anim_timer2.start();
}else if(type == 2)
{
lives1 = new Anim_Lives1_mc();
lives1.x = 430.9;
lives1.y = 237.95;
STAGE.addChild(lives1);
var anim_timer3:Timer = new Timer(2000, 1);
anim_timer3.addEventListener(TimerEvent.TIMER, remove_lives1);
anim_timer3.start();
}else{
lives2 = new Anim_Lives2_mc();
lives2.x = 430.9;
lives2.y = 237.95;
STAGE.addChild(lives2);
var anim_timer4:Timer = new Timer(2000, 1);
anim_timer4.addEventListener(TimerEvent.TIMER, remove_lives1);
anim_timer4.start();
}
}
//Handle remove_score1
private function remove_score1(e:TimerEvent):void
{
STAGE.removeChild(score1);
}
//Handle remove_score2
private function remove_score2(e:TimerEvent):void
{
STAGE.removeChild(score2);
}
//Handle remove_lives1
private function remove_lives1(e:TimerEvent):void
{
STAGE.removeChild(lives1);
}
//Handle remove_lives2
private function remove_lives2(e:TimerEvent):void
{
STAGE.removeChild(lives2);
}
}
}
Replace:
public static function animate(type:int)
with
public function animate(type:int)
Or if you want to have that method static add:
private static var _instance:Game = null;
in Game Class definition and change animate function:
public static function animate(type:int):void{
if(_instance!=null) _instance.hidden_animate(type);
}
protected function hidden_animate(type:int){
// PLACE HERE CODE FROM YOUR ORIGINAL ANIMATE FUNCTION
}
in constructor function add:
_instance = this;
If you often use static methods (like in this code) read more bout design patterns like singleton :)

Netstream audio playing twice

I am new to flash (this is the first time I've ever used it or actionscript) and I'm trying to make a video player. The video player gets params from the embed code and pulls the videos from a folder on the server.
I've got the following code (I've removed everything that I'm 100% sure isn't causing my problem):
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.events.NetStatusEvent;
import flash.events.MouseEvent;
import flash.events.FullScreenEvent;
import flash.events.Event;
import flash.ui.Mouse;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.TextFormat;
import flash.media.SoundTransform;
var nc:NetConnection;
var ns:NetStream;
var ns2:NetStream;
var video:Video;
var video2:Video;
//get filename parameters from embed code
var filename:String = root.loaderInfo.parameters.filename;
var filename2:String = root.loaderInfo.parameters.filename2;
var t:Timer = new Timer(5000);
var duration;
var currentPosition:Number;
var st:Number;
var started:Boolean;
Object(this).mcPlay.buttonMode = true;
Object(this).mcPause.buttonMode = true;
Object(this).ScreenClick.buttonMode = true;
Object(this).mcMax.buttonMode = true;
Object(this).mcSwitcher.buttonMode = true;
Object(this).mcPause.addEventListener(MouseEvent.CLICK,PlayPause);
Object(this).mcPlay.addEventListener(MouseEvent.CLICK,PlayPause);
Object(this).ScreenClick.addEventListener(MouseEvent.CLICK,PlayPause);
Object(this).mcMax.addEventListener(MouseEvent.CLICK,Maximize);
Object(this).slideVolume.addEventListener(Event.CHANGE, ChangeVolume);
Object(this).mcSwitcher.addEventListener(MouseEvent.CLICK, ToggleSwitcher);
t.addEventListener(TimerEvent.TIMER, TimerComplete);
stage.addEventListener(MouseEvent.MOUSE_MOVE, resetTimer);
stage.addEventListener(MouseEvent.MOUSE_DOWN, resetTimer);
stage.addEventListener(MouseEvent.MOUSE_UP, resetTimer);
stage.addEventListener(Event.ENTER_FRAME, videoTimer);
if (!nc) start();
var IsPaused:String;
function start():void
{
Object(this).slideVolume.maximum = 100;
Object(this).slideVolume.value = 100;
started = false;
var tf:TextFormat = new TextFormat();
tf.color = 0xFFFFFF;
tf.bold = true;
this.lblTime.setStyle("textFormat", tf);
connect();
t.start();
}
function connect():void
{
nc = new NetConnection();
nc.client = this;
nc.addEventListener(NetStatusEvent.NET_STATUS, OnNetStatus);
nc.connect(null);
}
function OnNetStatus(e:NetStatusEvent):void
{
switch(e.info.code)
{
case "NetConnection.Connect.Success":
if (!started)
{
started = true;
stream();
}
else
{
finish();
}
break;
default:
finish();
break;
}
}
function stream():void
{
ns = new NetStream(nc);
ns.client = this;
ns.bufferTime = 5; // set the buffer time to 5 seconds
if ((filename2 != null) && (filename2.length > 0))
{
ns2 = new NetStream(nc)
//ns2.client = this; //Uncomment to use ns2 vid for duration info
ns2.bufferTime = 5; // set the buffer time to 5 seconds
startVideo(2);
currentPosition = 1; //Default
ns.seek(0);
ns2.seek(0);
}
else
{
this.mcSwitcher.visible = false;
startVideo(1);
ns.seek(0);
}
}
function startVideo(num:Number):void
{
var startVolume:SoundTransform = new SoundTransform();
startVolume.volume = slideVolume.value / 100;
if (num == 2)
{
video = new Video(320,180);
video.x = 0;
video.y = 90;
addChild(video);
video.attachNetStream(ns);
ns.checkPolicyFile = false;
ns.play(filename); //path/filename
setChildIndex(video,1);
video2 = new Video(320,180);
video2.x = 320;
video2.y = 90;
addChild(video2);
video2.attachNetStream(ns2);
ns2.checkPolicyFile = false;
ns2.play(filename2); //path/filename
setChildIndex(video2,1);
ns.soundTransform = startVolume;
var videoVolumeTransform2:SoundTransform = new SoundTransform();
videoVolumeTransform2.volume = 0;
ns2.soundTransform = videoVolumeTransform2;
ns2.receiveAudio(false);
}
else if (num == 1)
{
video = new Video(640,360);
video.x = 0;
video.y = 0;
addChild(video);
video.attachNetStream(ns);
ns.checkPolicyFile = false;
ns.play(filename); //path/filename
setChildIndex(video,1);
ns.soundTransform = startVolume;
}
IsPaused = "playing";
this.removeChild(mcPlay);
setChildIndex(this.ScreenClick,0);
setChildIndex(this.mcTitleOverlay,2);
}
function ShowControls ():void
{
for (var i:int = 0; i < Object(root).numChildren; i++)
{
switch (Object(root).getChildAt(i))
{
case mcPause:
if (IsPaused != "paused")
Object(root).getChildAt(i).visible = true;
break;
case mcPlay:
if (IsPaused != "playing")
Object(root).getChildAt(i).visible = true;
break;
case mcSwitcher:
if ((filename2 != null) && (filename2.length > 0))
Object(root).getChildAt(i).visible = true;
break;
default:
Object(root).getChildAt(i).visible = true; //Bring back everything else
break;
}
ScreenClick.y = 154;
}
}
function videoTimer(e:Event):void
{
var curTime = ns.time; //Current time in seconds
var curMinutes = Math.floor(curTime / 60); //Get the minutes
var curSeconds = Math.floor(curTime % 60); //Get the leftover seconds
var durMinutes = Math.floor(duration / 60);
var durSeconds = Math.floor(duration % 60);
//Add the zeroes to the begining of the seconds if it is needed.
if (curSeconds < 10)
curSeconds = "0" + curSeconds;
if (durSeconds < 10)
durSeconds = "0" + durSeconds;
Object(this).lblTime.text = curMinutes + ":" + curSeconds + " / " + durMinutes + ":" + durSeconds;
}
function PlayPause (e:MouseEvent):void
{
switch (IsPaused)
{
case "playing":
IsPaused = "paused";
this.mcPlay.visible = true;
this.mcPause.visible = false;
ns.togglePause();
ns2.togglePause();
break;
case "paused":
IsPaused = "playing";
this.mcPause.visible = true;
this.mcPlay.visible = false;
ns.togglePause();
ns2.togglePause();
break;
default:
//
break;
}
}
The problem I have is small but frustrating (I've spend most of today trying to figure it out with zero progress made). It is thus: Everything works perfectly, except that when the videos load up and play, sound plays twice (for the video that has sound enabled). I am at my wits end trying to figure this out, any help would be greatly appreciated!
Thanks!
EDIT:
Ok, on further research (re-writing every function very simply and seeing if the problem goes away with the features) I've determined that the following function is the root of all evil (or at least my problems):
function startVideo(num:Number):void
{
var startVolume:SoundTransform = new SoundTransform();
startVolume.volume = Object(this).slideVolume.sldVol.value / 100;
if (num == 2)
{
video = new Video(320,180);
video.x = 0;
video.y = 90;
addChild(video);
video.attachNetStream(ns);
ns.checkPolicyFile = false;
ns.play(filename); //path/filename
this.removeChild(btnPlay);
setChildIndex(video,1);
video2 = new Video(320,180);
video2.x = 320;
video2.y = 90;
addChild(video2);
video2.attachNetStream(ns2);
ns2.checkPolicyFile = false;
ns2.play("test.mp4"); //path/filename
setChildIndex(video2,1);
ns.soundTransform = startVolume;
var videoVolumeTransform2:SoundTransform = new SoundTransform();
videoVolumeTransform2.volume = 0;
ns2.soundTransform = videoVolumeTransform2;
ns2.receiveAudio(false);
}
else if (num == 1)
{
video = new Video(640,360);
video.x = 0;
video.y = 0;
addChild(video);
video.attachNetStream(ns);
ns.checkPolicyFile = false;
ns.play("test.flv"); //path/filename
setChildIndex(video,1);
ns.soundTransform = startVolume;
}
IsPaused = "playing";
this.removeChild(btnPlay);
setChildIndex(this.ScreenClick,0);
//setChildIndex(this.mcTitleOverlay,2);
}
I shall persevere with my troubleshooting (I've isolated the problem, hopefully the next step is a solution!