Do I have to write all the possibilities? - actionscript-3

I made a memory game
Fishes (it's buttons ) display on the screen and stop,then other fishes ( a wrong fishes ) display on the stage.After a while stops all the scene and player make guess ( click ) right fishes.
For example if player clicked 2 false and 1 true button,or 2 true and 1 false, this results in a loss for the player.And if clicked true 3 fis then this results in a win for the player.
But problem is I have to write code for all possibilities.How can I do as simple.
var clicked1:Boolean = false;
var clicked2:Boolean = false;
var clicked3:Boolean = false;
var clicked4:Boolean = false;
var clicked5:Boolean = false;
var clicked6:Boolean = false;
 
 
btn1.addEventListener(MouseEvent.CLICK, fish1);
function fish1(event:MouseEvent):void
{
clicked1 = true;
checkButtonsone()
}
 
btn2.addEventListener(MouseEvent.CLICK, redButton1a);
function redButton1a(event:MouseEvent):void
{
clicked2 = true;
checkButtonsone()
}
 
btn3.addEventListener(MouseEvent.CLICK, redButton12);
function redButton12(event:MouseEvent):void
{
clicked3 = true;
checkButtonsone()
}
 
btn4.addEventListener(MouseEvent.CLICK, redButton22);
function redButton22(event:MouseEvent):void
{
clicked4 = true;
checkButtonsone()
}
 
btn5.addEventListener(MouseEvent.CLICK, redButton32);
function redButton32(event:MouseEvent):void
{
clicked5 = true;
checkButtonsone()
}
 
btn6.addEventListener(MouseEvent.CLICK, redButton42);
function redButton42(event:MouseEvent):void
{
clicked6 = true;
checkButtonsone()
}
 
//Check true and false
function checkButtonsone():void
var correctcombine = false;
var falsecombine1 = false;
 
{
if(clicked1 && clicked2 && clicked3 )
{
correctcombine = true;
}
 
{
if(falsetiklandi && falsetiklandi && falsetiklandi){
falsecombine1 = true;
}
 
///Go to true or false
 
if(correctcombine == true)
 
{
gotoAndStop(3)
}
if(falsecombine1 == true)
{
gotoAndStop(2)
}
}
}
}
 

var buttons:Array = [fish1,fish2,fish3,fish4,fish5,fish6];
var correct:Array = [true,true,true,false,false,false];
var answers:Array = [false,false,false,false,false,false];
var clicksLeft:int = 3;
for each (var aButton:InteractiveObject in buttons)
{
aButton.addEventListener(MouseEvemt.CLICK, onButton);
}
function onButton(e:Event):void
{
var aButton:InteractiveObject = e.currentTarget as InteractiveObject;
var anIndex:int = buttons.indexOf(aButton);
// Remove click handler to avoid unnecessary handling.
aButton.removeEventListener(MouseEvemt.CLICK, onButton);
// Check answers.
answers[anIndex] = true;
clicksLeft--;
if (clicksLeft > 0)
{
return;
}
var aWrong:Boolean = false;
var aComplete:Boolean = true;
for (var i:int = 0; i < correct.length; i++)
{
if (answers[i] != correct[i])
{
if (answers[i])
{
// answers[i] == true and correct[i] == false
aWrong = true;
}
else
{
// answers[i] == false and correct[i] == true
// That means all correct buttons are not pressed yet.
aComplete = false;
}
}
}
if (aWrong)
{
// User failed case.
}
else if (aComplete)
{
// User win case.
}
}

You can change your code, so it becomes more easy in this way:
You can call the same event linked to different buttons and then you can evaluate the currentTarget property of event (passed as parameter)
btn1.addEventListener(MouseEvent.CLICK, changeClicked);
btn2.addEventListener(MouseEvent.CLICK, changeClicked);
btn3.addEventListener(MouseEvent.CLICK, changeClicked);
btn4.addEventListener(MouseEvent.CLICK, changeClicked);
btn5.addEventListener(MouseEvent.CLICK, changeClicked);
btn6.addEventListener(MouseEvent.CLICK, changeClicked);
function changeClicked(event:MouseEvent):void {
switch(event.currentTarget.id) {
case "btn1": {
clicked1 = true;
break;
}
case "btn2": {
clicked2 = true;
break;
}
case "btn3": {
clicked3 = true;
break;
}
case "btn4": {
clicked4 = true;
break;
}
case "btn5": {
clicked5 = true;
break;
}
case "btn6": {
clicked6 = true;
break;
}
}
checkButtonsone();
}
You must overwrite your code with mine from your:
btn1.addEventListener(MouseEvent.CLICK, fish1);
until line before
//Check true and false
Further optimization can be instead use 6 different variables, you can use an Array or ArrayCollection or you can define an object where you can encapsulated your different click.
UPDATE
You can define an ActionScript object named (for example) QuizLevel as follow:
[Bindable]
public class QuizLevel {
private var _levelNo:int;
private var _value1:Boolean;
private var _value2:Boolean;
private var _value3:Boolean;
private var _value4:Boolean;
private var _value5:Boolean;
private var _value6:Boolean;
// Here you put getter and setter
}
When you start a new quiz level, you define your matrix.
If only three are true you have a QuizLevel object instantiated as follow:
levelNo = 1
value1 = true
value2 = true
value3 = true
value4 = false
value5 = false
value6 = false
In your MXML definition you can write (insteead of button, use check box and one only button to submit your choose)
I've created a s:WindowedApplication (by AIR but is the same for Flash Player and others) and I've defined a preinitialized event in the s:WindowedApplication
import mx.controls.Alert;
import mx.events.FlexEvent;
[Bindable]
private var quizLevel:QuizLevel = new QuizLevel();
private var check1:Boolean = false;
private var check2:Boolean = false;
private var check3:Boolean = false;
private var check4:Boolean = false;
private var check5:Boolean = false;
private var check6:Boolean = false;
protected function windowedapplication1_preinitializeHandler(event:FlexEvent):void
{
quizLevel = new QuizLevel();
quizLevel.levelNo = 1;
quizLevel.value1 = true;
quizLevel.value2 = true;
quizLevel.value3 = true;
quizLevel.value4 = false;
quizLevel.value5 = false;
quizLevel.value6 = false;
}
protected function changeClicked(event:MouseEvent):void
{
var checkBox:CheckBox = event.currentTarget as CheckBox;
switch(event.currentTarget.id) {
case "chk1":{
check1 = checkBox.selected;
break;
}
case "chk2":{
check2 = checkBox.selected;
break;
}
case "chk3":{
check3 = checkBox.selected;
break;
}
case "chk4":{
check4 = checkBox.selected;
break;
}
case "chk5":{
check5 = checkBox.selected;
break;
}
case "chk6":{
check6 = checkBox.selected;
break;
}
}
}
protected function btnSubmit_clickHandler(event:MouseEvent):void
{
var message:String = "";
if (quizLevel.value1 == check1 &&
quizLevel.value2 == check2 &&
quizLevel.value3 == check3 &&
quizLevel.value4 == check4 &&
quizLevel.value5 == check5 &&
quizLevel.value6 == check6) {
message = "It'OK";
} else {
message = "You're wrong";
}
Alert.show(message);
}
]]>
</fx:Script>
<s:VGroup width="100%" height="100%">
<s:CheckBox id="chk1" label="Choose #1" click="changeClicked(event)" />
<s:CheckBox id="chk2" label="Choose #2" click="changeClicked(event)" />
<s:CheckBox id="chk3" label="Choose #3" click="changeClicked(event)" />
<s:CheckBox id="chk4" label="Choose #4" click="changeClicked(event)" />
<s:CheckBox id="chk5" label="Choose #5" click="changeClicked(event)" />
<s:CheckBox id="chk6" label="Choose #6" click="changeClicked(event)" />
<s:Button id="btnSubmit" label="Submit" click="btnSubmit_clickHandler(event)" />
</s:VGroup>

Related

Hovering off DPAD sometimes makes character move infinitely in one direction

I have a DPAD in my game when the player holds down let's say the Left DPAD, if he moves his touch to the Up DPAD and let's go, the player continues going in the left direction.
It also works if you hold the a direction, lets say Up continue holding but move off the Up DPAD, sometimes you may continue going in that direction.
What I've tried to prevent this:
On direction clicks, trigger checks on whether your in motion, or
already going a different direction
Setting collisions to force these variables to become false; aka,
you hit something, inMotion = false, etc
That's about all I can think of on how to fix this.
Also, I use a lot of variables for my checks, is it better to change my functions to return booleans, or is this way fine? Just curious.
Game Class
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Game extends MovieClip
{
public var area1:Boolean = true;
public var area2:Boolean = false;
public var area3:Boolean = false;
public var player1:Boolean = true;
public var player2:Boolean = false;
public var upWalkspeed:Number = -5;
public var downWalkspeed:Number = 5;
public var leftWalkspeed:Number = -5;
public var rightWalkspeed:Number = 5;
public var inMotion:Boolean = false;
public var goingUp:Boolean = false;
public var goingDown:Boolean = false;
public var goingLeft:Boolean = false;
public var goingRight:Boolean = false;
public var playerPosKeeper_mc:MovieClip = new mc_PlayerPosKeeper();
public var up_dpad:MovieClip = new dpad_Up();
public var down_dpad:MovieClip = new dpad_Down();
public var left_dpad:MovieClip = new dpad_Left();
public var right_dpad:MovieClip = new dpad_Right();
public var menu_dpad:MovieClip = new dpad_Menu();
public var run_dpad:MovieClip = new dpad_Menu();
public var barrierRoof1_game:MovieClip = new game_BarrierRoof();
public var barrierRoof2_game:MovieClip = new game_BarrierRoof();
public var barrierSide1_game:MovieClip = new game_BarrierSide();
public var barrierSide2_game:MovieClip = new game_BarrierSide();
public var StageCollisions:Array = new Array(barrierRoof1_game, barrierRoof2_game, barrierSide1_game, barrierSide2_game);
// fix MC goes after not before ||| public var player1States:Array = new Array(mc_P1D1,mc_P1D2,"mc_P1L1","mc_P1L2","mc_P1R1","mc_P1R2","mc_P1U1","mc_P1U2");
public function Game()
{
trace("SUCCESS | Constructed Game Class");
var aMove:Movement = new Movement(this);
addChild(aMove);
}
}
}
Movement Class
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TouchEvent;
import flash.net.dns.AAAARecord;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class Movement extends MovieClip
{
public function Movement(main:Game)
{
trace("SUCCESS | Constructed Movement Class");
addChild(main.playerPosKeeper_mc);
main.playerPosKeeper_mc.x = 384;
main.playerPosKeeper_mc.y = 46;
addChild(main.up_dpad);
main.up_dpad.x = 55;
main.up_dpad.y = 336;
addChild(main.down_dpad);
main.down_dpad.x = 57;
main.down_dpad.y = 432;
addChild(main.left_dpad);
main.left_dpad.x = 19;
main.left_dpad.y = 372;
addChild(main.right_dpad);
main.right_dpad.x = 118;
main.right_dpad.y = 372;
addChild(main.menu_dpad);
main.menu_dpad.x = 61;
main.menu_dpad.y = 377;
addChild(main.run_dpad);
main.run_dpad.x = 684;
main.run_dpad.y = 369;
addChild(main.barrierRoof1_game);
main.barrierRoof1_game.x = 0;
main.barrierRoof1_game.y = 0;
addChild(main.barrierRoof2_game);
main.barrierRoof2_game.x = 0;
main.barrierRoof2_game.y = 470;
addChild(main.barrierSide1_game);
main.barrierSide1_game.x = 0;
main.barrierSide1_game.y = 0;
addChild(main.barrierSide2_game);
main.barrierSide2_game.x = 790;
main.barrierSide2_game.y = 0;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
main.up_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, upBeginInput);
main.down_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, downBeginInput);
main.left_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, leftBeginInput);
main.right_dpad.addEventListener(TouchEvent.TOUCH_BEGIN, rightBeginInput);
// Maybe add diagnol direction buttons in the future?;
// !! NOTE !!
// Use some sort of value, maybe a return or a variable to sync up animations
// to if the player is moving, in the future
// Movement Directions
// Start of UP Movement
function upBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = true;
main.goingDown = false;
main.goingLeft = false;
main.goingRight = false;
main.up_dpad.addEventListener(TouchEvent.TOUCH_END, upEndInput);
addEventListener(Event.ENTER_FRAME,sendUpMovement);
}
function upEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingUp = false;
main.up_dpad.removeEventListener(TouchEvent.TOUCH_END, upEndInput);
removeEventListener(Event.ENTER_FRAME,sendUpMovement);
}
function sendUpMovement():void
{
if (main.inMotion == true && main.goingUp == true && main.goingDown == false && main.goingLeft == false && main.goingRight == false)
{
movePlayer(0, main.upWalkspeed);
}
else
{
}
}
// End of UP Movement
// Start of DOWN Movement
function downBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = false;
main.goingDown = true;
main.goingLeft = false;
main.goingRight = false;
main.down_dpad.addEventListener(TouchEvent.TOUCH_END, downEndInput);
addEventListener(Event.ENTER_FRAME,sendDownMovement);
}
function downEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingDown = false;
main.down_dpad.removeEventListener(TouchEvent.TOUCH_END, downEndInput);
removeEventListener(Event.ENTER_FRAME,sendDownMovement);
}
function sendDownMovement():void
{
if (main.inMotion == true && main.goingUp == false && main.goingDown == true && main.goingLeft == false && main.goingRight == false)
{
movePlayer(0, main.downWalkspeed);
}
else
{
}
}
// End of DOWN Movement
// Start of LEFT Movement
function leftBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = false;
main.goingDown = false;
main.goingLeft = true;
main.goingRight = false;
main.left_dpad.addEventListener(TouchEvent.TOUCH_END, leftEndInput);
addEventListener(Event.ENTER_FRAME,sendLeftMovement);
}
function leftEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingLeft = false;
main.left_dpad.removeEventListener(TouchEvent.TOUCH_END, leftEndInput);
removeEventListener(Event.ENTER_FRAME,sendLeftMovement);
}
function sendLeftMovement():void
{
if (main.inMotion == true && main.goingUp == false && main.goingDown == false && main.goingLeft == true && main.goingRight == false)
{
movePlayer(main.leftWalkspeed, 0);
}
else
{
}
}
// End of LEFT Movement
// Start of RIGHT Movement
function rightBeginInput(e:TouchEvent):void
{
main.inMotion = true;
main.goingUp = false;
main.goingDown = false;
main.goingLeft = false;
main.goingRight = true;
main.right_dpad.addEventListener(TouchEvent.TOUCH_END, rightEndInput);
addEventListener(Event.ENTER_FRAME,sendRightMovement);
}
function rightEndInput(e:TouchEvent):void
{
main.inMotion = false;
main.goingRight = false;
main.right_dpad.removeEventListener(TouchEvent.TOUCH_END, rightEndInput);
removeEventListener(Event.ENTER_FRAME,sendRightMovement);
}
function sendRightMovement():void
{
if (main.inMotion == true && main.goingUp == false && main.goingDown == false && main.goingLeft == false && main.goingRight == true)
{
movePlayer(main.rightWalkspeed, 0);
}
else
{
}
}
// End of RIGHT Movement
function movePlayer(movementX:Number, movementY:Number):void
{
var originalX:Number = main.playerPosKeeper_mc.x;
var originalY:Number = main.playerPosKeeper_mc.y;
main.playerPosKeeper_mc.x += movementX;
if (checkCollision())
{
main.playerPosKeeper_mc.x = originalX;
}
main.playerPosKeeper_mc.y += movementY;
if (checkCollision())
{
main.playerPosKeeper_mc.y = originalY;
}
}
function checkCollision():Boolean
{
for each (var StageCollisions:MovieClip in main.StageCollisions)
{
if (main.playerPosKeeper_mc.hitTestObject(StageCollisions))
{
return true;
main.inMotion = false;
main.goingUp = false;
main.goingDown = false;
main.goingLeft = false;
main.goingRight = false;
}
}
return false;
}
}
}
}
Before you even start to debug behaviors, you need to understand what algorithmic approach is. You have 4 similar pieces of code which differ in minor details and make your whole script too long and unreadable and hard to manage. Here's the guideline:
var isMoving:Boolean;
var Direction:Point = new Point;
var Buttons:Array = [Up, Down, Left, Right];
// Subscribe all buttons for the same handlers and behaviors.
for each (var aButton:InteractiveObject in Buttons)
{
aButton.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
aButton.addEventListener(MouseEvent.MOUSE_OUT, onUp);
aButton.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
function onDown(e:MouseEvent):void
{
// Figure which button was pressed.
switch (e.currentTarget)
{
case Up:
Direction.x = 0;
Direction.y = -1;
break;
case Down:
Direction.x = 0;
Direction.y = 1;
break;
case Left:
Direction.x = -1;
Direction.y = 0;
break;
case Up:
Direction.x = 1;
Direction.y = 0;
break;
}
// Now start moving Hero into the Direction.
if (!isMoving)
{
isMoving = true;
addEventListener(Event.ENTER_FRAME, onFrame);
}
}
function onFrame(e:Event):void
{
Hero.x += Direction.x;
Hero.y += Direction.y;
}
function onUp(e:MouseEvent):void
{
// If any of buttons is released or mouse out, stop moving Hero.
removeEventListener(Event.ENTER_FRAME, onFrame);
Direction.x = 0;
Direction.y = 0;
isMoving = false;
}
As you can see, the beauty of algorithmic approach is that you need to handle differently only things that need to be handled differently, in the example case (which is pretty similar to what you want to create) it is the block to set the movement direction. The rest of the code is identical for all the buttons and that's why the whole script is short and readable, easy to understand and manageable.

Change handler not triggering the first time in Flex

I use a multiple-check Drop-Down which does not trigger the first Change event. Subsequent events trigger properly. When I select Select All or any other option the first time it does not trigger the event either.
use namespace mx_internal;
[Style(name="selectAllBorderAlpha", type="Number", inherit="no", theme="spark, mobile", minValue="0.0", maxValue="1.0")]
[Style(name="selectAllBorderColor", type="uint", format="Color", inherit="no", theme="spark, mobile")]
[Style(name="selectAllBorderVisible", type="Boolean", inherit="no", theme="spark, mobile")]
[Style(name="selectAllBackgroundColor", type="uint", format="Color", inherit="no", theme="spark, mobile")]
[Style(name="selectAllBackgroundAlpha", type="Number", inherit="no", theme="spark, mobile", minValue="0.0", maxValue="1.0")]
[IconFile("DropDownList.png")]
[DiscouragedForProfile("mobileDevice")]
public class CheckBoxDropDownList extends CheckBoxDropDownListBase
{
public function CheckBoxDropDownList()
{
super();
addEventListener(IndexChangeEvent.CHANGE, indexChangeHandler);
}
protected function indexChangeHandler(event:IndexChangeEvent):void
{
selectedAll = false;
}
[SkinPart(required="false")]
public var selectAllCheckBox:CheckBox;
[SkinPart(required="false")]
public var selectAllHitArea:UIComponent;
[SkinPart(required="false")]
public var labelDisplay:IDisplayText;
private var labelChanged:Boolean = false;
private var labelDisplayExplicitWidth:Number;
private var labelDisplayExplicitHeight:Number;
private var sizeSetByTypicalItem:Boolean;
override public function get baselinePosition():Number
{
return getBaselinePositionForPart(labelDisplay as IVisualElement);
}
private var _prompt:String = "";
[Inspectable(category="General", defaultValue="")]
public function get prompt():String
{
return _prompt;
}
public function set prompt(value:String):void
{
if (_prompt == value)
return;
_prompt = value;
labelChanged = true;
invalidateProperties();
}
[Inspectable(category="Data")]
override public function set typicalItem(value:Object):void
{
super.typicalItem = value;
invalidateSize();
}
override protected function commitProperties():void
{
super.commitProperties();
if (labelChanged)
{
labelChanged = false;
updateLabelDisplay();
}
if (selectedAllChanged)
{
selectedAllChanged = false;
if (selectAllCheckBox)
{
selectAllCheckBox.selected = _selectedAll;
this.dispatchEvent(new Event("selectAllChanged"));
}
invalidateList();
}
}
override protected function partAdded(partName:String, instance:Object):void
{
super.partAdded(partName, instance);
if (instance == labelDisplay)
{
labelChanged = true;
invalidateProperties();
}
if (instance == selectAllCheckBox)
{
selectedAllChanged = true;
invalidateProperties();
}
if (instance == selectAllHitArea)
{
selectAllHitArea.addEventListener(MouseEvent.CLICK, selectAllHitArea_clickHandler);
}
}
override protected function partRemoved(partName:String, instance:Object):void
{
super.partRemoved(partName, instance);
if (instance == selectAllHitArea)
{
selectAllHitArea.removeEventListener(MouseEvent.CLICK, selectAllHitArea_clickHandler);
}
}
protected function selectAllHitArea_clickHandler(event:MouseEvent):void
{
if (selectAllCheckBox)
selectedAll = !selectAllCheckBox.selected;
}
private var _selectedAll:Boolean = false;
private var selectedAllChanged:Boolean;
public function get selectedAll():Boolean
{
return _selectedAll;
}
public function set selectedAll(value:Boolean):void
{
if (value == _selectedAll)
return;
_selectedAll = value;
selectedAllChanged = true;
labelChanged = true;
selectedIndices = Vector.<int>([]);
//setSelectedItem(undefined, false);
invalidateProperties();
}
public function setSelectedIndices(selValues:Array):void
{
if (this.dataProvider == null) {
return;
}
var selIndices:Vector.<int> = new Vector.<int>();
if (selValues == null || selValues.length == 0)
{
this.selectedAll = true;
return;
}
for(var i:int=0; i < this.dataProvider.length; i++)
{
for(var j:int=0; j < selValues.length; j++)
{
var obj:Object = this.dataProvider.getItemAt(i);
if(selValues[j] == obj.value || selValues[j] == obj.label)
{
selIndices.push(i);
break;
}
}
}
if (selIndices.length == 0)
{
this.selectedAll = true;
}
else
{
this.selectedAll = false;
this.selectedIndices = selIndices;
}
}
override protected function item_mouseDownHandler(event:MouseEvent):void
{
if (selectedAll)
{
selectedAll = false;
var newIndex:int
if (event.currentTarget is IItemRenderer)
newIndex = IItemRenderer(event.currentTarget).itemIndex;
else
newIndex = dataGroup.getElementIndex(event.currentTarget as IVisualElement);
var arr:Array = dataProvider.toArray()
arr.splice(newIndex, 1);
selectedItems = Vector.<Object>(arr);
return;
}
super.item_mouseDownHandler(event);
// if all items are selected, then unselect them and check the "Select All" checkbox.
if (selectedItems.length == dataProvider.length)
{
selectedAll = true;
selectedIndex = -1;
}
}
override protected function dropDownController_closeHandler(event:DropDownEvent):void
{
super.dropDownController_closeHandler(event);
// Automatically selected all items if no items are selected when closing the dropDown.
if (selectedItems.length == 0 && !selectedAll)
selectedAll = true;
}
override protected function measure():void
{
var labelComp:TextBase = labelDisplay as TextBase;
// If typicalItem is set, then use it for measurement
if (labelComp && typicalItem != null)
{
// Save the labelDisplay's dimensions in case we clear out typicalItem
if (!sizeSetByTypicalItem)
{
labelDisplayExplicitWidth = labelComp.explicitWidth;
labelDisplayExplicitHeight = labelComp.explicitHeight;
sizeSetByTypicalItem = true;
}
labelComp.explicitWidth = NaN;
labelComp.explicitHeight = NaN;
// Swap in the typicalItem into the labelDisplay
updateLabelDisplay(typicalItem);
UIComponentGlobals.layoutManager.validateClient(skin, true);
// Force the labelDisplay to be sized to the measured size
labelComp.width = labelComp.measuredWidth;
labelComp.height = labelComp.measuredHeight;
// Set the labelDisplay back to selectedItem
updateLabelDisplay();
}
else if (labelComp && sizeSetByTypicalItem && typicalItem == null)
{
// Restore the labelDisplay to its original size
labelComp.width = labelDisplayExplicitWidth;
labelComp.height = labelDisplayExplicitHeight;
sizeSetByTypicalItem = false;
}
super.measure();
}
override mx_internal function updateLabelDisplay(displayItem:* = undefined):void
{
if (labelDisplay)
{
if (displayItem == undefined)
{
if (selectedItems != null && selectedItems.length > 1)
displayItem = VectorUtils.vectorToArray(selectedItems, Object);
else
displayItem = selectedItem;
}
if (displayItem != null && displayItem != undefined)
if (displayItem is Array)
{
this.toolTip = selectedItemsToLabel(displayItem, labelField, labelFunction);
labelDisplay.text = (displayItem as Array).length + " selected";
}
else
{
this.toolTip = null;
labelDisplay.text = selectedItemsToLabel(displayItem, labelField, labelFunction);
}
else if (selectedAll)
labelDisplay.text = "All";
else
labelDisplay.text = prompt;
}
}
private function invalidateList():void
{
if (dataGroup == null)
return;
for each (var itemIndex:int in dataGroup.getItemIndicesInView())
{
var renderer:UIComponent = dataGroup.getElementAt(itemIndex) as UIComponent;
if (renderer)
renderer.invalidateDisplayList();
}
}
private function selectedItemsToLabel(item:Object, labelField:String=null, labelFunction:Function=null):String
{
if (labelFunction != null)
return labelFunction(item);
var collection:ICollectionView = null;
if (item is Array)
{
collection = new ArrayCollection(item as Array);
}
else if (item is ICollectionView)
{
collection = ICollectionView(item);
}
else if (item is IList)
{
collection = new ListCollectionView(IList(item));
}
if (collection != null)
{
var itemLabels:Array = [];
for each (var obj:Object in collection)
{
itemLabels.push(obj[labelField]);
}
return itemLabels.join(", ");
}
return LabelUtil.itemToLabel(item, labelField, labelFunction);
}
public function get selectedValues():Array
{
var arr:Array = [];
if(selectedItems != null && selectedItems.length > 0)
{
for each (var obj:Object in selectedItems)
arr.push(obj.value);
}
return arr;
}
public function get selectedLabels():Array
{
var arr:Array = [];
if(selectedItems != null && selectedItems.length > 0)
{
for each (var obj:Object in selectedItems)
arr.push(obj.label);
}
return arr;
}
}
Try to call super() after the addEventListener() in the constructor function

Implicit coercion of a value of type flash.events:KeyboardEvent to an unrelated type flash.events:MouseEvent

how can I call a function of flash events : MouseEvent in flash events keyboardEvent function
I am a biggner in as3 please help
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
function keyPressed(event:KeyboardEvent){
if (event.keyCode == Keyboard.ENTER)
{
if (keyMode == 0)
{
keyMode = 1;
**startFun(event);**
}
else if (keyMode == 1)
{
**checkfun(event);**
}
else if (keyMode == 2)
{
keyMode = 1;
**anotherPro(event);**
}
}
}
There is several ways, dispatch events, etc. I'll give you a simple example:
// or should be KEY_UP?
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedHandler, false, 0, true);
stage.addEventListener(MouseEvent.CLICK, exampleMouseClickHandler, false, 0, true);
function exampleMouseClickHandler(event:MouseEvent):void
{
//if necessary to pass any parameter, just need to change these mouseClickLogic() / keyPressLogic() methods
mouseClickLogic();
keyPressLogic();
}
function mouseClickLogic():void
{
//do something...
}
function keyPressedHandler(event:KeyboardEvent):void
{
//if necessary to pass any parameter, just need to change these mouseClickLogic() / keyPressLogic() methods
keyPressLogic();
mouseClickLogic();
}
function keyPressLogic():void
{
//to something...
}
You can use like that:
MouseEvent in flash events:
import flash.events.MouseEvent;
stage.addEventListener(MouseEvent.CLICK,clickStage);
stage.addEventListener(MouseEvent.MOUSE_UP,upStage);
stage.addEventListener(Event.MOUSE_LEAVE,leaveStage);
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownStage);
function clickStage(e:MouseEvent):void
{
trace("click Stage");
}
function upStage(e:MouseEvent):void
{
trace("up Stage");
}
function leaveStage(e:Event):void
{
trace("leave Stage");
}
function mouseDownStage(e:MouseEvent):void
{
trace("mouse Down Stage");
}
keyboardEvent function:
function reportKeyDown(event:KeyboardEvent):void
{
trace("Key Pressed: " + String.fromCharCode(event.charCode) + " (character code: " + event.charCode + ")");
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
I thank all those who tried to help me
this is my program without any error the error which I made before is in this code instead of Event
I typed MousEvent
function startFun(evt:Event):void
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.Event;
var elapsedTime:Number;
var NumOfProplem:Number;
var PropSolved:Number;
var completeSet:Boolean;
answerbox.restrict = "0-9";
ProplemBox.restrict = "0-9";
mult2.restrict = "?";
mult1.restrict = "?";
var keyMode:Number = 0;
stage.focus = ProplemBox;
bt1.visible = false;
bt2.visible = false;
//////////////////////////////
btnstart.addEventListener(MouseEvent.CLICK, startFun);
function startFun(evt:Event):void {
if (ProplemBox.text == "") {
stage.focus = ProplemBox;
return;
}
bt1.visible = true;
bt2.visible = true;
NumOfProplem = Number(ProplemBox.text);
PropSolved = 0;
completeSet = false;
elapsedTime = getTimer();
keyMode = 1;
anotherPro(evt);
}
///////////////////////////////
stage.focus = answerbox;
answerbox.setSelection(0,3);
}
/////////////////
bt1.addEventListener(MouseEvent.CLICK,checkfun);
function checkfun(evt:Event):void
{
var x:Number = parseInt(mult1.text);
var y:Number = parseInt(mult2.text);
var z:Number = parseInt(answerbox.text);
if ((x*y )== z){
messagebox.text = "Right";
PropSolved++;
if (PropSolved >= NumOfProplem ){
keyMode = 3;
endGameReport();
}
else{
keyMode = 2;
}
}
else
{
messagebox.text = "Wrong";
stage.focus = answerbox;
answerbox.setSelection(0,3);
}
}
function endGameReport():void{
elapsedTime = (getTimer() - elapsedTime);
stage.focus = ProplemBox;
ProplemBox.setSelection(0,2);
bt1.visible = false;
bt2.visible = false;
messagebox.text = "You completed" + NumOfProplem + "Proplems in"
+ Math.floor(elapsedTime/1000) + "Second";
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
function keyPressed(evt:KeyboardEvent){
if (evt.keyCode == Keyboard.ENTER)
{
if (keyMode == 0)
{
keyMode = 1;
startFun(evt);
}
else if (keyMode == 1)
{
checkfun(evt);
}
else if (keyMode == 2)
{
keyMode = 1;
anotherPro(evt);
}
}
}

Argument error 1063 in AS3

so I have been working on a game called rock scissors paper lizard spock.
I got this error:
ArgumentError: Error #1063: Argument count mismatch on FlashGame_fla::MainTimeline/backtoBanana(). Expected 0, got 1.
this is my main code:
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.TextFormat;
rulesButton.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.visible = false;
gameRules.buttonMode = true;
function toggleRule(evt:MouseEvent):void
{
gameRules.visible = ! gameRules.visible;
}
menuButton.addEventListener(MouseEvent.CLICK, Click_backtoMain);
function Click_backtoMain(event:MouseEvent):void
{
gotoAndStop(213);
}
var isRolling:Boolean = false; //defalt is "false"
var pDieVal:int = 0;
var gDieVal:int = 0;
var pScore:int = 0;
var gScore:int = 0;
var pRolls:int = 0;
pDieMC.stop();
gDieMC.stop();
msgDisplay.text = "Click on the banana \nbutton to roll the die!";
pScoreDisplay.text = "0";
gScoreDisplay.text = "0";
rollButton.addEventListener(MouseEvent.CLICK, rollDie);
rollButton.addEventListener(MouseEvent.CLICK, dieRoll);
bananaWinLose.visible = false;
gameOverBananaMC.visible = false;
toMenuBtn.visible = false;
rollAgainBtn.visible = false;
function rollDie(evt:MouseEvent): void
{
if (isRolling)
{
//change flag to show die is NOT rolling
isRolling = false;
//change the label on the button to "BANANA!"
buttonDisplay.text = "BANANA!";
// STOP the dice animations
pDieVal= Math.ceil(Math.random() * pDieMC.totalFrames);
pDieMC.gotoAndStop(pDieVal);
gDieVal = Math.ceil(Math.random() * gDieMC.totalFrames);
gDieMC.gotoAndStop(gDieVal);
//set message display to an empty string
msgDisplay.text = "";
whoWon();
score();
}
else
{
//change flag to show die is rolling
isRolling = true;
//change the label on the button to "Stop"
buttonDisplay.text = "POPADAM!";
//PLAY the dice animations
pDieMC.play();
gDieMC.play();
//clear the message display
msgDisplay.text = "";
}
}
function whoWon():void
{
// is it a tie?
if (pDieVal == gDieVal)
{
msgDisplay.text = "Papoi?! It's a tie!";
}
else
{
// assume the player has lost
var hasPlayerWon:Boolean = false;
// determine if the player wins
if (pDieVal == 1 && (gDieVal == 4 || gDieVal == 5))
{
hasPlayerWon = true;
}
else if (pDieVal == 2 && (gDieVal == 1 || gDieVal == 5))
{
hasPlayerWon = true;
}
else if (pDieVal == 3 && (gDieVal == 1 || gDieVal == 2))
{
hasPlayerWon = true;
}
else if (pDieVal == 4 && (gDieVal == 3 || gDieVal == 2))
{
hasPlayerWon = true;
}
else if (pDieVal == 5 && (gDieVal == 3 || gDieVal == 4))
{
hasPlayerWon = true;
}
// display the results to the player
if (hasPlayerWon)
{
msgDisplay.text = "Yay! You win!";
}
else
{
msgDisplay.text = "Boo! Stuart wins!";
}
}
}
function dieRoll(evt:MouseEvent):void
{
trace("calculating pRolls");
if (pRolls == 20)
{
rpslsWon();
}
else
{
//increment pRolls by 1
pRolls++;
}
}
function score():void
{
//if player wins, his/her score increases by 1
if (msgDisplay.text == "Yay! You win!")
{
pScore = pScore + 1
pScoreDisplay.text = pScore.toString();
//if player loses, computer score increases by 1
}
else if (msgDisplay.text == "Boo! Stuart wins!")
{
gScore = gScore + 1
gScoreDisplay.text = gScore.toString();
//if neither wins, their scores remain unchange
}
else
{
pScore = pScore
gScore = gScore
}
}
function rpslsWon():void
{
gameOverBananaMC.visible = true;
bananaWinLose.visible = true;
bananaWinLose.text = "Kampai! You are totally bananas!! \nYour Score: " + pScore;
toMenuBtn.visible = true;
rollAgainBtn.visible = true;
toMenuBtn.addEventListener(MouseEvent.CLICK, Click_backtoMain);
rollAgainBtn.addEventListener(MouseEvent.CLICK, backtoBanana);
}
function backtoBanana():void
{
pScore = 0;
gotoAndStop("menu");
gotoAndStop("banana");
}
so the error appears in the function backtoBanana(), I can't seem to fix it.
Can someone help me? Thanks alot.
The callback function for the MouseEvent-listener will be passed a MouseEvent. Change
function backtoBanana():void
to
function backtoBanana(event:MouseEvent):void
just like your other callback function:
function Click_backtoMain(event:MouseEvent):void

1120: Access of undefined property _stop

i am having problem in creating a video player in flash via as3, the problem is that whenever i try to compile the project, the compiler error shows:
1120: Access of undefined property _stop.
1120: Access of undefined property _pause.
1120: Access of undefined property _play.
1180: Call to a possibly undefined method Button.
1120: Access of undefined property _prev.
1180: Call to a possibly undefined method Button.
1120: Access of undefined property _next.
And this keeps on going as much i've mentioned these objects, so please help me solve this. and am newbie so a bit hard for me to find the error.
as3:
import flash.events.MouseEvent;
var _xmlLoader :URLLoader = null;
var _urlRequest :URLRequest = null;
var _xml :XML = null;
var _netConn :NetConnection = null;
var _netstr :NetStream = null;
var _video :Video = null;
var _currentVideoId :int = 0;
var _isPlaying :Boolean = false;
var _soundTransform :SoundTransform = new SoundTransform();
var _volume :int = 1;
var _duration :Number = 0;
function Init():void
{
_urlRequest = new URLRequest("vids.xml");
_xmlLoader = new URLLoader();
_xmlLoader = new URLLoader(_urlRequest);
_xmlLoader.addEventListener(Event.COMPLETE, XMLLoaded, false, 0, true);
}
function XMLLoaded($e:Event):void
{
_xml = new XML($e.target.data);
}
function SetupVideo():void
{
_netConn = new NetConnection();
_netConn.addEventListener(NetStatusEvent.NET_STATUS, OnStatusEvent, false, 0, true);
_netConn.connect(null);
}
function OnStatusEvent(stat:Object):void
{
trace(stat.info.code);
switch(stat.info.code)
{
case "NetConnection.Connect.Success":
SetupNetStream();
break;
case "NetStream.Play.Stop":
_stop.enabled = false;
_pause.enabled = false;
_play.enabled = true;
_isPlaying = false;
_netstr.close();
break;
}
}
function SetupNetStream():void
{
_netstr = new NetStream(_netConn);
_netstr.addEventListener(NetStatusEvent.NET_STATUS, OnStatusEvent, false, 0, true);
var $customClient = new Object();
$customClient.onMetaData = onMetaData;
_netstr.client = $customClient
_video = new Video(500, 250);
_video.smoothing = true;
_video.y
_video.x = stage.stageWidth/2 - _video.width/2;
_video.attachNetStream(_netstr);
addChild(_video);
}
function onMetaData($info:Object):void
{
_duration = $info.duration;
}
function SetupButtons():void
{
_prev.addEventListener(MouseEvent.CLICK, PreviousVideo, false, 0, true);
_next.addEventListener(MouseEvent.CLICK,NextVideo,false,0,true);
_play.addEventListener(MouseEvent.CLICK, PlayVideo, false, 0, true);
_pause.addEventListener(MouseEvent.CLICK, PauseVideo, false, 0, true);
_stop.addEventListener(MouseEvent.CLICK, StopVideo, false, 0, true);
_sound.addEventListener(MouseEvent.CLICK, SoundVolume, false, 0, true);
_stop.enabled = false;
_pause.enabled = false;
_prev.enabled = false;
_next.enabled = false;
}
function PreviousVideo($e:MouseEvent):void
{
_currentVideoId -=1;
_stop.enabled = true;
_pause.enabled = true;
_play.enabled = false;
if(_currentVideoId < 0)
{
_currentVideoId = _xml.video.length()-1;
}
_videoName.text = _xml.video[_currentVideoId].#name;
_netstr.play(String(_xml.video[_currentVideoId].#path));
}
function NextVideo($e:MouseEvent):void
{
_currentVideoId +=1;
_stop.enabled = true;
_pause.enabled = true;
_play.enabled = false;
if(_currentVideoId == _xml.video.length())
{
_currentVideoId = 0;
}
_videoName.text = _xml.video[_currentVideoId].#name;
_netstr.play(String(_xml.video[_currentVideoId].#path));
}
function PlayVideo($e:MouseEvent):void
{
_play.enabled= false;
_next.enabled = true;
_prev.enabled = true;
_stop.enabled= true;
_pause.enabled= true;
if(_isPlaying == false)
{
_isPlaying = true;
_netstr.play(String(_xml.video[_currentVideoId].#path));
_videoName.text = _xml.video[_currentVideoId].#name;
addEventListener(Event.ENTER_FRAME, Update, false, 0, true);
}else{
_netstr.resume();
}
}
function PauseVideo($e:MouseEvent):void
{
_play.enabled= true;
_pause.enabled= false;
_netstr.pause();
}
function StopVideo($e:MouseEvent):void
{
_stop.enabled= false;
_pause.enabled= false;
_play.enabled= true;
_isPlaying = false;
removeEventListener(Event.ENTER_FRAME, Update);
_netstr.close();
}
function Update($e:Event):void
{
_track.value = (_netstr.time / _duration) * _track.maximum;
}
function SoundVolume($e:MouseEvent):void
{
if( _volume == 1 )
{
_volume = 0;
_sound.label = "Sound On";
}else{
_volume = 1;
_sound.label = "Sound Off";
}
_soundTransform.volume = _volume;
_netstr.soundTransform = _soundTransform;
}
Init();
SetupVideo();
SetupButtons();
And even i've converted this objects to button symbols.
Probably you forgot to assign instance name for the objects, which used as a _stop, _pause, _play buttons etc.
And also check the "Export for the ActionScript" flag in the properties in the library.