Background:
I recently completed a tic-tac-toe game in AS3, using some simple function-based code I had written in C many years ago.
Now I’m on a quest to do it the “right way” using OOP techniques and best practices.
Everything is now divided into neat little packages, it looks pretty, and the last part of my journey is to get all the little buggers to communicate with each other.
My dilemma:
I want to move the code which holds the game state from my main to it’s own class in com.okaygraphics.model.GameState.
The problem is nearly every other package gets and sets these game state properties.
I’m trying to figure out the simplest way to encapsulate this stuff, while still allowing my other classes to access it.
Where I’m at:
package com.okaygraphics.model{
public class GameState {
private var _player1State:uint=0x00000000;
private var _player2State:uint=0x00000000;
private var _activePlayer:int=0;
public function get p1GameState():uint {
return _player1State;
}
public function set p1GameState(value:uint):void {
_player1State = value;
}
public function get p2GameState():uint {
return _player2State;
}
public function set p2gameState(value:uint):void {
_player2State = value;
}
public function get activePlayer():int {
return _activePlayer
}
public function set activePlayer(value:int):void {
_activePlayer = value;
}
}
}
Qestions:
1) Do I need a constructor? I mean, my program will never have more than one GameState. If I should call my getters/setters as instance methods, how do I get each other class to reference the SAME instance from their respective packages?
2) Do I even need getters and setters? Perhaps the class could just have 3 public properties? If so, how would I acheive the proper scope with regard to my other classes?
3) Should I assign everything to the class itself using the static keyword? If so, how would I implement and use those static methods?
4) Is this a mistake? Did I totally just program myself into a corner?
This seems like a pretty common task, yet one that I still don’t fully understand. A brief explaination, some links, or the name of the technique I need would be greatly appreciated.
Thanks in advance,
-Max
You could approach this several different ways.
You could make
GameStatea Singleton. That’ll ensure that any instance ofGameStateis the same instance. Here’s how to do that:Then, anytime you want to get
GameState, you use this syntax:By using a Singleton, you can still use the getters and setters you’ve already made, but the Singleton will ensure that every class that accesses
GameStatewill be accessing the same instance.Or, if you don’t want to use a Singleton, you could make those private vars public static vars instead:
You’ll no longer need the getters/setters, and you’d set them from other classes like this:
Either way you set up the Model, remember to put thought into how it’ll be communicated with by the Controller and View. Remember that separation of Model and View is one of the main goals of the MVC pattern.