Code for a 10x10 multiplication table in flash as3, - actionscript-3

I'm new to coding in AS3, and I would like some assistance. I've recieved a task where I have to code a Multiplication table (10 rows, 10 columns). I've managed to code the table, but I need help to add the numbers needed without manually adding the text.
It should look somewhat like this;
Can someone here assist me with this task?
Here is my code:
var xColumns:uint=10;
var xRows:uint=10;
var _columnWidth:Number=40;
var _rowHeight:Number=40
var _width:Number=_columnWidth*xColumns;
var _height:Number=_rowHeight*xRows;
graphics.lineStyle(2, 0x0000ff, 1);
for(var i:int=1; i<=xColumns; i++){
graphics.moveTo(i*_columnWidth,0);
graphics.lineTo(i*_columnWidth,_height);
}
for(i=1; i<=xRows; i++){
graphics.moveTo(0,i*_rowHeight);
graphics.lineTo(_width,i*_rowHeight);
}

This is the sample of "Cell" class:
package
{
import flash.display.Graphics;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
public class Cell extends Sprite
{
//---------------------------------------
protected var m_oLabel:TextField;
protected var m_nWidth:Number = 20;
protected var m_nHeight:Number = 20;
protected var _backgroundColor:Number;
//---------------------------------------
//Group: CONSTRUCTOR
public function Cell()
{
super();
m_oLabel = new TextField();
m_oLabel.text = "999";
m_oLabel.autoSize = TextFieldAutoSize.CENTER;
addChild(m_oLabel);
setLabel("999");
}
//--------------------------------------------------//
// PUBLIC PUBLIC PUBLIC PUBLIC //
//--------------------------------------------------//
public function setLabel(p_sLabel:String):void
{
m_oLabel.text = p_sLabel || "";
updateLayout();
}
public function get backgroundColor():Number
{
return _backgroundColor;
}
public function set backgroundColor(value:Number):void
{
_backgroundColor = value;
redraw();
}
//------------------- OVERRIDDEN -------------------//
override public function get width():Number
{
return m_nWidth;
}
override public function set width(value:Number):void
{
m_nWidth = value;
updateLayout();
redraw();
}
override public function get height():Number
{
return m_nHeight;
}
override public function set height(value:Number):void
{
m_nHeight = value;
updateLayout();
redraw();
}
//--------------------------------------------------//
// PRIVATE/PROTECTED PRIVATE/PROTECTED //
//--------------------------------------------------//
protected function updateLayout():void
{
//adjust layout
if (m_oLabel)
{
m_oLabel.x = width * .5 - m_oLabel.width * .5;
m_oLabel.y = height * .5 - m_oLabel.height * .5;
}
}
protected function redraw():void
{
var g:Graphics = this.graphics;
g.beginFill(_backgroundColor);
g.drawRect(0, 0, width, height);
g.endFill();
}
//------------------- OVERRIDDEN -------------------//
//--------------------------------------------------//
// EVENTS EVENTS EVENTS EVENTS //
//--------------------------------------------------//
//------------------- OVERRIDDEN -------------------//
//--------------------------------------------------//
// UTILS UTILS UTILS UTILS //
//--------------------------------------------------//
//------------------- OVERRIDDEN -------------------//
}
}
and usage:
var container:Sprite = new Sprite();
addChild(container);
container.x = 10;
container.y = 10;
for (var i:int = 0; i <= 10; i++)
{
for (var j:int = 0; j <= 10; j++)
{
var cell:Cell = new Cell();
if (i == 0 || j == 0)
{
//headers
cell.setLabel(Math.max(i, j).toString());
cell.backgroundColor = 0x808080;
}
else
{
var mul:Number = i * j;
cell.setLabel(mul.toString());
cell.backgroundColor = 0xC0C0C0;
}
container.addChild(cell);
cell.x = cell.width * j;
cell.y = cell.height * i;
}
}
which looks like this:
new class "Cell" gives you flexibility and encapsulation of code for creation of single table cell. In my example it is only container for textfield and has ability to draw background. I've created public methods/accessors that allow to modify the "features" of the cell (i.e. what is displayed in TextField and what is colour of background). I had to override default width/height behaviour as otherwise it would return the size of it's content which would vary depending on the TextField content and size and in table we need steady size.

Related

Error: Call to a possibly undefined method crearNotaS through a reference with static type Class

I'm new at programming and I'm working on a 'minigame' for my career.
I'm getting this error, hope someone can help me out.
public class Notas
{
public var stage:Stage;
public var velocidad:int = 5;
public var i:int = 0;
public var notaS:Array = new Array(16);
public var notaD:Array = new Array(16);
public function Notas(escenario:Stage)
{
stage = escenario;
}
public function Inicializar():void
{
crearNotaS(0xFFFFFF, 30, 10, 0, 0);
}
public function Destruir():void
{
if (notaS[i].y < 720)
{
for (i = 0; i < notaS.length; i++)
{
stage.removeChild(notaS[i])
}
}
}
public function Mover():void
{
notaS[i].y += velocidad;
}
public function drawRect(color:uint, ancho:int, alto:int, x:int, y:int):Sprite
{
var dj:Sprite = new Sprite();
dj.graphics.beginFill(color,1);
dj.graphics.drawRect(0,0,ancho,alto);
dj.graphics.endFill();
dj.x = x;
dj.y = y;
return(dj);
}
public function asignarNotas():void
{
notaS[0] = 1
}
public function crearNotaS(color:int, ancho:int, alto:int, x:int, y:int):void
{
var contador:int = 0;
for (i = 0; i < notaS.length; i++)
{
if (notaS[i] == 1 && i == 0)
{
notaS[i] = drawRect(color, ancho, alto, x, y);
stage.addChild(notaS[i]);
notaS[i].y = -alto / 2;
}
else if (notaS[i] == 1 && i > 0)
{
for (j = i; j < notaS.length; j++)
{
contador = i - j
notaS[i] = drawRect(color, ancho, alto, x, notaS[j].y + alto * contador);
stage.addChild(notaS[i]);
return;
}
}
}
}
}
Its supposed to create a array of squares (only if the content of the index is a 1, if it is a 0 then it won't create the square there.) one on top of each other and then move them all down, like a guitar hero.
Probably the way im doing it isn't proper but well, its the 1st thing i'm doing on my own...
ActionScript is an object oriented Language. Classes are supposed to be objects too and when you want to access their methods you either need to make an instance of them first or make sure the target function is of type "Static", which has limitations of its own.
This is all about core concepts which you need to know before running your code. I suggest taking a look at some tutorials about classes. This might be a good start:
Tutorial: Understanding Classes in AS3 Part 1
But about your code. It misses some imports and variable definitions, not a major flaw though. Im able to run your code. I will attach a zip file containing the AS3 AIR project which i created to test the code: Test Project
You could do this yourself in couple of steps:
Create an As3 project in the IDE of your choice. (I use FlashDevelop)
Declare the variable of type YourClass (Notas) which holds instance of your class
before using functions of your class make an instance of your class and store it in the variable.
viola, use public methods and properties of your class by accessing the variable you created.
this is the main function:
package
{
import flash.display.Sprite;
/**
* ...
* #author tkiafar
*/
public class Main extends Sprite
{
private var _not:Notas;
public function Main():void
{
if (stage) {
_not = new Notas(this.stage);
_not.asignarNotas();
_not.Inicializar();
}
}
}
}
this is your class that resides in the main package (beside main.as):
package
{
import flash.display.Sprite;
import flash.display.Stage;
public class Notas
{
public var stage:Stage;
public var velocidad:int = 5;
public var i:int = 0;
public var j:int = 0;
public var notaS:Array = new Array(16);
public var notaD:Array = new Array(16);
public function Notas(escenario:Stage)
{
stage = escenario;
}
public function Inicializar():void
{
crearNotaS(0xFF00FF, 30, 10, 0, 0);
}
public function Destruir():void
{
if (notaS[i].y < 720)
{
for (i = 0; i < notaS.length; i++)
{
stage.removeChild(notaS[i])
}
}
}
public function Mover():void
{
notaS[i].y += velocidad;
}
public function drawRect(color:uint, ancho:int, alto:int, x:int, y:int):Sprite
{
var dj:Sprite = new Sprite();
dj.graphics.beginFill(color, 1);
dj.graphics.drawRect(0, 0, ancho, alto);
dj.graphics.endFill();
dj.x = x;
dj.y = y;
return (dj);
}
public function asignarNotas():void
{
notaS[0] = 1
}
public function crearNotaS(color:int, ancho:int, alto:int, x:int, y:int):void
{
var contador:int = 0;
for (i = 0; i < notaS.length; i++)
{
if (notaS[i] == 1 && i == 0)
{
notaS[i] = drawRect(color, ancho, alto, x, y);
stage.addChild(notaS[i]);
notaS[i].y = -alto / 2;
}
else if (notaS[i] == 1 && i > 0)
{
for (j = i; j < notaS.length; j++)
{
contador = i - j
notaS[i] = drawRect(color, ancho, alto, x, notaS[j].y + alto * contador);
stage.addChild(notaS[i]);
return;
}
}
}
}
}
}
after all i have some suggestions:
seperate the array that contains control indexes and the one that contains sprites.
avoid making variables public. in your case there is no need for accessing them outside your class, but if you need to make them accessible, use getters/setters. google "getters/setters in as3".
invent some naming standards of your own. google "rules of naming in as3".

Moving b2body With Keyboard

I have this code that gives the b2Body an impulse towards the cursor when you click on stage.
private function clicked(e:MouseEvent):void
{
var impulse_x:Number = (mouseX / world_scale - mainChar.GetPosition().x);
var impulse_y:Number = (mouseY / world_scale - mainChar.GetPosition().y);
var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}
I was trying to use keyboard right arrow key for movement and so in the update function I added the if key[Keyboard.RIGHT]:
private function update(e:Event):void {
world.Step (1 / 30, 10, 10);
if (key[Keyboard.RIGHT]) {
impulse_x = 3;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}
}
private function onKeyUp(e:KeyboardEvent):void
{
key[e.keyCode] = false;
}
private function onKeyDown(e:KeyboardEvent):void
{
key[e.keyCode] = true;
}
But the b2body goes to top left on the screen and stays there and doesn't move. I am changing the impulse value that then goes into the vector that is applied to the body.
Although it doesn't give me any errors.
EDIT: The whole code!
package
{
import Box2D.Collision.Shapes.b2PolygonShape;
import Box2D.Common.Math.b2Vec2;
import Box2D.Dynamics.b2Body;
import Box2D.Dynamics.b2BodyDef;
import Box2D.Dynamics.b2FixtureDef;
import Box2D.Dynamics.b2World;
import Box2D.Dynamics.Contacts.b2ContactEdge;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
public class Main extends Sprite
{
public var world:b2World = new b2World(new b2Vec2(0, 0), true);
public var world_scale:Number = 30;
public var mainChar:b2Body;
private var ground:b2Body;
public var keys:Array = [];
public var beingPressed:Boolean;
public var impulse_x:Number;
public var impulse_y:Number;
public var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
public function Main():void
{
createMainCharacter(stage.stageWidth / 2, stage.stageHeight / 2, 50, 100);
var th:uint = 10;
addEventListener(Event.ENTER_FRAME, update);
//stage.addEventListener(MouseEvent.CLICK, clicked);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
/**private function clicked(e:MouseEvent):void
{
var impulse_x:Number = (mouseX / world_scale - mainChar.GetPosition().x);
var impulse_y:Number = (mouseY / world_scale - mainChar.GetPosition().y);
var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}**/
private function update(e:Event):void
{
world.Step (1 / 30, 10, 10);
var temp:Sprite;
for (var body:b2Body = world.GetBodyList(); body != null; body = body.GetNext())
{
if (body.GetUserData())
{
temp = body.GetUserData() as Sprite;
temp.x = body.GetPosition().x * world_scale;
temp.y = body.GetPosition().y * world_scale;
temp.rotation = body.GetAngle() * (180 / Math.PI); // radians to degrees
}
}
if (keys[Keyboard.RIGHT])
{
impulse_x = 3;
impulse_y = 0;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
} else {
impulse_x = 0;
impulse_y = 0;
}
}
private function createMainCharacter(x:Number, y:Number, width:Number, height:Number):void
{
var mainCharSprite:Sprite = new Sprite();
mainCharSprite.graphics.beginFill(0x000000);
mainCharSprite.graphics.drawRect( -width / 2, -height / 2 , width, height);
mainCharSprite.graphics.endFill;
mainCharSprite.x = x;
mainCharSprite.y = y;
addChild(mainCharSprite);
var mainCharDef:b2BodyDef = new b2BodyDef();
mainCharDef.userData = mainCharSprite;
mainCharDef.type = b2Body.b2_dynamicBody;
mainCharDef.position.Set (x / world_scale, y / world_scale);
mainChar = world.CreateBody(mainCharDef);
var shape:b2PolygonShape = new b2PolygonShape();
shape.SetAsBox((width / 2) / world_scale, (height / 2) / world_scale);
var fixtureDef:b2FixtureDef = new b2FixtureDef();
fixtureDef.shape = shape;
fixtureDef.restitution = 0.1;
fixtureDef.friction = 0.1;
fixtureDef.density = 0.5;
mainChar.CreateFixture(fixtureDef);
}
private function onKeyUp(e:KeyboardEvent):void
{
keys[e.keyCode] = false;
}
private function onKeyDown(e:KeyboardEvent):void
{
keys[e.keyCode] = true;
}
}
}
Changing the values of impulse_x and impulse_y is not going to update the values used by the b2Vec2 impulse. In AS3 primitives are passed by value not by reference. If you want the b2Vec2 object referenced by the variable impulse to change its values you need to change them directly on the object itself:
impulse.x = 3.0;
impulse.y = 0.0;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());

Actionscript 3.0 - MouseEvents not working

I'm trying to code a sort of strategy game through FlashDevelop and I'm getting problems when trying to use Events (particularly MouseEvents). It's not so much that the events are returning errors, it's just that they don't do anything, not even getting a trace.
I'm trying to make the hexagons HexObject image invisible when clicked on (just a simple test to see if the MouseEvent is actually working).
This is my code:
Main.as
package {
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* ...
* #author Dean Sinclair
*/
public class Main extends Sprite {
public var gameInitialised:Boolean = false;
public var MIN_X:int = 0;
public var MAX_X:int = stage.stageWidth;
public var MIN_Y:int = 0;
public var MAX_Y:int = stage.stageHeight - 100;
public var GameGrid:HexGrid = new HexGrid(MIN_X, MAX_X, MIN_Y, MAX_Y);
public var blackBG:Shape = new Shape();
public function Main():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
addEventListener(Event.ENTER_FRAME, update);
// entry point
}
private function update(event:Event):void {
if (gameInitialised == false) {
GameGrid.initialiseGrid();
initialiseBackground();
gameInitialised = true;
}
updateGraphics();
}
public function drawGrid():void {
for (var x:int = 0; x < GameGrid.TOTAL_X; x++) {
for (var y:int = GameGrid.yArray[x][0]; y < GameGrid.yArray[x][1]; y++) {
if (x != GameGrid.nox || y != GameGrid.noy) {
GameGrid.Grid[x][y].update();
this.stage.addChild(GameGrid.Grid[x][y].image);
}
}
}
}
public function updateGraphics():void {
this.stage.addChild(blackBG);
drawGrid();
}
public function initialiseBackground():void {
blackBG.graphics.beginFill(0x000000, 1);
blackBG.graphics.lineStyle(10, 0xffffff, 1);
blackBG.graphics.drawRect(0, 0, stage.stageWidth-1, stage.stageHeight-1);
blackBG.graphics.endFill();
}
}
}
HexGrid.as
package {
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* #author Dean Sinclair
*/
public class HexGrid extends Sprite {
public static var HEX_RADIUS:int = 0;
public static var HEX_DIAMETER:int = 0;
public static var GRID_WIDTH:int = 0;
public static var GRID_HEIGHT:int = 0;
public var TOTAL_X:int = 0;
public var MIN_X:int = 0;
public var MAX_X:int = 0;
public var MIN_Y:int = 0;
public var MAX_Y:int = 0;
public var Grid:Array;
public var yArray:Array;
public function HexGrid(min_x:int, max_x:int, min_y:int, max_y:int) {
super();
MIN_X = min_x;
MAX_X = max_x;
MIN_Y = min_y;
MAX_Y = max_y;
}
public function initialiseGrid():void {
setGridDetails();
setLineLengths();
setGridPositions();
}
public function setGridDetails():void {
HEX_RADIUS = 25;
HEX_DIAMETER = 2 * HEX_RADIUS;
GRID_WIDTH = (((MAX_X - MIN_X) / HEX_DIAMETER) - 1);
GRID_HEIGHT = ((((MAX_Y - 100) - MIN_Y) / (HEX_DIAMETER - (HEX_DIAMETER / 3))) - 3);
TOTAL_X = GRID_WIDTH + Math.floor((GRID_HEIGHT - 1) / 2);
}
private function setLineLengths():void {
yArray = new Array(TOTAL_X);
for (var a:int = 0; a < TOTAL_X; a++) {
yArray[a] = new Array(2);
}
for (var x:int = 0; x < TOTAL_X; x++) {
if (x < GRID_WIDTH) {
yArray[x][0] = 0;
}else {
yArray[x][0] = (x - GRID_WIDTH + 1) * 2;
}
yArray[x][1] = 1 + (2 * x);
if (yArray[x][1] > GRID_HEIGHT) {
yArray[x][1] = GRID_HEIGHT;
}
trace("Line", x, " starts at", yArray[x][0], " ends at", yArray[x][1]);
}
}
public var nox:int = 5;
public var noy:int = 3;
private function setGridPositions():void {
var hexState:int = 4;
Grid = new Array(TOTAL_X);
for (var x:int = 0; x < TOTAL_X; x++) {
Grid[x] = new Array(yArray[x][1]);
for (var y:int = yArray[x][0]; y < yArray[x][1]; y++) {
if(nox!=4 || noy!=6){
Grid[x][y] = new HexObject(HEX_DIAMETER + (HEX_DIAMETER * x) - (HEX_RADIUS * y), HEX_DIAMETER + (HEX_DIAMETER * y) - ((HEX_DIAMETER / 3) * y), HEX_RADIUS, 2);
}
}
}
}
}
}
HexObject.as
package {
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* ...
* #author Dean Sinclair
*/
public class HexObject extends Sprite {
[Embed(source = "../images/hexagons/hex_darkRed.png")]
private var DarkRedHex:Class;
[Embed(source = "../images/hexagons/hex_lightBlue.png")]
private var LightBlueHex:Class;
[Embed(source = "../images/hexagons/hex_midGreen.png")]
private var MidGreenHex:Class;
public var image:Bitmap = new LightBlueHex();
protected var state:int = 0;
private var radius:int = 0;
public function HexObject(xPos:int, yPos:int, hexRadius:int, hexState:int) {
super();
x = xPos;
y = yPos;
state = hexState;
radius = hexRadius;
checkState();
initialiseGraphics();
}
private function checkState():void {
switch(state) {
case 1: // plains
image = new MidGreenHex();
break;
case 2: // hills
break;
case 3: // rock
image = new DarkRedHex();
break;
case 4: // water
image = new LightBlueHex();
break;
default:
break;
}
}
private function initialiseGraphics():void {
image.visible = true;
image.width = radius * 2;
image.height = radius * 2;
image.x = x - radius;
image.y = y - radius;
}
private function onMouseClick(e:MouseEvent):void {
image.visible = false;
trace("image.visible =", image.visible);
}
public function update():void {
image.addEventListener(MouseEvent.CLICK, onMouseClick);
}
}
}
I've tried countless methods to get the events working, but none have had any success. Any sort of solution to this would be a lifesaver as I've been toiling over this for hours, thanks!
My problem was fixed by VBCPP, I was using the class Bitmap which cannot dispatch MouseEvents. The solution was to take image from HexObject and put it inside an container of type Sprite, with the logical one being the object it was in. I just had to add the following code inside HexObject.as:
this.addChild(image);
and then just refer to the Object in future as opposed to image.

how to make Astar pathfinding can used by multi enemy?

i have learn A star pathfinding from "AdvancED_ActionScript_Animation" e-book:
List item
i make node class, Node.as .
i make grid class, Grid.as .
i make AStar class, AStar.as .
and the main clas, Game.as .
A-star Pathfinding is work, but just 1 player.
how to make it work in multi player?
spoiler
4.Game.as :
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
public class Game extends Sprite
{
private var _cellSize:int = 30;
private var _grid:Grid;
private var _player:Sprite;
private var _index:int;
private var _path:Array;
public function Game()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
makePlayer();
makeGrid();
stage.addEventListener(MouseEvent.CLICK, onGridClick);
}
private function makePlayer():void
{
_player =new Sprite();
_player.graphics.beginFill(0x336633);
_player.graphics.drawCircle(0,0,5);
_player.graphics.endFill();
_player.x = Math.random() * 100;
_player.y = Math.random() * 100;
addChild(_player);
}
private function makeGrid():void
{
_grid = new Grid(10,10);
for (var i:int =0; i < 10; i++)
{
_grid.setWalkable(Math.floor(Math.random()*10),
Math.floor(Math.random()*10),false);
}
drawGrid();
}
private function drawGrid():void
{
graphics.clear();
for (var i:int =0; i < _grid.numCols; i++)
{
for (var j:int =0; j<_grid.numRows; j++)
{
var node:Node = _grid.getNode(i,j);
graphics.lineStyle(0);
graphics.beginFill(getColor(node));
graphics.drawRect(i *_cellSize,
j*_cellSize,_cellSize,
_cellSize);
}
}
}
private function getColor(node:Node):uint
{
if (! node.walkable)
{
return 0;
}
if (node == _grid.startNode)
{
return 0xcccccc;
}
if (node == _grid.endNode)
{
return 0xcccccc;
}
return 0xffffff;
}
private function onGridClick(event:MouseEvent):void
{
var xpos:int =Math.floor(mouseX/_cellSize);
var ypos:int =Math.floor(mouseY/_cellSize);
_grid.setEndNode(xpos,ypos);
xpos = Math.floor(_player.x / _cellSize);
ypos = Math.floor(_player.y / _cellSize);
_grid.setStartNode(xpos,ypos);
drawGrid();
findPath();
}
private function findPath():void
{
var astar:AStar = new AStar();
if (astar.findPath(_grid))
{
_path = astar.path;
_index = 0;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
}
private function onEnterFrame(event:Event):void
{
var targetX:Number = _path[_index].x * _cellSize
+ _cellSize / 2;
var targetY:Number = _path[_index].y * _cellSize
+ _cellSize / 2;
var dx:Number = targetX - _player.x;
var dy:Number = targetY - _player.y;
var dx2:Number = targetX - _box.x;
var dy2:Number = targetY - _box.y;
var dist2:Number =Math.sqrt(dx2*dx2+dy2+dy2);
var dist:Number =Math.sqrt(dx*dx+dy+dy);
if (dist<1)
{
_index++;
if (_index >= _path.length)
{
removeEventListener(Event.ENTER_FRAME,onEnterFrame);
}
}
else
{
_player.x += dx * .5;
_player.y += dy * .5;
}
}
}
}
I am not going to go the extra mile and code this for you. (Anyone else can feel free to do that)
What you need to do is create a function that accepts a start node and end node, and returns the path. Something like this :
public function getPath(starNode:Point, endNode:Point):Array
{
// get your path by utilizing the astar instance
// return that path array
// note that I have used Points to store the x,y location
// you'll need to apply those values to the grid before your astar call
// using the setStarNode and setEndNode methods of the grid instance
}
Then you can modify the code that is used in your enterFrame, to utilize an array containing path data for any player/enemy you want.
For example you might have a function you call for each entity such as :
public function followPath(entity:MovieClip, pathData:Array, pathIndex:int):void
{
// your modified code from onEnterFrame
// replace _player variable with entity
// replace _path variable with pathData
// replace _index with pathIndex
}
If you understand OOP well enough, you might want to create a class for your player/enemy entities that has properties for pathData and pathIndex. If you do that, than you can just call an update method that will update their movement each frame using the pathData and pathIndex properties of that instance.
This is a basic approach you could use to accomplish your goal.

FLEX - BitmapImage not updated after filters assigned

I've a flex mobile project and a component (as-Class) inside of it with an BitmapImage, a Button and a Graphic sign.
When a boolean is false the button is disabled, the image gets gray through a ColorMatrixFilter (bitmapImage.filters = [myCMFilter]) and the sign appers, else button is enabled, the image has no filters (bitmapImage.filters = []).
The problem is that the image doesn't switch to grey -> but the sign appears and the button gets disabled.
If call the setting of the filters one frame later (callLater -> a function setting the filters) everything works.
I have extracted the code to a sample project and everything works... without callLater
Anyone an idea what can happpen in my case???
Christian
Code:
package de.xxx.yyy.app.view.componentsV2.widgets
{
import de.assets.header.HeaderBGDarkGray;
import de.assets.miscellaneous.StarGrey;
import de.assets.miscellaneous.StarYellow;
import de.assets.miscellaneous.UnderConstruction;
import de.assets.ImageAssets;
import de.xxx.yyy.app.view.componentsV2.buttons.BasicButton;
import de.xxx.yyy.app.view.pools.UserInterfaceComponentsPool;
import flash.debugger.enterDebugger;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.ColorMatrixFilter;
import mx.core.IVisualElement;
import mx.core.UIComponent;
import spark.components.Button;
import spark.components.Group;
import spark.core.SpriteVisualElement;
import spark.primitives.BitmapImage;
public class StadiumWidget extends Group{
private static var STADION_LEVELS:int = 7;
private static var SIDE_SPACING:int = 7;
private static var BUTTON_WIDTH:int = 150;
private static var BUTTON_HEIGHT:int = 33;
////////////////////////////////////////////////////////////////////////////
// USER INTERFACE COMPONENTS
////////////////////////////////////////////////////////////////////////////
private var underConstructionImage:UnderConstruction;
private var currentImage:BitmapImage;
private var footerBackground:HeaderBGDarkGray;
private var developButton:BasicButton;
private var manageButton:BasicButton;
private var displayedlevel:int;
////////////////////////////////////////////////////////////////////////////
// FIELDS
////////////////////////////////////////////////////////////////////////////
private var createdStars:Array = [];
////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////
private var _grayscaleFilter:ColorMatrixFilter;
public function get grayscaleFilter():ColorMatrixFilter
{
if(!_grayscaleFilter)
{
var matrix:Array = [0.3, 0.59, 0.11, 0, 0,
0.3, 0.59, 0.11, 0, 0,
0.3, 0.59, 0.11, 0, 0,
0, 0, 0, 1, 0];
_grayscaleFilter = new ColorMatrixFilter(matrix);
}
return _grayscaleFilter;
}
public function set grayscaleFilter(value:ColorMatrixFilter):void
{
_grayscaleFilter = value;
}
////////////////////////////////////////////////////////////////////////////
// GETTER AND SETTER WITH DIRTY FLAG
////////////////////////////////////////////////////////////////////////////
private var levelChanged:Boolean;
private var _level:int;
public function set level(value:int):void
{
_level = value;
levelChanged = true;
invalidateProperties();
invalidateDisplayList()
}
public function get level():int
{
return _level;
}
//
private var isUnderConstructionChanged:Boolean;
private var _isUnderConstruction:Boolean;
public function set isUnderConstruction(value:Boolean):void
{
_isUnderConstruction = value;
isUnderConstructionChanged = true;
invalidateProperties();
invalidateDisplayList()
}
public function get isUnderConstruction():Boolean
{
return _isUnderConstruction;
}
////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////
public function Stadium()
{
super();
}
////////////////////////////////////////////////////////////////////////////
// LIFECYCLE STANDARD METHODS
////////////////////////////////////////////////////////////////////////////
var testSprite:UIComponent;
override protected function createChildren():void
{
super.createChildren();
currentImage = new BitmapImage();
currentImage.smooth = true;
currentImage.percentWidth = 100;
currentImage.scaleMode = "letterbox";
addElement(currentImage);
// FOOTER
footerBackground = new HeaderBGDarkGray();
addElement(footerBackground);
developButton = new BasicButton();
developButton.width = BUTTON_WIDTH;
developButton.height = 38;
developButton.x = SIDE_SPACING;
developButton.label = resourceManager.getString("FlexApp", "stadium.developButtonLabel");
developButton.addEventListener(MouseEvent.CLICK, handleDevelopButtonClicked);
addElement(developButton);
manageButton = new BasicButton();
manageButton.width = BUTTON_WIDTH;
manageButton.height = 38;
manageButton.label = resourceManager.getString("FlexApp", "stadium.manageButtonLabel");
manageButton.addEventListener(MouseEvent.CLICK, handleManageButtonClicked);
addElement(manageButton);
}
override protected function commitProperties():void
{
super.commitProperties();
if(currentImage && levelChanged)
{
setcurrentImage();
setStars();
levelChanged = false;
}
if(isUnderConstructionChanged)
{
setUnderConstruction();
isUnderConstructionChanged = false;
}
}
override protected function measure():void
{
super.measure();
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
var FOOTER_HEIGHT:int = footerBackground.getPreferredBoundsHeight();
var STAR_X_STEP:int = 25;
footerBackground.y = unscaledHeight - FOOTER_HEIGHT;
footerBackground.width = unscaledWidth;
manageButton.x = unscaledWidth - (BUTTON_WIDTH + SIDE_SPACING);
manageButton.y = developButton.y = footerBackground.y + ((FOOTER_HEIGHT - BUTTON_HEIGHT) / 2);
if(currentImage.height > unscaledHeight - footerBackground.height)
{
currentImage.height = unscaledHeight - footerBackground.height;
}
if(underConstructionImage)
{
underConstructionImage.x = (unscaledWidth - underConstructionImage.width) / 2;
}
var starStartX:int = unscaledWidth / 2 - (STADION_LEVELS * STAR_X_STEP) / 2;
var starY:int = createdStars.length > 0 ? unscaledHeight - FOOTER_HEIGHT + (FOOTER_HEIGHT - createdStars[0].height) / 2 : 0;
for(var i:int = 0; i < createdStars.length; i++)
{
createdStars[i].y = starY;
createdStars[i].x = starStartX + i * STAR_X_STEP;
}
}
////////////////////////////////////////////////////////////////////////////
// HELPER METHODS
////////////////////////////////////////////////////////////////////////////
private function setStars():void
{
var pool:UserInterfaceComponentsPool = UserInterfaceComponentsPool.getInstance();
var star:IVisualElement;
while(createdStars.length > 0)
{
star = createdStars.pop() as IVisualElement;
if(containsElement(star))
{
removeElement(star);
}
pool.disposeUserInterfaceComponent(star);
}
// POOL THE STARS!!!
for(var i:int = 1; i <= STADION_LEVELS; i++)
{
if(i <= level)
{
star = pool.getYellowStar();
}
else
{
star = pool.getGreyStar();
}
addElement(star)
createdStars.push(star);
}
}
private function setcurrentImage():void
{
if(level != displayedlevel)
{
currentImage.source = currentImages["LEVEL_" + level + "_NAME"];
displayedlevel = level;
}
setUnderConstruction();
}
private function setUnderConstruction():void
{
developButton.enabled = isUnderConstruction == false;
if(isUnderConstruction)
{
if(!underConstructionImage)
{
underConstructionImage = new UnderConstruction();
underConstructionImage.y = 30;
underConstructionImage.width = 330;
underConstructionImage.height = 330;
addElement(underConstructionImage);
}
callLater(setFilters, [true]);
}
else
{
callLater(setFilters, [false]);
if(underConstructionImage && containsElement(underConstructionImage))
{
removeElement(underConstructionImage);
}
underConstructionImage = null;
}
}
private function setFilters(value:Boolean):void
{
if(value && (!currentImage.filters || currentImage.filters.length == 0))
{
currentImage.filters = [grayscaleFilter];
}
else if(!value && currentImage.filters && currentImage.filters.length > 0)
{
currentImage.filters = [];
}
}
////////////////////////////////////////////////////////////////////////////
// EVENT HANDLER
////////////////////////////////////////////////////////////////////////////
private function handleDevelopButtonClicked(event:MouseEvent):void
{
dispatchEvent(new Event("openlevelPopup", true));
}
private function handleManageButtonClicked(event:MouseEvent):void
{
dispatchEvent(new Event("openManagePopup", true));
}
////////////////////////////////////////////////////////////////////////////
// DISPOSE
////////////////////////////////////////////////////////////////////////////
public function dispose():void
{
developButton.removeEventListener(MouseEvent.CLICK, handleDevelopButtonClicked);
manageButton.removeEventListener(MouseEvent.CLICK, handleManageButtonClicked);
}
}
}