How to run another instance of Main() in AS3 - ios

How would you run a new instance of your Main function in AS3? Basically I want the program to rerun itself from the start, once it reaches the end of the program. I thought about removing all my childs from the tree at the end, then running the first method again, but that just seems unnecessary and messy. The class extends Sprite.
EDIT: Trying to create a Custom Event and using dispatchEvent to trigger this at the end of the program but having a little problem. This is my current code below.
Entire RunMain.as:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class RunMain extends Sprite {
public function RunMain():void {
addEventListener(Event.ENTER_FRAME, loop);
}
private function loop(event:Event){
removeEventListener(Event.ENTER_FRAME, loop);
dispatchEvent(new EndEvent(EndEvent.END_EVENT));
}
}
}
Entire EndEvent.as:
package
{
import flash.events.Event;
public class EndEvent extends Event
{
// Event types.
public static const END_EVENT:String = "event1";
public function EndEvent(type:String = EndEvent.END_EVENT)
{
super(type);
}
override public function clone():Event {
// Return a new instance of this event with the same parameters.
return new EndEvent(type);
}
}
}
Parts of Main.as:
public function Main() {
runMain = new RunMain();
runMain.addEventListener(EndEvent.END_EVENT, onProgramFinish);
addChild(runMain);
init();
otherMethods();
}
public function onProgramFinish() {
removeChild(runMain);
runMain = null;
runMain = new RunMain() ;
}
Inside my Main class, I have the line onProgramFinish(); at the end of the program.
At the moment, when I run the compiler it comes up with the error:
ArgumentError: Error #1063: Argument count mismatch on Main/onProgramFinish().
Expected 0, got 1.
When I choose to continue, the program runs fine, but it doesn't run a new instance at the end of it.

In fact you must create a special class container and swap him (create new or delete) exactly in main class. This game class can dispatch events, at least sprites can dispatch events. Creating your custom events and passing them to higher and higher level will allow you to perform actions in Main class.
class Main extends Sprite {
public var game:Game ;
public function Main():void {
game = new Game(new Player(), "asd") ;
game.addEventListener(GameEvent.GAME_OVER, onGameOver) ;
addChild(game) ;
}
public function onGameOver(){
removeChild(game) ;
//also you can try removing heavy children of game
game = null ; //Let garbage collector know about object without reference.
game = new Game(new Player(), "example") ;
}
}
public class Game extends Sprite {
public var hero:Hero = new Hero() ;
public function Game(player:Player, name:String):void {
addEventListener(Event.ENTER_FRAME, loop) ;
}
private function loop(event:Event){
if (hero.hp == 0){
removeEventListener(Event.ENTER_FRAME, loop) ;
dispatchEvent(new GameEvent(GameEvent.GAME_OVER)) ;
}
}
}

Your event:
package {
import flash.events.Event;
public class ProgramEvent extends Event
{
public static const FINISH:String = "Finished" ;
public function ProgramEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
public override function clone():Event
{
return new ProgramEvent(type, bubbles, cancelable);
}
public override function toString():String
{
return formatToString("ProgramEvent", "type", "bubbles", "cancelable", "eventPhase");
}
}
}
RunMain:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class RunMain extends Sprite {
public function RunMain():void {
addEventListener(Event.ENTER_FRAME, loop);
}
private function loop(event:Event){
removeEventListener(Event.ENTER_FRAME, loop);
dispatchEvent(new ProgramEvent(ProgramEvent.FINISH));
}
}
}
And Main:
public function Main() {
startProgram() ;
init();
otherMethods();
}
public function onProgramFinish(event:ProgramEvent) {
runMain.removeEventListener(ProgramEvent.FINISH, onProgramFinish) ;
removeChild(runMain);
runMain = null;
startProgram() ;
}
public function startProgram(){
runMain = new RunMain() ;
runMain.addEventListener(ProgramEvent.FINISH, onProgramFinish);
addChild(runMain);
}

Related

connecting vertices in jung by edges results in another extra vertex being created

I am implementing an interface for taking commands for creating , connecting and coloring vertices in JUNG when I want to connect two already existing vertices JUNG connects to vertices and creates an extra vertex , why?
Here is my code for connect method:
public class Connect extends Command {
private CommandMaster cm;
private BehGraphUndirected behGraph;
private static int edgenumber=0;
#Override
public Object run(BehGraphUndirected behGraph, VisualizationImageServer panel, InterpretMaster interpretMaster, String... args) {
System.out.print("connect Runs\n");
this.cm = new CommandMaster();
this.behGraph = behGraph;
if(cm.exists(args[0]))
{
//got to another command
}else
{
switch (args[0]) {
case "edge":
this.createEdge(args[1] , args[2]);
break;
}
}
interpretMaster.refreshAndRepaint();
return null;
}
public void createEdge(String nodeName1 , String nodeName2)
{
this.behGraph.addEdge(edgenumber++,nodeName1, nodeName2);
System.out.println(this.behGraph.getVertexCount());
System.out.println("edge between: "+nodeName1+" and "+ nodeName2+" added");
}
And it's the create method just in case you want to know the way I implemented the code:
package interpreter.command;
import GraphHandling.BehGraphUndirected;
import edu.uci.ics.jung.visualization.VisualizationImageServer;
import interpreter.Command;
import interpreter.CommandMaster;
import interpreter.InterpretMaster;
/**
*
* #author Administrator
*/
public class Create extends Command{
private CommandMaster cm;
private BehGraphUndirected behGraph;
#Override
public Object run(BehGraphUndirected behGraph, VisualizationImageServer panel, InterpretMaster interpretMaster, String... args) {
System.out.print("create Runs \n");
this.cm = new CommandMaster();
this.behGraph = behGraph;
if(cm.exists(args[0]))
{
//got to another command
}else
{
switch (args[0]) {
case "node":
this.createNode(args[1]);
break;
case "label":
this.createLabel(args[1]);
break;
}
}
interpretMaster.refreshAndRepaint();
return null;
}
public void createNode(String nodeName)
{
this.behGraph.addVertex(nodeName);
System.out.print("vertex: "+nodeName+" added");
}
private void createLabel(String string) {
}
class str
{
int i;
long j;
}
}
Graph images before and after connecting two nodes:
and Here is my BehGraphUndirected class:
package GraphHandling;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import java.util.LinkedList;
/**
*
* #author Administrator
*/
public class BehGraphUndirected extends UndirectedSparseGraph{
private final LinkedList<Node> nodeList;
public BehGraphUndirected()
{
this.nodeList = new LinkedList<>();
}
public void addNode(Node newNode)
{
this.nodeList.add(newNode);
}
}
You should look at what BehGraphUndirected is doing; it's not a JUNG class or interface.
What is the name of the vertex that's being created, and how does that relate to what's being passed to the create method?
I have compiled and tested your code , The Jung library seems working right and It extinguishes the different nodes by the different object that was given to it It seems you have some other problem , Like a problem in processing the input strings that are used as objects that create nodes.

Override method in dart on fly (like JAVA)

Is there way to overriding method in Dart like JAVA, for example:
public class A {
public void handleLoad() {
}
}
And when overriding:
A a = new A() {
#Override
public void handleLoad() {
// do some code
}
};
No, Dart does not have anonymous classes. You have to create a class that extends A and instantiate it.
No but it much less useful in Dart because you can just reassign function:
typedef void PrintMsg(msg);
class Printer {
PrintMsg foo = (m) => print(m);
}
main() {
Printer p = new Printer()
..foo('Hello') // Hello
..foo = ((String msg) => print(msg.toUpperCase()))
..foo('Hello'); //HELLO
}
However you will need some extra boilerplate to access instance.
Use type Function:
class A {
final Function h
A(this.h);
void handleLoad(String loadResult) { h(loadResult); }
}
Or
class A {
final Function handleLoad;
A(this.handleLoad);
}
A a = new A((String loadResult){
//do smth.
});

1067: Implicit Coercion of a value

So I'm currently trying to run my collision test on my two sprites, and I'm getting the following error:
C:\\Code\\Game\Game.as, Line 54, Column 34 1067: Implicit coercion of a value of type mvc:PlayerModel to an unrelated type assets.Scripts:SpriteAnimation.
Which is pointing to the following line of code:
handleSpriteToSpriteCollision(_player, _boss);
The function is as follows:
private function handleSpriteToSpriteCollision(sprite1:SpriteAnimation, sprite2:SpriteAnimation):void
{
var toSprite2 : VectorModel = new
VectorModel(0,0,0,0, sprite2.x - sprite1.x, sprite2.y - sprite1.y);
var bitmapData1:BitmapData = new BitmapData(sprite1.width, sprite1.height);
while(testBitmapCollision(sprite1.spriteFrameBitmapData, sprite1.topLeftX, sprite1.topLeftY, sprite2.spriteFrameBitmapData, sprite2.topLeftX, sprite2.topLeftY))
{
sprite2.x -= toSprite2.dx;
sprite2.y -= toSprite2.dy;
}
}
Both sprites display just fine, but as soon as I make the function call it all comes crumbling down. At this point I just need some fresh eyes to take a look at the code to see what's going wrong.
Edit: Here is the PlayerModel.as
package mvc
{
import flash.events.Event;
import flash.events.EventDispatcher;
import assets.Scripts.SpriteAnimation;
public class PlayerModel extends EventDispatcher
{
private var _previousX:Number = 0;
private var _previousY:Number = 0;
private var _xPos:Number = 0;
private var _yPos:Number = 0;
public var vx:Number = 0;
public var vy:Number = 0;
private var _height:uint = 30;
private var _width:uint;
private var _color:uint;
public function PlayerModel():void
{
}
public function update():void
{
xPos += vx;
yPos += vy;
}
public function get height():uint
{
return _height;
}
public function get color():uint
{
return _color;
}
public function get xPos():Number
{
return _xPos;
}
public function set xPos(value:Number):void
{
_xPos = value;
dispatchEvent(new Event(Event.CHANGE));
}
public function get yPos():Number
{
return _yPos;
}
public function set yPos(value:Number):void
{
_yPos = value;
dispatchEvent(new Event(Event.CHANGE));
}
public function set setX(value:Number):void
{
_previousX = value - vx;
xPos = value;
}
public function set setY(value:Number):void
{
_previousY = value - vy;
yPos = value;
}
}
}
The first thing i would check is the class of your boss and player objects inherit your SpriteAnimation class:
class PlayerModel extends SpriteAnimation
{ ...
Seems as though your handleSpriteToSpriteCollision function is looking for two SpriteAnimations and at least the PlayerModel being passed isn't one
Sprite inherits EventDispatcher so as long as your SpriteAnimation inherits Sprite as well, you shouldn't lose any functionality

removeChild used incorrectly?

I'm just trying to remove a movie clip from the stage upon double clicking
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import fl.motion.MotionEvent;
public class Main extends MovieClip{
var thingeh:Things;
public function Main() {
thingeh = new Things;
stage.addEventListener(MouseEvent.CLICK, onClick);
stage.addEventListener(MouseEvent.DOUBLE_CLICK, onDouble);
}
public function onClick(event:MouseEvent)
{
addChild(thingeh);
}
public function onDouble(event:MouseEvent)
{
if(thingeh)
removeChild(thingeh);
}
}
}
public function onDouble(event:MouseEvent)
{
if( thingeh && contains(thingeh) )
{
removeChild(thingeh);
}
}
Also, You may want doubleClickEnabled = true within your constructor.
Do note, MouseEvent.CLICK gets fired TWICE along with a MouseEvent.DOUBLE_CLICK event.

BlackBerry - Get current Process ID

I read Blackberry - How to get the background application process id but I'm not sure I understand it correctly. The following code gets the foreground process id;
ApplicationManager.getApplicationManager().getForegroundProcessId()
I have two processes which execute the same piece of code to make a connection, I want to log the process which made the calls along with all my usual logging data to get a better idea of how the flow is working.
Is it possible to get the id for the process which is currently running the code? One process is in the foreground (UI process) and the other is in the background but both use the same connection library shared via the runtime store.
Thanks in advance!
Gav
So you have three modules: application, library and service.
You need to get descriptor by module name, and then get process id.
UPDATE1
String moduleName = "application";
int handle = CodeModuleManager.getModuleHandle(moduleName);
ApplicationDescriptor[] descriptors = CodeModuleManager
.getApplicationDescriptors(handle);
if (descriptors.length > 0 && descriptors[0] != null) {
ApplicationManager.getApplicationManager().getProcessId(descriptors[0]);
}
Then, to log which module uses library, use
Application.getApplication().getProcessId();
inside library methods. I think its better to implement logging inside library.
When you got process id of application from library code, you can compare it with id's found by module name and then you will know what module uses library code.
UPDATE2
alt text http://img138.imageshack.us/img138/23/eventlog.jpg
library module code:
package library;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.system.CodeModuleManager;
import net.rim.device.api.system.EventLogger;
public class Logger {
// "AppLibSrvc" converted to long
long guid = 0xd4b6b5eeea339daL;
public Logger() {
EventLogger.register(guid, "AppLibSrvc", EventLogger.VIEWER_STRING);
}
public void log(String message) {
EventLogger.logEvent(guid, message.getBytes());
}
public void call() {
log("Library is used by " + getModuleName());
}
private String getModuleName() {
String moduleName = "";
String appModuleName = "application";
int appProcessId = getProcessIdByName(appModuleName);
String srvcModuleName = "service";
int srvcProcessId = getProcessIdByName(srvcModuleName);
int processId = Application.getApplication().getProcessId();
if (appProcessId == processId)
moduleName = appModuleName;
else if (srvcProcessId == processId)
moduleName = srvcModuleName;
return moduleName;
}
protected int getProcessIdByName(String moduleName) {
int processId = -1;
int handle = CodeModuleManager.getModuleHandle(moduleName);
ApplicationDescriptor[] descriptors = CodeModuleManager
.getApplicationDescriptors(handle);
if (descriptors.length > 0 && descriptors[0] != null) {
processId = ApplicationManager.getApplicationManager()
.getProcessId(descriptors[0]);
}
return processId;
}
}
application module code:
package application;
import java.util.Timer;
import java.util.TimerTask;
import library.Logger;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.MainScreen;
public class App extends UiApplication {
public App() {
pushScreen(new Scr());
}
public static void main(String[] args) {
App app = new App();
app.enterEventDispatcher();
}
}
class Scr extends MainScreen {
public Scr() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
Logger logger = new Logger();
logger.call();
}
};
timer.schedule(task, 3000, 3000);
}
}
service module code:
package service;
import java.util.Timer;
import java.util.TimerTask;
import library.Logger;
import net.rim.device.api.system.Application;
public class App extends Application {
public App() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
Logger logger = new Logger();
logger.call();
}
};
timer.schedule(task, 3000, 3000);
}
public static void main(String[] args) {
App app = new App();
app.enterEventDispatcher();
}
}

Resources