OO Design, open/closed principle question - language-agnostic

I've been thinking about this object oriented design question for a while now and have unable to come up with a satisfactory solution, so thought I'd throw it open to the crowds here for some opinions.
I have a Game class that represents a turn based board game, we can assume it's similar to Monopoly for the purposes of this question.
In my design I have a Player class containing a method TakeTurn.
The Game loops through all Players and calls the TakeTurn method to do all the necessary things to complete the turn.
I want to be able to have n number of players, and be able to set an arbitrary number of them to be computer players.
So, my thought was to have a HumanPlayer class and a ComputerPlayer class, both of which derive from Player.
The Game knows only the Player class and simply calls the TakeTurn method on each Player in turn.
My problem comes in the fact that ComputerPlayer objects can be completely automated, i.e. keeping with the Monopoly example, can decide to buy a property using some piece of logic.
Now, with the HumanPlayer object, it needs to get an input from the actual user to be able to buy a property for instance, which seems to imply a different interface and potentially mean they shouldn't derive
I haven't been able to come up with a good solution to the problem without having the Game class know the actual implementations of the various Player classes explicitly.
I could always make the assumption in the Game class that there will only ever be human and computer players and effectively close it for extension, but it doesn't seem like good OO programming.
Any opinions on this would be appreciated.

I think you should not let the Game class handle IO.
this way, the (blocking) TakeTurn method will hide from the game board the means of implementation. it can use other objects to communicate with the user.
All the Game class should concern itself with is the state of the board and the turn. the players should all implement a single Player interface, and hide all implementation from the Game.

If the Game is managing the game state and doing I/O, the Game is doing too much.
You want Game to be tightly focused on just rules and turns and state changes.
Game doesn't know what a player is; it only knows that it has players.
You want Players to examine the Game state and execute the legal actions during their turns.
Human Players and the Game as a whole both share a common I/O package that shows game state and prompts humans for their input.
You can make good use of the Java Observable by making the I/O package an Observer of the Game. That way, Game state changes are reported to the I/O for display or logging or both.

I would probably not have two HumanPlayer and ComputerPlayer classes, but a single Player class which is configured at creation time with the proper input strategy.
The way the player obtains information to decide its move in the next turn of the game is the only thing that varies (from the original problem description, at least), so just encapsulate that in a separate abstraction.
Whatever high-level class that sets up the game should also create the two sets of players (one human, another computer-simulated), with the proper input strategy for each, and then simply give these player objects to the game object. The Game class will then only call the TakeTurn method on the given list of players, for each new turn.

Instead of telling the game class there is only ever one human, why not let it get that input during the menu/initialization of the game? If there are more players, that can be decided via some form of input (select players in the menu), prior to the game class initialization.

The interface that Player presents to Game is orthogonal to the behaviour of derived Player classes.
The fact that the implementation of TakeTurn varies depending on the concrete type of the Player object should not be a cause for concern.

I think the Game Class should not concern about any implementations of the Player classes, and also ignore the User Interface.
Any user input needs to be handled by the HumanPlayer class.

I'd say, the Game class shouldn't care if this is a computer player or a human player. It should always call TakeTurn on the next player class. If this is a human player, it is the responsibility of the Player class, to communicate with the user and ask the user what to do. That means it will block till the user made up his mind. As usually UI interaction takes place in the main thread of an application, it is only important that a blocking TakeTurn won't block the application as a whole, otherwise user input cannot be processed while Game waits for TakeTurn.

Instead of the Game class calling TakeTurn on all the players the players should call TakeTurn on the Game class and the Game class should validate if the right player is taking his turn.
This should help solve the User and Computer player problem.

Im am not sure if this is what you want
public abstract class Player
{
int position;
DecisionMaker decisionDependency;
...
public void TakeTurn()
{
position += RollDice();
GameOption option GetOptions(position);
MakeDescion(option);
}
protected int RollDice()
{
//do something to get the movement
}
protected abstract void MakeDecision(GameOption option);
}
Public class ComputerPlayer : Player
{
public ComputerPlayer()
{
decisionDependency = new AIDecisionMaker();
}
protected override void void MakeDecision(GameOption option)
{
decisionDependency.MakeDecision(option);
//do stuff, probably delgate toan AI based dependency
}
}
Public class HumanPlayer : Player
{
public HumanPlayer()
{
decisionDependency = new UIDecisionMaker();
}
protected override void void MakeDecision(GameOption option)
{
decisionDependency.MakeDecision(option);
//do stuff, probably interacting with the a UI or delgate to a dependency
}
}

Related

Runtime game values class

I'm newbie on libgdx and game developing logic. So i need your advice.
Here is my problem. I'm trying to make a game and i need to know how should i collect game values. Like hp, coins, score, attack speed ect. There's two side on my game. Player and enemy. I made two classes, LeftSide(this is player) and RightSide(this is enemy). Then i notice i didn't take user name and i can not think about this. What should i do? Should one class be optimized? or Should more classes, like i said before for player and enemy and maybe user's names.
Edit:
I ask this question because i don't know whis is most good for performance.
Option 2 is cleaner, if only because it can be factored down to two instances of a player class. Option 1 will be harder to maintain and will likely have duplicated logic.

How to avoid tight coupling?

I have been trying to get my head around this problem for the last week and can't seem to find a solution that doesn't either require a singleton or tight coupling.
I am developing a 3D space game, an early demo of which is here...
www.sugarspook.com/darkmatters/demo.html
... and I'm getting to the point of adding Missions which the player will be able to select from the heads up display (Hud class).
The structure of the game is:
The Game class contains the Hud and the ObjectsList class.
The ObjectsList class contains various game Objects, including the Player, the various kinds of ship, planets, and Orbitals (space stations).
Missions get instantiated when the Player gets to within a certain distance of an Orbital.
Missions are added to a MissionsList class, itself within the ObjectsList.
Missions can become unavailable and expire without warning (as if they are selected by another pilot) so the list displayed on the Hud is dynamic and updated regularly.
Previously I've had the Missions dispatching events up to Game which in turn informs Hud of the change. This seems a little clunky to me, as there are various deeper 'levels' to the Hud that the information needs to be passed down to. I end up with a lot of the same functions all the way down the chain.
The solution I was thinking of involved injecting a reference to the MissionsList class into the Hud, enabling it to listen for updates from the Missonslist. I've heard that it's bad practise to mix the state of something with its display, but I don't see how else to get the 'live' list of Missions to the Hud. In contrast, if the Hud contains only display details without reference to the Mission object that generated those details, when a player selects a Mission from the Hud how can I determine which Mission has been chosen?
Is tight coupling in this case OK? Or should I use a singleton to communicate to the Hud?
If there is something fundamentally wrong with anything I'm suggesting I welcome being told what that is and what is the best solution.
Thanks.
Well the simple answer is why not couple via an intermediate interface?
interface IMissionList
{
ObservableCollection<IMission> Missions{get;}
}
Then in your Dependency Injection bind that to something that can resolve to a instance, singleton or constant or etc...
then inject it into your Hud's constructor
Hud(IMissionList missionList){}
Now you are loosely coupled to a contract, the implementation of-which can be changed at any point, so long as the implementation adheres to the contract. Also, due to injection your Hud only has to concern it self with using IMissionList rather than also finding it.
[Edit] Sorry, this is C#, but hopefully the idea is of use. See for actionscript interfaces and Dependency Injection for Actionscript

Proper object oriented structure for global classes

What are the pros and cons of using a singleton class for sound management?
I am concerned that it's very anti-OOP in structure and don't want to potentially get caught up going down the wrong path, but what is a better alternative?
It's an awkward topic but I'd say that a sound manager style class is a good candidate for a class that should not be initialized.
Similarly, I would find it OK if a keyboard input manager style class was a completely static class.
Some notes for my reasoning:
You would not expect more than one instance that deals with all sounds.
It's easily accessible, which is a good thing in this case because sound seems more like an application-level utility rather than something that should only be accessed by certain objects. Making the Player class for a game static for example would be a very poor design choice, because almost no other classes in a game need reference directly to the Player.
In the context of a game for example, imagine the amount of classes that would need a reference to an instance of a sound manager; enemies, effects, items, the UI, the environment. What a nightmare - having a static sound manager class eliminates this requirement.
There aren't many cases that I can think of where it makes no sense at all to have access to sounds. A sound can be triggered relevantly by almost anything - the move of the mouse, an explosion effect, the loading of a dialogue, etc. Static classes are bad when they have almost no relevance or use to the majority of the other classes in your application - sound does.
Anyways; that's my point of view to offset the likely opposing answers that will appear here.
They are bad because of the same reasons why globals are bad, some useful reading :
http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx
A better alternative is to have it as a member of your application class and pass references of it to only modules that need to deal with sound.
"Managers" are usually classes that are very complex in nature, and thus likely violate the Single Responsibility Principle. To paraphrase Uncle Bob Martin: Any time you feel yourself tempted to call a class "Manager" of something - that's a code smell.
In your case, you are dealing with at least three different responsibilities:
Loading and storing the sounds.
Playing the sounds when needed.
Controlling output parameters, such as volume and panning.
Of these, two might be implemented as singletons, but you should always be very careful with this pattern, because in itself, it violates the SRP, and if used the wrong way, it causes your code to be tightly coupled (instead, you should use the Dependency Injection pattern, possibly by means of a framework, such as SwiftSuspenders, but not necessarily):
Loading and storing sounds is essentially a strictly data related task, and should thus be handled by the SoundModel, of which you only need one instance per application.
Controlling output parameters is something that you probably want to handle in a central place, to be able to change global volume settings, etc. This may be implemented as a singleton, but more likely is a tree-like structure, where a master SoundController handles global settings, and several child SoundControllers are responsible for more specific contexts, such as UI sound effects, game sounds, music, etc.
Playing the sound is something, which will occur in many places, and in many different ways: There may be loops (to which you need to keep references to be able to stop them later), or effect sounds (which are usually short and play only once), or music (where each song is usually played once, but needs subsequent songs to be started automatically, when the end is reached). For each of those variations (and whichever ones you come up with), you should create a different class, which implements a common SoundPlayer interface, e.g. LoopSoundPlayerImpl, SequentialSoundPlayerImpl, EFXSoundPlayerImpl, etc. The interface should be as simple as play(),pause(), rewind() - you can easily exchange those later, and will not have any problems with tightly coupled libraries.
Each SoundPlayer can hold a reference to both the master SoundController an its content-specific one, as well as - possibly - the SoundModel. These, then can be static references: Since they are all parts of your own sound plugin, they will usually be deployed as a package, and therefore tight coupling won't do much damage here - it is important, though, not to cross the boundary of the plugin: Instantiate everything within your Main partition, and pass on the instances to all classes, which need them; only have the SoundPlayer interface show up within your game logic, etc.

Managing collision detection in games

So my question isn't about the how-to of collision detection, but is more of a broad 'what code should own collision detection'. I've written some game in the past(relatively simple 2D Flash games) and it got me thinking of which code should own collision detection?
Let me clarify - say in a game I have a group of enemies and a group of projectiles the player has fired. So in the past I've had say an EnemyManager class, that every frame updates the positions of the enemies and likewise for the player projectiles had a PlayerProjectilesManager class that moved around the bullets. That's cool - everything is fine and dandy. But then, I decide I want the bullets to affect the enemies(crazy I know!). So that means somewhere in the code I need to:
Figure out which bullets and enemies are colliding(I don't care how for this question)Figure out the response to each collision
So basically what I've done in the past is just have the EnemyManager class take 'ownership' of the collisions, and during its update loop it finds the player bullets that collide with enemy bullets(i.e. Step 1) and also calls code for both objects to handle the collision (e.g. the enemy losses health, the bullet disappears) (i.e. Step 2). So I've given control of the collision detection and collision 'reaction' to the EnemyManager.
A couple comments about that:
It feels vary arbitrary to me that the EnemyManager is in 'control' instead of the PlayerProjectilesManager
Both collision detection and collision 'reaction' are handled by the same owner, this isn't a requirement from my point of view
What's forming in my mind is a 3rd party entity managing collision detection. For instance have a CollisionManager which has code that know's which other Managers need to have collisions detected. That leads to other questions like what interfaces do the 'Managers' need to expose for efficient collision detection without exposing too many innards to the CollisionManager. Then I suppose the CollisionManager what broadcast some sort of an event, containing which 2 objects collided etc... and perhaps the EnemyManager/PlayerProjectilesManager could separately listen for these events and react accordingly and separately. Starting to make sense in my mind. :)
Thoughts? Almost every game has collision detection, so I'm sure this has been discussed before. :)
this is a nice question. Personally, I would not complicate it so much by using "Managers". Let's say we have a GameEngine, which runs the game in its main loop. This main loop could consist of 3 steps: get the user input, update the state of all objects in the game (based on the user input) and finally draw everything again on the screen.
Everything about the collision detection is done in the second step - when updating the objects' state. Let's say all objects in the game are stored in a pool. This includes the player, the bullets, the enemies and even the world (if you'd like the world to be affected as well somehow). All the different objects could have some common properties - they could be Drawable, Movable, Collidable e.t.c. (think like implementing an interface or extending a base class to have these properties)
For each of these properties I would have a class that do something with all the objects in the pool. Like Mover.moveAll(objectsFromPool). This will move all objects, which are Movable.
The same for collision detection -> after we've relocated the objects with the Mover, then we check for collision with CollisionDetector.cehckAll(objectsFromPool). This checkAll() method will do the actual collision detection between the objects themselves, knowing their coordinates. If an object is Collidable, the CollisionDetector will invoke its method onCollide(withOtherObject) and then the object itself reacts properly, depending what other object hit it. Let's say, if the player is touched by the enemy body, they will both step back for example. If a bullet is hits by another bullet - they will both be marked for deletion. If the enemy is hit by a bullet, then some damage will happen and the bullet will be marked for deletion. All these reactions should be in the corresponding objects themselves.The collision detector applies its algorithms to detect collision between any two objects and then invokes their onCollide(withOtherObjct) method.
If an object is not Collidable, it will be simply ignored by the CollisionDetector (for examples rain particles or dust are not Collidable).
I hope I managed to express myself correct :)
Questions specific to game development are best suited to https://gamedev.stackexchange.com/ by the way.
So in the past I've had say an EnemyManager class
I consider any SomethingManager class to be a sign that your code isn't organised accurately yet. For the most part, objects should manage themselves. If they can't, that implies there is some external information about them, and that information probably has a representation more specific than 'manager'. 3 game-specific examples might be GameWorld, GameRegion, or GameLevel. Enemies exist within a world, or a region of the world, or a current game level, so have such an object maintain its list of enemies.
and likewise for the player projectiles had a PlayerProjectilesManager class
Projectiles too would live in some sort of game space, a world, region, or level.
By now, you can probably guess that one of the above objects can (and probably should) be responsible for owning all the above objects (perhaps indirectly, via a container class, but not via a heavyweight manager of any sort) and responsible for detecting collisions and resolving them.

Who should a method belong to?

I'm trying to design a simple game ---Pong, Arkanoid--- using strictly "Proper OO", whatever that means.
So, by designing myself to death, I'm trying to get to a point where I'll know what to do or not do next time...
Who should handle, for example, colissions? And scorekeeping?
My first idea was giving a couple jobs to the ball, but that started expanding exponentially into a god object: The ball'd know where it is, who it crashed into, and report to the scorekeeping objects.
And that's too much for the poor ball.
rule of thumb:
if an object logically owns all of the state involved, then it owns the methods that use that state
if a method requires state from more than one object:
if a container object owns all of the objects used by the method, then it owns the method, too
otherwise you need a 'bridge' object to own the utility method
unless there is a strong argument for one object to be the 'controller' for the method (can't think of an example offhand though)
in your case, the 'gameboard' or 'game environment' would probably have a 'game physics' class (or group of methods) that owned the collision-detection (utility/bridge) methods
A good or bad design reveals itself by how well it accomodates unexpected requirements, so I would suggest keeping a stock of potential "game features" handy to inform your design reflexions. Since you're doing this as a learning project you can afford to go crazy.
Arkanoid is a very good choice for this, it offers so many options. Make different bricks score different amounts of points. Make some bricks change the score of other bricks when hit. Make some bricks require multiple hits. Give superpowers to the ball, paddle, or bricks. Vary these powers: one of them makes the ball keyboard-controllable, another makes it transparent, another reverses "gravity", and so on. Make bricks drop objects.
The goal is that when you make such a change, it impacts the minimum possible number of classes and methods. Get a feel for how your design must change to fit this criterion.
Use an IDE that has a Refactoring menu, in particular the move method refactoring. (If you haven't, read the book Refactoring.) Experiment with placing your various methods here and there. Notice what becomes hard to change when the method is placed "wrong", and what becomes easier when you place it elsewhere. Methods are placed right when objects take care of their own state; you can "tell" an object to do something, rather than "ask" it questions about its state and then make decisions based on its answers.
Let's assume that in your design each sprite is an object instance. (You could choose other strategies.) Generally, motion alters the state of a sprite, so the method that describes motion for a particular kind of sprite probably belongs on that sprite's class.
Collision detection is a sensitive part of the code, as it potentially involves checking all possible pairs of sprites. You'll want to distinguish checking for collisions and informing objects of collisions. Your ball object needs to alter its motion on colliding with the paddle, for instance. But the algorithm for detecting collisions in general won't belong on the ball class, since other pairs of objects may collide with consequences that matter to the game.
And so on...
Keep in mind that objects can also exist for logical elements of a given problem (not only real elements, like balls and boards).
So for collision detection, you could have a CollidingElement class that handles the position and shape states. This object can then be embedded by composition in any object that should collide in the game and delegate any needed method call to it.
It really depends on your implementation, but I imagine you'd have a "gameboard" object to manage score keeping, or maybe a goal object on each side. As far as collisions I think you might want to pass events between the objects. I think any object should know its location though.
in most games you have statics and actors . .. actors move around and each of them independently figures out when they collide with something since they are aware of their shape and extents