AS3 OOP Game Development Structure - actionscript-3

I'm wondering what is the best practise for gamedevelopment for actioncript 3.
I'm currently in the progress of creating a tile-based game, but I'm already having some troubles using seperate classes.
This is the current situation:
Main class
Generates the tiles
Adds player class
Adds interface class
The interface class contains all interface elements. For example, there is an option to spawn an object into the game. This object could be placed on a selected tile.
Now the problem is a followed: The spawned object is placed within the interface class, how should the spawned object be able to communicate with the tiles?
This same problem arises with several other parts in the game. Like how should the player be able to interact with the spawned object? Everything is in different classes making the communcation between all these things so difficult.
Is there any standard procedure regarding game development which handles this problem?I was thinking of making a "world" class where every object should be placed somehow. But it's hard for me to actually make this with the little knowledge of this sort of structure that I posess.
This is all sort of new to me, so I would appreciate it if the explanation would be as noob proof as possible.
Thanks in advance!

You can use event dispatching for your objects to communicate with one another, there are several approaches available, one of the simpler approach would be for you to create a controller class whose sole responsibility would be to dispatch & listen to events, in order to inform the relevant classes of what's occurring within your game
A better approach could be to use a framework such as Robotlegs, the learning curve is a bit steeper but worth the extra effort.
http://www.robotlegs.org/
You should easily find examples & tutorials for Robotlegs.

Try to imagine the organization of the parts of your game in a slightly different way. In the first place this World class you mention could contain both the Map object also contain the Unit objects for the spawned player or creatures. The Map object which also contains Tile objects which each one have its own information as terrain and attributes. Also the Unit objects would contain the information related to each spawn. For the interaction with your player you could have a Game object that contains both the World and a representation of your player, namely a Player object, and this Game object would communicate the instructions from the player towards the World as to make things happen. As you can see each object contains other objects of finer detail, the World contains the Map that contains the Tile's, this way the higher object uses the lower finer objects and makes them all communicate between them.
This could be a good approach to start something quickly or to learn while you experiment. More complex situation require other ways of arranging all the information of the game like the Model-View-Controller structure, but you probably should not worry to much about it until you have learned enough as to know you need a better solution.

I would suggest to read a little about design patterns. A singleton Dispatcher class can help in your case, you just bind everything to it and send events from one entity to another.
The reason why not use the built-in events is that you would need your objects to be on the display list.

Related

Share Data between Systems in ECS (Ashley)

I'm currently restructuring my LibGDX-Projekt to fit an ECS-Structure using Ashley.
At the moment I have the following System-Structure:
InputSystem (handles Player-Input)
PhysicSystem (applies velocity to entities, does collisiondetection and moves them)
CameraSystem (adjusts the camera to the camera-focus)
RenderingSystem (transforms the SpriteBatch with the camera-information and draws all entities)
Now I know that each System is supposed to contains all the logic it needs and is encapsuled to reduce complixity.
But I need the camera in the CameraSystem to adjust it, I need it in the RenderSystem to apply the camera-transformation and I need it in the InputSystem to see where the mouse is pointing at. How do you solve this with the ECS-Approach? Can Systems communicate with one another? Should I just use a Singleton called "SharedData" where I dump all the stuff that multiple systems need? Seems a little ugly to me.
Thanks in advance :)
Yes, using a singleton would defeat the purpose of using an ECS in the first place. In an ECS, the approach used is that all shared data is expressed using entities. It is perfectly fine to have an Entity type for which there will only be once instance of it during the lifetime of the game.
These could then be accessed directly from the Engine when the EntiySystem is added to it. An alternative approach could be to pass commonly accessed entities to the constructor of the systems if it is frequently accessed, in the past I have used this for passing a Box2D World entity.
I believe my code does a better job of explaining my reasoning so you can have a look at one of my previous games using Ashley. https://github.com/basimkhajwal/LSD
P.S - My project also includes an event queue for messaging between different entity systems (without passing data, all the data is still encapsulated in Entity classes) which I found to be extremely useful.

What's the reason for interface to exist in Actionscript-3 and other languages

what is the meaning of this interfaces? even if we implement an interface on a class, we have to declare it's functionality again and again each time we implement it on a different class, so what is the reason of interfaces exist on as3 or any other languages which has interface.
Thank you
I basically agree with the answers posted so far, just had a bit to add.
First to answer the easy part, yes other languages have interfaces. Java comes to mind immediately but I'm pretty sure all OOP languages (C++, C#, etc.) include some mechanism for creating interfaces.
As stated by Jake, you can write interfaces as "contracts" for what will be fulfilled in order to separate work. To take a hypothetical say I'm working on A and you're working on C, and bob is working on B. If we define B' as an interface for B, we can quickly and relatively easily define B' (relative to defining B, the implementation), and all go on our way. I can assume that from A I can code to B', you can assume from C you can code to B', and when bob gets done with B we can just plug it in.
This comes to Jugg1es point. The ability to swap out a whole functional piece is made easier by "dependency injection" (if you don't know this phrase, please google it). This is the exact thing described, you create an interface that defines generally what something will do, say a database connector. For all database connectors, you want it to be able to connect to database, and run queries, so you might define an interface that says the classes must have a "connect()" method and a "doQuery(stringQuery)." Now lets say Bob writes the implementation for MySQL databases, now your client says well we just paid 200,000 for new servers and they'll run Microsoft SQL so to take advantage of that with your software all you'd need to do is swap out the database connector.
In real life, I have a friend who runs a meat packing/distribution company in Chicago. The company that makes their software/hardware setup for scanning packages and weighing things as they come in and out (inventory) is telling them they have to upgrade to a newer OS/Server and newer hardware to keep with the software. The software is not written in a modular way that allows them to maintain backwards compatibility. I've been in this boat before plenty of times, telling someone xyz needs to be upgraded to get abc functionality that will make doing my job 90% easier. Anyhow guess point being in the real world people don't always make use of these things and it can bite you in the ass.
Interfaces are vital to OOP, particularly when developing large applications. One example is if you needed a data layer that returns data on, say, Users. What if you eventually change how the data is obtained, say you started with XML web services data, but then switched to a flat file or something. If you created an interface for your data layer, you could create another class that implements it and make all the changes to the data layer without ever having to change the code in your application layer. I don't know if you're using Flex or Flash, but when using Flex, interfaces are very useful.
Interfaces are a way of defining functionality of a class. it might not make a whole lot of sense when you are working alone (especially starting out), but when you start working in a team it helps people understand how your code works and how to use the classes you wrote (while keeping your code encapsulated). That's the best way to think of them at an intermediate level in my opinion.
While the existing answers are pretty good, I think they miss the chief advantage of using Interfaces in ActionScript, which is that you can avoid compiling the implementation of that Interface into the Main Document Class.
For example, if you have an ISpaceShip Interface, you now have a choice to do several things to populate a variable typed to that Interface. You could load an external swf whose main Document Class implements ISpaceShip. Once the Loader's contentLoaderInfo's COMPLETE event fires, you cast the contentto ISpaceShip, and the implementation of that (whatever it is) is never compiled into your loading swf. This allows you to put real content in front of your users while the load process happens.
By the same token, you could have a timeline instance declared in the parent AS Class of type ISpaceShip with "Export for Actionscript in Frame N *un*checked. This will compile on the frame where it is first used, so you no longer need to account for this in your preloading time. Do this with enough things and suddenly you don't even need a preloader.
Another advantage of coding to Interfaces is if you're doing unit tests on your code, which you should unless your code is completely trivial. This enables you to make sure that the code is succeeding or failing on its own merits, not based on the merits of the collaborator, or where the collaborator isn't appropriate for a test. For example, if you have a controller that is designed to control a specific type of View, you're not going to want to instantiate the full view for the test, but only the functionality that makes a difference for the test.
If you don't have support in your work situation for writing tests, coding to interfaces helps make sure that your code will be testable once you get to the point where you can write tests.
The above answers are all very good, the only thing I'd add - and it might not be immediately clear in a language like AS3, where there are several untyped collection classes (Array, Object and Dictionary) and Object/dynamic classes - is that it's a means of grouping otherwise disparate objects by type.
A quick example:
Image you had a space shooter, where the player has missiles which lock-on to various targets. Suppose, for this purpose, you wanted any type of object which could be locked onto to have internal functions for registering this (aka an interface):
function lockOn():void;//Tells the object something's locked onto it
function getLockData():Object;//Returns information, position, heat, whatever etc
These targets could be anything, a series of totally unrelated classes - enemy, friend, powerup, health.
One solution would be to have them all to inherit from a base class which contained these methods - but Enemies and Health Pickups wouldn't logically share a common ancestor (and if you find yourself making bizarre inheritance chains to accomodate your needs then you should rethink your design!), and your missile will also need a reference to the object its locked onto:
var myTarget:Enemy;//This isn't going to work for the Powerup class!
or
var myTarget:Powerup;//This isn't going to work for the Enemy class!
...but if all lockable classes implement the ILockable interface, you can set this as the type reference:
var myTarget:ILockable;//This can be set as Enemy, Powerup, any class which implements ILockable!
..and have the functions above as the interface itself.
They're also handy when using the Vector class (the name may mislead you, it's just a typed array) - they run much faster than arrays, but only allow a single type of element - and again, an interface can be specified as type:
var lockTargets:Vector.<Enemy> = new Vector.<Enemy>();//New array of lockable objects
lockTargets[0] = new HealthPickup();//Compiler won't like this!
but this...
var lockTargets:Vector.<ILockable> = new Vector.<ILockable>();
lockTargets[0] = new HealthPickup();
lockTargets[1] = new Enemy();
Will, provided Enemy and HealthPickup implement ILockable, work just fine!

Where should these AS3 variables go?

I am trying to build the foundations for a platformer game in Actionscript 3. I'm still fairly novice at AS3, but I'm hoping this will help build my knowledge.
Anyway,
I understand that I can create Actionscript files that are associated with something such as a Sprite or a MovieClip by extending the Sprite/Movieclip class. I also know about Actionscript files that work as the 'Document class'.
Each level in my game will have different properties that vary such as gravity. Where should I store these variables? Obviously not in the player... Not sure if they're supposed to go in the timeline or the document class, or if they have a separate AS file of their own. I've been told that having global variables is generally bad, so I'm not sure what to do.
You can make levels as separate files that are even not Actionscript, but XML or JSON, since your levels are basically data structures with different starting values. And you can make a Level class that can take such a file, parse it and initialize an in-game level structure based on what's read. Yes, such data should not go to timeline, because should you need to change one piece of that data, it could implicitly affect other game processes. Also, one simple right click can ruin such a game :) I myself use JSON files as my level data holders, and I parse them at the initialization time, you can do like this or say when your level is being loaded.
In short, if something is different by initial data, but common in methods, it should reside separately from main code, or entire code, and be included as data.
I think this similar question and answers will help you somewhat:
As3 OOP game structure (class architecture)
Basically, "What you want to do is to separate what changes in your game from the game itself". So definitely do not include the code in the timeline.

Preferable way to manage data, classes or arrays?

I'm making a turn based RPG in Flash, with AS 3 as the language, though I'm pretty sure you could help me regardless of the language you are using.
Basically, my idea was to put all of my weapon data on a single multi-dimensional array. Now if I want to add a weapon into my inventory, easy, i just use inventoryArray.push(weaponArray[1]) Easy, I just added the weapon into my inventory.
I've been looking into Design patterns, and it seems that most OOP designs are using classes and inheriting from a superclass. Component-->Weapon-->Sword-->LongSword.
What should I go with, putting all data in one array or using the inherit style, with one class containing a single weapon?
Any Ideas are welcome! I basically know how to make the game in itself, its just that I don't know some patterns I should go with.
Most of the objects in your game are going to have some properties in common - for example, maybe they will all have an ID, a name and a description.
If you don't use inheritance, you will have all your classes having this duplicate information in them, which will make your game hard to maintain.
If you do use inheritance, you can have all these common properties in a base (probably abstract) class and have all the other classes inherit from it. So yes, the design pattern you looked at is the way to go.
Also, rather than do inventoryArray.push(weaponArray[1]), you should also create an Inventory class with an add() method. That will allow you to dispatch events when an object is added to the inventory. The front end can then listen to this event and, for example, update the inventory graphics. In general, you should never use generic Flash objects (Array, Object, etc.) for potentially complex objects like inventory, characters, etc. Using your own custom classes allows you to easily extend them as your game becomes more complex.
I'd say composition over inheritance is the way to go.
There is a basic gameobject class that could be extended to weapons,rings,helms,shields, potions etc. These all have a set of restrictions that can be managed through inheritance (like the fact that you can place a weapon in hands and inventory only). But abilities of all of these (how they affect the character) should be done through compositions. Every time you add an object to the sash, hand, head etc. they affect the character through composition. So when you're dealing with the character's action, you don't loop through every object, you just use the composite function like attack, which has all the functions of the inventory that apply part of the character action.
The other design pattern you can look into is the decorator pattern. I find that the outcome is pretty similar to composition. "While the decorator pattern lets us add responsibilities to objects without subclassing, the composite pattern has a different goal: structuring classes in order to handle related objects in the same way, and multiple objects can be treated as one." source
example of decorator pattern:
http://www.as3dp.com/2011/06/well-armored-warrior-decorator-for-beginners/

How to manage entity display data and logical data?

What's a good way to store an entity's display data and an entity's logical data? Entities need to go on seperate layers (so like, background objects go behind foreground or so that enemies are always displayed underneith of bullets, etc.). The problem is, how do you manage these lists?
Does this seem like a logical solution?
I have a World object. The World object stores a list of all entities. To create a new entity, you go world.createEntity(type) and when a new entity is created, the world fires an entityCreatedCallback function that notifies all of the listeners that a new entity was created. In my PlayGameState class, I attach a listener to the world to listen in and when a new entity is created, I add that entity to an appropriate display layer for drawing later.
Then during the game loop I cascade like this:
allScreens.update() -> world.update() -> allEntities.update()
allScreens.draw() -> playGameScreen.draw() -> allLayers.draw()
Does that seem reasonable?
You are talking about a 2D game, right?
I like your architecture, because it seperates the creation of the entities with their initialization and use. I think it is clean and extensible.
In a game I wrote I had a similar approach, but my rendering engine made it easy for me and supported DisplayGroups which automatically rendered the objects in the right order. I don't know what technology you are using, but generally speaking if you are using hardware rendering with OpenGL/DirectX you could use the Z values to achieve the effect (literally place background objects behind).
In case you use software rendering, I think there is no other option than to order the objects before you draw them on the surface.
HTH