Actionscript: What good does using private variables do? - actionscript-3

So I am reading the Actionscript 3 tutorials here: http://www.adobe.com/devnet/actionscript/learning/oop-concepts/writing-classes.html
and I want to know, how is Rectangle version three better (more resuable and flexible) than rectangle version two? I see that in version three, they create private variables and then change the private variables to variables in the constructer method but then they go back and use the private variables in draw().. what good does that do?

Keeping variables private is all about 'encapsulation'. If most of a Class's code is private any code that uses that Class doesn't need to know how it implements its methods. This means that, so long as the method names and parameters stay the same, you can change how a Class implements methods without changing anything OUTSIDE the Class. It also prevents 'tight coupling'; where Classes come to depend on other Classes.

Imagine buying a brand new TV. You have a remote, you have a few buttons on the TV, some jacks, a cord or two, speakers, and a screen. Now all you have to do is just get that TV plugged up, and you're ready to go, right?
Do you need to know how the TV works internally? Do you need to know whether it has an electron gun, a liquid crystal display, or some other means to convery the image? Do you need to know how many fans, buses, wires, switches, logic gates, etc. are in there? ... Do you need to know how to make a TV yourself?
No. And the fact that all these sorts of details, bits, pieces, and parts are hidden behind what is essentially a black, plastic box is not just for aesthetic pleasure - it's to keep the customer from getting into stuff they shouldn't.
If you're the manufacturer, and if you leave the TV's circuit boards on the outside of the TV, not on the inside, some customers who don't know what in the world they're doing are going to mess with those circuit boards and accidentally screw up the TV. Furthermore having to worry about whether to mess with those circuit boards or not is going to cost them time in learning how to use that particular model of a TV. So you keep the circuit boards, wires, and all sorts of other stuff packaged neatly inside that black, plastic box - away from the eyes of the customer. All they need (and should) worry about is getting used to their new remote.
This is not to say, mind you, that the customer can't just get out a screwdriver and start pulling this stuff out anyway. This is just to say that by keeping those things tucked away like that, even if the customer does open up the TV and mess around with the internal workings, they'll at least know they're treading on dangerous ground.
Private variables and methods are like the bits and pieces inside of the TV, whereas public ones are things like the speakers, monitor, and remote control. You make the distinction for the same exact reasons. In most cases the programmer you're tucking these details away from (a lot of times it's you guarding it against yourself and your own careless errors) can still see what you've got there, and they can still get to it and mess with it if they need to, but the keyword "private" gives them a very solid realization that "this variable/method belongs to this class and this class alone, and it should not be tampered with anywhere outside of it". If they do try to access it from something outside of that class's code, it just won't compile basically.

Related

WorldRenderer responsibilities

I started learning libgdx lately and, obviously, I've been looking into several sample games and tutorials.
I couldn't help but notice inconsistencies into how authors/developers choose to design their game classes - especially when it comes to the "renderer" classes.
In some examples, I see some authors relying solely on the "renderer" classes to draw using the SpriteBatch. While others tend to send a SpriteBatch reference to game objects to do the rendering themselves.
For example, considering a Bird class, some would associate it with a Texture type, load it and render the bird inside a Bird.render method. Others load the Texture in separate "Renderer" classes (Like WorldRenderer) and draw the bird texture from there by relying on position parameters such as bird.getX() and bird.getY().
I wrote some sample games using XNA in the past and I used to embed the rendering logic into my game classes. My renderer class used to simply loop over all "enabled" game objects and call "GameObject.render()". Is this a bad practice in libgdx?
It is not about bad practice in libgdx, it's a general opinion oriented problem.
Usually, it's always better if you can separate game logic and rendering logic (preferably in different classes). This way, if you want to change look and feel of the game (re-skin it) later, you won't have to touch the code containing game logic (less testing required, no new bugs).
But not everyone follows this (some might think it as overkill for small things). Having renderer class for each and every small thing might seem too much. So you'd see a lot of code having mixed both rendering and game logic.
If you want to build scalable games, I'd suggest you to follow MVC (game codes so large that developers might get lost). But at the same time, you should be pragmatic enough to know when not to use it (small games taking 2 weeks to make).
So it's for you to decide really, since it's about personal preferences.
Hope this helps.
A lot probably depends if the developer has used MVC (Model-View-Controller) before. In an MVC design the "game" objects like bird are part of the model and don't directly have anything to do with the display(view). Sometimes it depends on the technologies being used, for instance the LibGDX Scene2d API warns you that "Scene graphs have the drawback that they couple model and view".
In a worldRenderer you should render all your objects. All your objects belongs to a world so it makes sense. A benefit to add attention to is that you can always keep all gameObjects in separate arrays aswell as in a big array (containing all).
Array: GameObjects
Array: Birds (also in GameObjects)
Array: Cows (also in GameObjects)
Array: Cats (also in GameObjects)
This makes it possible for you to decide on what "z" axis all gameobjects should rely on (render) aswell as just loop through them all right away (update)

ActionScript 3 movieclip with interchangeable images

I'm creating a game using Flash Develop and ActionScript 3.0 and I can't figure out how to make a "Character Creation" menu, in the sense that, I want to animate a movieclip full of images (head, torso, arms, etc.) and then change out any image with another.
So I'd like players to be able to choose what kind of sunglasses they want their character to have, for example, and the different sunglasses will keep the animation that I made with the original ones.
From what I know so far I can export a movie clip as a .swf and use it as such, but how do I change out images and keep the animation?
Any suggestions are greatly appreciated.
Thanks!
I don't know how much actionscript you know.. but if you just want an idea how to do it and not the whole thing in code...
I would personally make different movie clips for the different parts of the body that can be changed and then change frames in that move clip. For example one movie clip with different hairstyles, one with (sun)glasses and so on.. and then just go to then next frame in the "hairMC" to change the hairstyle.
The way I'd do it is to create MovieClips that all implement the same Interface and then have other MC's higher up that know how to use the particular Interface. For example, if you had an IArm, it might know how to swing and how to grasp (and it might grasp by using an IHand). A fat ITorso might attach the arms at a different spot than a thin one.
And your Character might have an IHead, ITorso, etc. When you created a Character, you could either pass in these components via the constructor (I'm not a big fan of constructor arguments for Views, but it's one way to do this), or you can expose setters on your Character that allow you to set these properties one at a time.
This gives you tremendous flexibility in how to put your character together--none of the pieces know precisely how the others are put together, but the methods they need to operate on are in place, so you can put in any implementation you can think of.

Class organization: Function internal or external

I am creating a side scrolling game in Flash (as3) and trying to keep things organized and clean.
Ive created a "Level" class that gets all the level data, player data, and creates all the terrain objects and the player object. Its starting to get messy because im handlng all of the functions for player collision checks and player movement, terrain movement, sound starting and stopping, enemies, and more, all in this class. Is this normal? Or is there a better way to organize things to keep them separate, but still allow them to interact with each other.
I have a player class, and terrain class, and enemy class and etc. but there is not much going on inside them.
Thanks/
Sounds like it's time to take a look at how you can break up your level class and move some of that functionality to other classes. What you're describing happens all the time, so don't worry - it just means it's time to reorganize a little.
You might consider taking you player collision for example, and moving that out to a Physics class. You can set up a static function that allows you to pass in two DisplayObjects, and then tests for collisions between the two.
For sounds, you might consider a singleton class like a SoundManager, that holds onto all of your sounds in an array or dictionary, and then have your other classes play sounds through a function like playSound(soundName:String):void on SoundManager.
Hopefully that gives you a start. Feel free to ask if you need more details. It also might help if you post some of your code. Good luck with it!
Without getting too much into object-oriented design principles here, my advice would be to ask yourself "What belongs in a class named X".
So for example, it sounds like the Level class should keep track of the players, enemies, and terrain on that... well, level (perhaps map or stage might be a better name?). But it doesn't need to do all the work for those objects; many of the functions that do the work for movement, collisions, sound, etc. can be moved to those other classes. Then the Level becomes an orchestrator; kind of like a conductor leading the music (but not actually playing the violins, horns, etc.).
Also, it sounds like players, terrain, and enemies have quite a lot in common. For example, they all need movement and collision handling. You may be able to create a parent class (say GameObject) and have the Player, Terrain, and Enemy classes extend from that. This kind of polymorphism can be very helpful for taking care of common functionality.

Help with decoupling a game design

Here's the current dependency graph (with freehand circles for TheTXI)
A game has players and a single board shared between them.
A player also has access to the board to be able to add/move/remove units from it.
A player has access to the units it owns, both on and off the board (A unit also knows it's owner, but that can probably be removed and just do a lookup).
A board has units on it and knows units' positions.
Units have abilities (Players possibly can as well)
The big one that I'm having trouble figuring out is Unit's Abilities. They should be able to affect anything in the game, healing/damaging a player/unit, reposition things on the board, possibly even the game itself (so far there isn't a need, but it could come up).
How can I have abilities that can affect anything without them having a reference to everything? I realize each ability can and should have references to only what it needs, but a unit class has abilities built in to them, so if a unit's ability affects the board, it will need to get a reference to the board from the unit somehow?
I'm trying to keep the design as flexible as possible, because the rules aren't set in stone yet (we're creating a game, and still pretty early on, so it's try something, see how it feels, change the rules until the game feels right)
Even whether there's a board/map at all is still up in the air, so the units should be decoupled from that, which they currently are. There is no global state or any "god object" (yet), and I'd like to keep it that way.
Specifically it's in Python, webapp, so while the question itself is language agnostic, any specifics based on a dynamic language with first class functions are certainly welcome.
First, let me point you to the wonderful gamedev StackExchange. You might have more luck posting this question there.
As far as your question itself goes, I think one solution would be to pass notifications from the object triggering the ability up to the game object, which would then parse these notifications and hand them out to specific players, or boards, and from there to specific units.
It's hard to explain, so let me try and write it out in psuedocode...
Game {
getMe(); //Returns reference to singleton class.
list of players
list of boards
}
Board {
list of units
}
Unit {
int health
}
function Unit.notifyAbility(source, targeting-condition, ability-code) {
Game::getMe()->sendNotification(source, targeting-condition, ability-code);
}
function Game.sendNotification(source, targeting-condition, ability-code) {
for each unit in list of units {
if(unit matches targeting condition) {
apply ability-code
}
}
}
Targeting-condition and ability-code could themselves be data structures that pass relevant information. Even better, make them virtual classes and use some form of polymorphism to handle unique cases.
Example:
AbilityCode {
virtual function applyToUnit(target Unit)
virtual function applyToPlayer(target Unit)
}
AbilityGainHP: child of AbilityCode {
function applyToUnit(target Unit) { target.hp+= gainAmt; }
int gainAmt;
}
Hope this makes sense.
You might overthink this a bit.
Keep in mind, you want to be able to work with your code base, so it's important that you can easily understand your code, even if you haven't worked on that particular part for a bit.
If you describe your game in words, you'll most likely the use something like:
It's a game for X players, played on a board of (specfics).
Each player controls Y units.
So, start your design like this.
The game (either your complete code, or just the PLAYING state of your program) needs to have references to the board and the players.
Now, the board will handle most of your problems.
If a player interacts with the game, he'll most likely do something on the board.
Start with a simple system that allows you to move stuff around you should be able to move around, while not being able to move the stuff you shouldn't.
The abilities will most likely be a list containing the currently available selection out of the whole list.
These will depend on the unit and maybe other elements of the board.
Depending on the type of game, you can either use events to inform the units that something has changed, or simply get the information when you need it.
Don't add more layers of abstraction than you actually need.
From your description, the abilities seem to be the part you want to spend most time on, to ensure you can easily change and add to them.
Start with a simple design for the other parts, and refactor if you see that you need an extra layer at certain points.
This will avoid analysis paralysis. Esp. when you want to make a "neat design" it's very easy to overcomplicate things.
You want to get the game running. You want to be able to read (and understand) your code easily.
Your coding style and knowledge will change even while working on the project, and you'll also get new ideas while coding.

Avoiding Global State

Currently I'm writing an app. If I want to avoid Singletons, do I have to simply pass references of everything around?
For example,
I have a "main" class.
Class: Main
+---- Screen
+---- Camera
+---- Terrain
+---- Vehicle
+---- PhysicsWorld
It contains my Camera, Terrain, and Vehicle,etc classes. Now, I have issues when I'm creating say, the Terrain object. Terrain wants to access Main classes Screen object so it can add its Terrain Graphics to the screen. It also wants to know about the Camera object for when it is drawing so it knows what scale to draw it. It also wants to know about my PhysicsWorld object so it can add itself to the physics engine.
Do I have to always lug these objects back and forth between constructors? I mean, when I create a Terrain object, do I simply have to pass around my screen object, my physicsWorld, camera, etc?
Another random scenario I have, is now.. inside my Vehicle class I need to call a Restart() method on my Main class. Does this mean I have to pass an instance of main to Vehicle? Really??
It feels cumbersome to constantly have to pass 4-5 things to my classes, especially in my scenario now where almost every in-game object I have needs a screen, physics, camera info, etc.
Any suggestions?
It feels cumbersome to constantly have
to pass 4-5 things to my classes,
especially in my scenario now where
almost every in-game object I have
needs a screen, physics, camera info,
etc.
Then the correct question to ask is "why do I need all 5 objects in all my classes?"
Why on Earth does every in-gmae object need any of the mentioned things? An in-game object needs a position and whatever it needs to process its behavior. Then a separate renderer can, you know, render, the object. Which means that only the renderer needs the camera info and screen.
The physics could go either way. You could have a separate physics entity which updates the game object, or you could pass that physics object to every game object. But even if you do pass that around, we're down to one out of the three objects listed. :)
That's why globals and singletons are often best avoided. They disguise your dependencies so you end up with far more dependencies between your objects than you actually need. And then it becomes almost impossible to remove the globals.
However, if you do stick with globals, do yourself a favor, and at least avoid singletons. You don't need the additional constraints enforced by a singleton.
Terrain wants to access Main classes
Screen object so it can add its
Terrain Graphics to the screen. It
also wants to know about the Camera
object for when it is drawing so it
knows what scale to draw it. It also
wants to know about my PhysicsWorld
object so it can add itself to the
physics engine.
The terrain object needs to know one thing: What is the terrain like. Someone else can take responsibility for rendering it. That someone will need to know about the camera, screen and terrain graphics, sure, which suggests that the same object might plausibly be able to do other tasks involving these objects (such as other rendering tasks).
Why should the terrain care about what scale it's drawn in? It needs to know the scale ingame, but not the scale in camera-space. And why can't someone else add the terrain to the physics engine? The main function might be able to do that, even. Create terrain, create physics engine, register terrain with physics engine, start game.
I don't know ActionScript, but assuming variables are passed by reference, the least you could do is construct a 'Environment' class holding Camera, Screen, Terrain, PhysicsWorld which you pass to the instances.
I have the exact same problem (also in actionscript 3, coincidentally).
I have been working on an RTS for flash and had found myself needing to pass around large numbers of references to each new class (e.g., gameGrid, currentSelection, visibleUnits, etc.).
I eventually realised that what I really should be doing is to have every class maintain it's own properties, and instead pass around references to these classes, (well objects).
But anyway, now what I'm doing is having static variables containing references to commonly used objects such as the main stage, interface, engine and display area inside a class called RTSGlobals. I'm also putting constants such as the screen size in there.
I know this doesn't really answer your question, but I figure sometimes it is worth ignoring a bit of OOP good practice in favour of an efficient solution.
If someone has a does have a good practice solution though, please tell :)
I suggest you take a look at XNA's samples projects (google it). They're well designed and might give you some hints.
Also, since you're using AS3, you could use the event system to dispatch message to other entities. For example, instead of passing your Main to your Vehicle class, make your Main (or whatever else interested) a listener of your Vehicle class. Then, let's say the car crash and you want to restart the game, dispatch an event, for example CAR_CRASHED. The listeners of your car should do something based on this message. If you want to understand the event system, type EventDispatcher, highlight it and hit F1 in your Flash IDE.