Basic MVC pattern communication - actionscript-3

I just started to study the Model View Controller pattern. I now understand the basic usage of MVC, but when i tried to implement MVC in a simple test, i ran into a problem. Ofcoarse I could easily adjust the code so it works, but I wish to learn how to correctly implement the MVC pattern.
The test:
I used actionscript 3 to make a simple program. It consist of a turret, and a mouseclick. The turret is in the middle of the screen. When I click anywhere the turret rotates towards the point where I clicked. Both the mouse and the turret have their own model,view and controller. When I click, the MouseModel changes correctly. But for the actual TurretView to respond, the TurretModel must change its rotation variable and send out an event.
The question is who responds to the MouseModel event?
/------->MouseControl------\
/ \
MouseView ?<---MouseModel
TurretView <------------------TurretModel
TurretControl
I figured its best not to have MouseModel directly influence TurretModel or TurretControl, because this would require them to be an eventListener. Making TurretView listen to the MouseModel, and then tell TurretControl to adjust TurretModel, after wich TurretView can update trough a TurretModel event looks like a lot of extra code for a simple task. Also I'd rather not have MouseControl affect TurretModel, this would break the flexibility of the mouse as input for future classes.
Ow, also in which class do I put the code for the angle calculation?
Thanks in advance

Remember that the goal with MVC is primarily the separation of Model and View, and the Controller can serve as the communicator between the two.
Unless you are planning on storing each action that occurs (clicking, rotating, etc.), there is no real need for an action (in this situation) to send data to the Model. Everything you'd like to do should be easily handled with the Controller. So the flow would be:
Mouse click
Event is fired to trigger a command (in the Controller), passing along the mouse location
The command calculates the turret's rotation
The command tells the View to rotate the turret
This is, of course, my suggestion based off of your example. In truth, depending on the project, the above flow could easily change (for instance, in this situation it seems good to do rotation calculation in the command, but in other situations that may not make as much sense). Look at MVC as a goal - you're trying to separate these elements as much as possible, but there is no 100% "works-every-time" way to do it.
Robotlegs, a popular MVC framework, has a great diagram on their site showing how they tackled MVC:
http://www.robotlegs.org/diagram/
I'm not advertising that you NEED to use Robotlegs (it's good, but there's plenty of other alternatives), but they definitely made a pretty diagram :)

You should have one model, which then has pieces in it that you are currently calling MouseModel and TurretModel. You can either keep those names and breakdowns, or do something else once you have a better "handle" on what needs to be done.
The View that is tracking the mouse clicks should dispatch an event that your Controller component catches to update the TurretModel (at this point, there's probably no need for a MouseModel). Your TurretView can then update itself based on the TurretModel, or the Controller can update the TurretView based on the new value. This will depend on how you have it wired.
Usin a Framework such as Robotlegs can help you figure out all the ins and outs of this process, and I've heard that this book http://shop.oreilly.com/product/0636920021216.do provides a great explanation of MVC, even if you don't choose to use Robotlegs after you read it.

Related

Integrating game with libGDX

I have multiplatform 2d game made in kotlin, which has its own game-loop, fires evens which then can be used to construct GUI/modify it. The project is very modular and quite flexible.
The game loop has multiple implementations using coroutines, java threads, javascript requestAnimationFrame, setInterval, etc.
I have multiple implementations of GUI, including text interface and HTML/javascript.
Now I decide to give it a try and make GUI using libGDX. I am playing around with it a bit trying to integrate it with each other (first using "desktop" platform).
My game loop goes through all necessary components like "unit spawner", "unit container", "projectile container", etc. passing "delta" to all of these. These components are firing different events like "unit moved", "projectile fired", etc.
If I understand correctly, so far I see 2 options on how to integrate:
Keep my gameloop, collect relevant events related to UI update and then update all of them in render function of my ApplicationAdapter (because I cannot render outside of render methods, right?).
Use Actor class and for every component (or group of components) and use it's render and basically let libGDX handle gameloop for me.
How would you proceed? Are there any other options to go?
I want to keep my design flexible and modular, not to be tightly bound to libGDX, and rather make it another GUI implementation if possible.

What is capture and normal phase in event handeling in Scene2D ?

I read the wiki but it's very confusing for me. Can someone explain it in easy language? There are few doubts I have
1. Is capture listener and normal listener are also one of the many listeners provided by scene2D like InputListener, ClickListener etc
What is the difference between target and listener actor?
No, these terms describe whether you've assigned one of the types of listeners as a capture listener or not. Capture listeners allow an actor a chance to reject an event on one of its descendents. For example, some kind of group widget can decide whether to reject presses on a button that is in it based on some criteria. I think the built-in ScrollPane class uses this to prevent buttons and sliders from being manipulated while the view is being scrolled. Most people will not have a reason to use this, as it is for custom widgets that have very particular behavior.
Target and listener actors are usually the same. The listener actor is the actor you attached the listener to, and by default it will also be the target. But you can change the target actor to something else. This is just a feature to allow you to create listeners with custom behavior. Most people will not have a use for this. I don't even think it is used by any of the built-in classes.
The complexities of the listener system were designed to get button and widgets to react to input like a traditional UI. Unless you are designing widgets with customized input behavior, you only need
ChangeListener for the UI widgets (buttons and sliders).
If you're using Scene2D for stuff other than UI (the game scene) you'll subclass InputListener to react to touches. Or maybe GestureListener.
I built a small game using Scene2D and found that it is a bit clumsy for non-UI stuff. I wouldn't do it again, personally. So I would say 99% of people making simple games should only ever use ChangeListener.
The action system is nice for tweening stuff, but you can just add actions to the stage root and react to them externally with your own non-actor classes.

AS3 How to communicate between frames

I have been writing a game in timeline code. I want the different frames (rooms) in the game to be able to share information between each other. Of course, timeline code is limited to the frame it is written in.
After doing quite a bit of reading ("Foundation Game Design with Flash" and a number of articles, tutorials, forums etc) I decided to employ a document class. This did not work either. It seems it only works for frame one but not the rest of the frames (I have four).
How can I have frame four respond to something that happpened in frame one? For example, if the player achieves something in frame one, I want a movie clip in frame four to be visible.
If You are writing your code on the timeline, My suggestion would be to create two layers in the timeline, one for 'frame-actions' - in this layer you insert the code specific to a single frame (will work when the movieclip is stopped on that particular frame).. And also create one more layer called global-actions (for the entire timeline). Only the first frame will be a key frame and there should be empty frames till the end of the timeline.
In this layer actions write the code that you want to access from any keyframe in the same timeline.
If you define a variable in the actions which are written for the whole timeline (global-actions) then that will be available on all the frames.
Now if you want to go to a different frame based on some action, just write some functions in the layer which contains global actions and call that particular function through the frame actions. To go to a different frame use the 'gotoAndStop(frameNumber)' function of flash.
I want to tell you that while it will work, I would not recommend using it in this way.
HTH.
You can use static variables - these are variables which are linked to a class, rather than an instance of it.
Suppose your document class was called Document.as, and you wanted a variable, playerLives, to be visible from any part of the program.
Declare it inside Document.as:
public static var playerLives:int = 3;
You can then reference this directly from anywhere else in your code with:
Document.playerLives
(note that the variable is a member of the class itself, not an instance of it).
You could use a dedicated Statics class to hold these variables if you want to keep your document neat, or attach them to the relevant classes (eg Player.lives)
I've not used timeline/frames for some years but I believe this is how I used to do it!
NB Statics will be fine for your purposes but they are, in some ways, an equivalent to the _global variable in AS2 (at least, they can be used in the same manner) - many would not approve of their use, or over-use, as they are freely accessible from anywhere in your program (thus anathema to the OO concept of encapsulation), but personally I try not to worry about it in small cases - the most important thing to know about the rules of any design pattern is when they can be broken!
They are also slightly slower to access than instance members, but you won't notice this unless you are constantly accessing/changing them (making things like player velocity, which will need to be referenced/changed every frame, static, is not a good idea).
Hope this helps.
You may find the simplest way to link everything with the document class is to move your four frames into a movieclip together and have that on the first frame, then interact with that movieclip.
E.g. in the document class, where the movieclip instance on the timeline is called 'game'.
game.gotoAndStop(4);
game.objectToDisplay.visible = true;
If you encounter reference errors in the IDE then you can avoid these by using [] notation to refer to the properties of game, e.g. game["objectToDisplay"].visible = true;
Note that it's not really best practice to do this, but it will at least help you to finish that first game which is really more important at this stage in your learning. Afterwards, if you want to learn more then I'd recommend "The Essential Guide to Flash Games" by Jeff Fulton from 8bitrocket.com - it will teach you how to use the document class effectively.

Code for A Graphical User Interface window

How would someone go about coding a 'window'? I'm starting to make a GUI, and I want to learn how to code one. One that can be skinnable, and one that actually loops and creates itself at runtime. I understand that this might be a bit vague, so I'll add details.
One that actually 'creates' itself. Most GUI tutorials I've looked on depends on an 'image' that just gets added on the screen. I want to be able to use skins in my windows. One where my 'skin' is just a collection of 'borders'. Then when I insert window.create(50,50) where 50,50 is my height, width, It would just create that window, following the skin.
I understand that it probably follows just like when a language draws a rectangle, it just follows a different set of rules (maybe?). However, for all my Google-fu skills I cannot find a tutorial that teaches me this.
Please Help. I didn't include the language I used as you can see, because I believe I just need to know how to create one. Anyway though, I am using Actionscript 3. A tutorial would be just fine, or even A SINGLE CLASS THAT HAS THIS FUNCTIONALITY, I'll just study the code. Or if you know one, maybe a whole book about GUI and programming it :D
Pure As3.0 GUI coding is quite troublesome. I try to Googling, but not come out well. anyway for my case, i generate using a SWC, and Class Mapping and Customizing. but i'm not sure best way. in other way i use a bit101 library. this is gives me want Window, Charts, Componets easily of high abstraction. see the below image.
It can be pretty hard and complicated to do, or very easy, it just depends on how flexible your solution should be. You need firstly to design a structure of your program and approach to the problem.
I like to go from the image of how it should look like from API point of view. I think I would create a GUI element like this:
var wholeGui:MyGUI = new MyGUI();
var window:IGuiElement = new GuiWindow(dataObject, skinObject);
wholeGui.addElement(window);
So what would you need?
1) Object that would manage all GUI elements. Why? Simply because your GUI elements shouldn't be destroyed by themselves if user will click "X" on your little window. The wholeGui object would manage them and listen for any events including those that would destroy them. You may consider creating custom events for interaction between the wholeGui object and your window object if this interaction is going to be complicated.
2) Interface for your GUI objects. Some problem here is that AS3 actually doesn't have interface for Sprite, and you would like to interact with it like with extended Sprite. The workaround here is to have in this interface a declaration like this:
function asSprite():Sprite;
And your implementation in GuiWindow would look like this:
public function asSprite():Sprite {
return this;
}
And your GuiWindow class should extend Sprite of course. Then you would have access to it's Sprite properties and methods by writing for example: window.asSprite.startDrag();
This interface should give you abilities that you need to operate on your GUI element.
3) Class for your GUI element, in this example GuiWindow.
4) Class for your data that would be injected into your element. If you would load data dynamically, and from some location, you would need to deal with the situation when no data can be provided - but that logic would be inside your window.
5) Class for your skin - so you would be able to dynamically create a skin object and use it to create your window in a way you want.
That's just few thoughts to consider.
PS. It may be good idea to fill GuiWindow object with data AFTER creating it, and not in constructor, as you would be able to visualize loading process then.

Taking an intro Flash/AS3 course; problems with MVC pattern

Okay, so I've been busting my hump the last week or so on this project for my OOP/AS3 course and this past Sunday I realized that my approach wasn't going to work so I scrapped the better part of it and started over.
Our assignment is to create an XML based flash menu that demonstrates an understanding of the OOP patterns we've just learned. It was kind of a 'test the waters' project where he gave us a ton of tutorials and information and told us to make our best attempt at making sense of it so I'm certain there are more efficient ways to do what I'm doing, but that's a moot point.
We need to employ at least two patterns in our menu, though at the moment I'm just focusing on MVC so that I can get the mainUI working before I finalize the second part of the UI. It essentially flows like so:
MainUI has 4 menus that slide out.
Each slider has 3 thumbnails on it.
Clicking on any of the thumbnails will move to the next part of the UI. This functionality is currently disabled.
The program runs with 0 compiler errors, but the images are not being placed on the stage correctly and I can't figure out why. All the image paths are being pulled and stored from the XML properly. The main background image is pulled once and is supposed to be only placed once (if statement that uses a count to determine whether to run the placement function or not), but it is being placed 4 times with the sliding menu image. The sliders are being placed in the correct positions (switch statement that iterates through the mainUI function in the View class and creates a separate loader for each one), but the thumbnails are not all showing up. So here is what I'm seeking help with:
The mainPanel image should only be placed once, rather than 4 times with each slider.
The sliders, while being placed correctly, must be tweened in different directions through the as (using TweenMax), but each instance is unidentifiable from the other so right now they all have an eventListener that calls the same tween method. How can I distinguish them in a way that lets me apply a different tween to each (This will likely be a concern with the thumbnail functionality later as I will need to load different XML data based on which thumb is clicked).
I have added what I hope are very informative comments to each script so hopefully people can help. Also included are images of what I want the mainUI to eventually look like and how it's coming out currently.
pastebin with all 3 classes and XML (2 hyperlink limit) - http://pastebin.com/u/crookedparadigm
top image is how the stage is outputting, bottom image is what I'd like to to be - http://imgur.com/a/bOmsS
Last quick note, stage is currently set to 600x480 with a black background. Ideally, to reinforce OOP principles, our professor wants us to avoid using the timeline or library if possible.
Any advice at all will be greatly appreciated! Thanks!
Install FlexPMD This is a very good add on( sometimes hard to install ) It basically is used to show areas of your code that you are not following standards. For example your classes lack the use of "this". And you should avoid passing parameters in constructors. It would be good practice to develop standardized writing skills while you are still new.
Looking at your code I see you are calling buildUI from within a loop.
buildUI is assigning a MainView object to mainUI.
So each time you go through a loop iteration you are reassigning mainUI.
In the end mainUI will only be the last iteration of that loop.
Not sure this is your issue but is an issue.
[EDIT]
Excellent Singleton guide for Flex SDK
Part 1
Part 2
Some Good writing on pure AS3 Singletons.
I would prolly start from scratch as your XML data is miss formatted.
your XML should resemble something like this.
<MainProject>
<MainUI>
<Thumbnail Name="Spring">
<Destination Name="Spring" Price="99" ratingPath="images/SP1/SP1rating.png" />
</Thumbnail>
<Thumbnail Name="Winter">
<Destination Name="Winter" Price="152" ratingPath="images/SP1/SP2rating.png" />
</Thumbnail>
</MainUI>
</MainProject>
Then you should have the following structure on your stage. These movieclips should be empty and already placed inside on your stage with instance name.
Stage
MenuUI MovieClip
ThumbNail1 MovieClip <- feed it thumbnail from the XML
ThumbNail2 MovieClip <- feed it thumbnail from the XML
ThumbNail3 MovieClip <- feed it thumbnail from the XML
ThumbNail4 MovieClip <- feed it thumbnail from the XML
This might be a bit too vague, just tell me if you need more details.
Hope this helps !