AS3: Model and View Communication in a Game - actionscript-3

So I'm attempting to use the MVC pattern for a game I'm working on. Everything has been going pretty smoothly so far, but I'm having trouble figuring out how to get my model and my view to talk to each other effectively.
My general model structure involves lots of nested information.
a Level has Rooms
a Room have Layers
a Layer has Objects
Each layer has an index and a corresponding layer in the view that is rendering it. I need the objects to post an update message as they animate so it's corresponding layer in the view can update. I'm trying to use the built in event system to handle these updates.
My issue is I'm not sure how to avoid putting listeners on every object in the game - which strikes me as bad ( perhaps I'm wrong here ). If I change the rooms, the layer doesn't have a way of removing listeners from the objects in the last room because it only accesses layers through the current room. Objects are only updated when they are in the current room, so the other objects won't need to fire events.
The view is set up to cascade events to all of the children, so the root node can receive all updates ( I think I did that part correctly ), and the layer can match the target because it knows which layer it's rendering. The problem is getting the message out from the objects to the view.
Of course this makes sense to me, because I've been working with the code for a while now.
If I can provide more clarification please ask. This is my first time working with the MVC pattern, so I'm sure I could do things better.
If you have any suggestions as to how I might solve this conundrum, please share!
Edit: I have something working keeping track of the current layerset from outside of the view and the model which manages adding/removing the appropriate event listeners and delegating the update event to the layer as suggested. But please, anything I can do to improve this please do.

If you are new to MVC you may want to check out the PureMVC framework for AS3. When I first started learning MVC I started by trying to build my own implementation of the pattern. After trying out PureMVC I got a much better understanding of the structure of MVC.
Your rooms/layers/objects sound like they have a parent/child like relationship and may be a good candidate for the composite design pattern. Basically this is a tree like structure where you could trigger an event which would then cascade through all branches. If you do a search for 'composite pattern' you may get a better explanation of how this may work for you.

There a few solutions you could take, adding event listeners is reasonable, but as mentioned you are going to need to make sure you clean them up appropriately, but this will be a requirement with a lot of other solutions as well.
Another one would be to pass in the layer on object construction, perhaps in the form of a "parent" property. In this case the object would notify its parent whenever it has changed, then on layer update, it would go through and handle all objects who have registered as having changed. This has performance benefits in that the object could change several time between renders, but the parent would only act on this changes once, (when its been told to update itself.) In this case you would still need to make sure you clean up your references properly to avoid garbage collection problems.
Yet another solution would be objects register with them selves as having been changed, typically in the form of a simple Boolean value. In this case the parent (your layer) would loop through all children, presumable stored in some form of collection, and handle updates to all those who say they've been changed. This solution removes the dependencies from object to layer, but in extreme cases, could lead to performance issues, (Extreme case being so many objects the process of checking a single Boolean value on them is too much to handle (that'll be A LOT of objects))
Hope that helps.

Using the Mediator pattern in PureMVC, rather than putting listeners on every object, you could have a Mediator listen to the application instance for the events. Then inside the actual objects, send a bubbling event that bubbles up the display hierarchy to the application where the Mediator hears it. Then the mediator takes the appropriate action such as sending off a notification to trigger a command with some logic, perhaps. The target of the event, would of course be the item in your world that sent the event, so if the Command would need to manipulate or inspect that item, then just pass the event.target in the notification body. QED.
-=Cliff>

Related

Restructuring to avoid accessing components in models

Continuing to work on my port of a CakePHP 1.3 app to 3.0, and have run into another issue. I have a number of areas where functionality varies based on certain settings, and I have previously used a modular component approach. For example, Leagues can have round-robin, ladder or tournament scheduling. This impacts on the scheduling algorithm itself, such that there are different settings required to configure each type, but also dictates the way standings are rendered, ties are broken, etc. (This is just one of 10 areas where I have something similar, though not all of these suffer from the problem below.)
My solution to this in the past was to create a LeagueComponent with a base implementation, and then extend that class as LeagueRoundRobinComponent, LeagueLadderComponent and LeagueTournamentComponent. When controllers need to do anything algorithm-specific, they check the schedule_type field in the leagues table, create the appropriate component, and call functions in it. This still works just fine.
I mentioned that this also affects views. The old solution for this was to pass the league component object from the controller to the view via $this->set. The view can then query it for various functionality. This is admittedly a bit kludgy, but the obvious alternative seems to be extracting all the info the view might require and setting it all individually, which doesn't seem to me to be a lot better. If there's a better option, I'm open to it, but I'm not overly concerned about this at the moment.
The problem I've encountered is when tables need to get some of that component info. The issue at hand is when I am saving my add/edit form and need to deal with the custom settings. In order to be as flexible as possible for the future, I don't have all of these possible setting fields represented in the database, but rather serialize them into a single "custom" column. (Reading this all works quite nicely with a custom constructor and getters.) I had previously done this by loading the component from the beforeSave function in the League model, calling the function that returns the list of schedule-specific settings, extracting those values and serializing them. But with the changes to component access in 3.0, it seems I can no longer create the component in my new beforeMarshal function.
I suppose the controller could "pass" the component to the table by setting it as a property, but that feels like a major kludge, and there must be a better way. It doesn't seem like extending the table class is a good solution, because that would horribly complicate associations. I don't think that custom types are the solution, as I don't see how they'd access a component either. I'm leaning towards passing just the list of fields from the controller to the model, that's more of a "configuration" method. Speaking of configuration, I suppose it could all just go into the central Configure data store, but that's always felt to me like somewhere that you only put "small" data. I'm wondering if there's a better design pattern I could follow that would let the table continue to take care of these implementation details on its own without the controller needing to get involved; if at some point I decide to change from the serialized method to adding all of the possible columns, it would be nice to have those changes restricted to the table class.
Oh, and keep in mind that this list of custom settings is needed in both a view and the table, so whatever solution is proposed will ideally provide a way for both of them to access it, rather than requiring duplication of code.

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

ActionScript - Should Event Dispatching/Listening Be Avoided Where Possible?

recently, i ran into a problem where i needed to access the List object from the List's custom cell renderer class.
there were 2 options:
listen for and dispatch a custom event to communicate between the 2 classes.
reference the List from the cell renderer class with the parent property: List(parent.parent.parent)
while it's much easier to choose the second option, i feel that dispatching and listening for a custom event would result in code that's more inline with the design of AVM2, offers greater control for communication and, as it's expected AS3, should be less difficult to debug or maintain within new hands.
however, i also feel that using an event is more expensive, requires attention to resource management perhaps making it more difficult to debug and maintain and could be generally overkill.
is this simply a matter of needs or taste? should dispatching/listening for custom events be avoided if they can be?
Don't forget that you can't see the control flow of event listeners from single glances at the code.
While I'm not against event listeners completely, if you use them, you should try to use them in the most self-documenting and simple way possible. If you have clever stuff, like adding/removing event listeners, and it goes wrong, then it can be a nightmare to debug because you cannot see what dispatchEvent is going to do.
If owner gets you the right object, then I would just go with that, myself.
I would look at it from another angle. If the other option ends up creating more dependency between the two classes, I would definitely opt for event dispatching.
In that regard , I'm not sure why you think that an event driven application would be harder to debug & maintain. It would seem to be the opposite, but it would of course depends on how one implements the event dispatching in the application. But saying this and re-reading your question I realize you seem to contradict yourself! Of course , I tend to agree with the first statement.
...offers greater control for communication and, as it's expected AS3,
should be less difficult to debug or maintain...
...perhaps making it more difficult to debug and maintain and
could be generally overkill.

Game programming without a main loop

My professor gave my class an assignment today based on object oriented programming in Pygame. Basically he has said that the game that we are to create will be void of a main game loop. While I believe that it is possible to do this (and this question has stated that it is possible) I don't believe that this is required for adherence to the Object Oriented paradigm.
In a diagram that the professor gave, he showed the game initializing and as the objects were instantiated the control flow of the program would be distributed among the objects.
Basically I believe it would be possible to implement a game this way, but it would not be an ideal way nor is it required for Object Oriented adherence. Any thoughts?
EDIT: We are creating an asteroids clone, which I believe further complicates things due to the fact that it is a real time action game.
Turn based games or anything event driven would be the route to go. In other words, take desktop GUI apps. They'll just tick (wait) over until an event is fired. The same could be done for a simple game. Take Checkers for example. Looping each game cycle would be overkill. 90% of the time the game will be static. Using some form of events (the observer design pattern would be nice here) would provide a much better solution. You're using Pygame, so there may be support for this built in, through due to my limited use I cannot comment fully. Either way, the general principles are the same.
All in all it's a pretty rubbish assignment if you ask me. If it's to teach you event driven programming, a simple GUI application would be better. Even the simplest of games us a basic game loop, which can adhere to OO principles.
Hmm. In the general case, I think this idea is probably hokum. SDL (upon which PyGame is implemented), provides information to the program via an event queue, and consuming that queue requires some sort of repeatedly checking the queue for events, processing them, and waiting until the next event arrives.
There are some particular exceptions to this, though. You can poll the mouse and keyboard for their state without accessing the event queue. The problem with that is it still requires something like a loop, so that it happens over and over again until the game exits.
You could use pygame.time to wait on a timer instead of waiting on the event queue, and then pass control to the game objects which poll the mouse and keyboard as per above, but you are still 'looping', but bound by a timer instead of the event queue.
Instead of focusing on eliminating a main loop, how about instead think about using it in an object oriented way.
For instance, you could require a 'root' object, which actually has its own event loop, but instead of performing any action based on the incoming events, it calls a handler on several child objects. For instance when the root object recieves a pygame.event.MOUSEBUTTONDOWN event, it could search through it's children for a 'rect' attribute and determine if the event.pos attribute is inside that rect. if it is it can call a hypothetical onClick method on that child object.
I think it might qualify as event driven programming? Which can still be object oriented. You see this in Flash a lot.
There's a difference between a main loop in a main class. You can still have a game class initialize all of your objects, and then rely on inputs to move the game onward.
Kinda hard to say exactly without knowing the exact parameters of your assignment, the devil is in the details.
You might look at how python utilizes signals. A decent example I found is at: http://docs.python.org/library/signal.html

Creating lightweight Linq2Sql proxy objects

I'm trying to find the most efficient way to send my Linq2Sql objects to my jQuery plugins via JSON, preferably without additional code for each class.
The EntitySets are the main issue as they cause not only recursion, but when recursion is ignored (using JSON.NET's ReferenceLoopHandling feature) a silly amount of data can be retrieved, when I only really need 1 or 2 levels. This gets really bad when you're talking about Users, Roles and Permissions as you get the User's Role, the User's Permissions, the Role's Permissions, and the Role's Users all up in your JSON before it hits recursion and stops. Compare this to what I actually want, which is just the RoleId.
My initial approach was to send a "simplified" version of the object, where I reflect the entity and set any EntitySets to null, but of course in the above example Roles gets set to null and so RoleId is null. Setting only the 2nd level properties to null kind of works but there's still too much data as the EntitySets that weren't killed (the first level ones) repopulate their associated tables when the JsonSerializer does its reflection and I still get all those Permission objects that I just don't need.
I definately don't want to get into the situation of creating a lightweight version of every class and implementing "From" and "To" style methods on them, as this is a lot of work and seems wasteful.
Another option is to put a JsonIgnoreAttribute on the relevant properties, but this is going to cause a nightmare scenario whenever classes need to be re-generated.
My current favourite solution which I like and hate at the same time is to put the classes into opt-in serialization mode, but because I can't add attributes to the real properties I'd have to create JSON-only properties in a partial class. Again, this seems wasteful but I think it's the best so far.
Any suggestions gratefully received!
Have you tried to set the Serialization Mode in the dbml file?
It's a standard property under code generation and when you set it to Unidirectional it won't generate all the additional levels of your table structure. I've used this with silverlight and WCF to send data because the data contracts don't allow for additional levels to be sent (silverlight is very limited on what you can and can't do).
Hope this helps!