XNA phase management - xna-4.0

I am making a tactical RPG game in XNA 4.0 and was wondering what the best way to go about "phases" is? What I mean by phases is creating a phase letting the player place his soldiers on the map, creating a phase for the player's turn, and another phase for the enemy's turn.
I was thinking I could create some sort of enum and set the code in the upgrade/draw methods to run accordingly, but I want to make sure this is the best way to go about it first.
Thanks!
Edit: To anaximander below:
I should have mentioned this before, but I already have something implemented in my application that is similar to what you mentioned. Mine is called ScreenManager and Screen but it works exactly in the same way. I think the problem is that I am treating screen, phase, state, etc, to be different things but in reality they are the same thing.
Basically what I really want is a way to manage different "phases" in a single screen. One of my screens called map will basically represent all of the possible maps in the game. This is where the fighting takes place etc. I want to know what is the best way to go about this:
Either creating an enum called FightStage that holds values like
PlacementPhase,PlayerPhase, etc, and then split the Draw and
Update method according to the enum
Or create an external class to manage this.
Sorry for the confusion!

An approach I often take with states or phases is to have a manager class. Essentially, you need a GamePhase object which has Initialise(), Update(), Draw() and Dispose() methods, and possibly Pause() and Resume() as well. Also often worth having is some sort of method to handle the handover. More on that later. Once you have this class, inherit from it to create a class for each phase; SoldierPlacementPhase, MovementPhase, AttackPhase, etc.
Then you have a GamePhaseManager class, which has Initialise(), Update(), Draw() and Dispose() methods, and probably a SetCurrentPhase() method of some kind. You'll also need an Add() method to add states to the manager - it'll need a way to store them. I recommend a Dictionary<> using either an int/enum or string as the key. Your SetCurrentPhase() method will take that key as a parameter.
Basically, what you do is to set up an instance of the GamePhaseManager in your game, and then create and initialise each phase object and add it to the manager. Then your game's update loop will call GamePhaseManager.Update(), which simply calls through to the current state's Update method, passing the parameters along.
Your phases will need some way of telling when it's time for them to end, and some way of handling that. I find that the easiest way is to set up your GamePhase objects, and then have a method like GamePhase.SetNextPhase(GamePhase next) which gives each phase a reference to the one that comes next. Then all they need is a boolean Exiting with a protected setter and a public getter, so that they can set Exiting = true in their Update() when their internal logic decides that phase is over, and then in the GamePhaseManager.Update() you can do this:
public void Update(TimeSpan elapsed)
{
if (CurrentPhase.Exiting)
{
CurrentPhase.HandOver();
CurrentPhase = CurrentPhase.NextPhase;
}
CurrentPhase.Update(elapsed);
}
You'll notice I change phase before the update. That's so that the exiting phase can finish its cycle; you get odd behaviour otherwise. The CurrentPhase.HandOver() method basically gets the current phase to pass on anything the next phase needs to know to carry on from the right point. This is probably done by having it call NextPhase.Resume() internally, passing it any info it needs as parameters. Remember to also set Exiting = false in here, or else it'll keep handing over after only one update loop.
The Draw() methods are handled in the same way - your game loop calls GamePhaseManager.Draw(), which just calls CurrentPhase.Draw(), passing the parameters through.
If you have anything that isn't dependent on phase - the map, for example - you can either have it stored in the GamePhaseManager and call its methods in GamePhaseManager's methods, you can have the phases pass it around and have them call its methods, or you can keep it up at the top level and call it's methods alongsideGamePhaseManager's. It depends how much access the phases need to it.
EDIT
Your edit shows that a fair portion of what's above is known to you, but I'm leaving it there to help anyone who comes across this question in future.
If already you have a manager to handle stages of the game, my immediate instinct would be to nest it. You saw that your game has stages, and built a class to handle them. You have a stage that has its own stages, so why not use the stage-handling code you already wrote? Inherit from your Screen object to have a SubdividedScreen class, or whatever you feel like calling it. This new class is mostly the same as the parent, but it also contains its own instance of the ScreenManager class. Replace the Screen object you're calling map with one of these SubdividedScreen objects, and fill its ScreenManager with Screen instances to represent the various stages (PlacementPhase, PlayerPhase, etc). You might need a few tweaks to the ScreenManager code to make sure the right info can get to the methods that need it, but it's much neater than having a messy Update() method subdivided by switch cases.

Related

How can I look inside an AppleScript “whose” clause to optimize resolving a script object specifier?

The documentation for -[NSObject scriptingValueForSpecifier:] says:
You can override this method to customize the evaluation of object specifiers…
I want to do this to make AppleScript lookups in my app more efficient. There are certain types of whose tests where I could do a hash lookup instead of having AppleScript ask for every single object and then query their properties one-by-one. The problem is that if I receive a NSWhoseSpecifier, I can get its test, which is a NSSpecifierTest, but there doesn’t seem to be a way to look inside the NSSpecifierTest to figure out the property being tested. Everything but the initializers and the -isTrue method are private.
Let's make a distinction. If you merely want to customize the values returned by a whose clause — in the sense of fine-tuning results — then you would override scriptingValueForSpecifier for the object in question. For example, say you have an object called 'box' that has a property called 'color,' and you want a statement like every box whose color is blue to also return boxes whose color is 'aqua,' 'teal,' or 'navy' (which are all shades of blue), then you would override scriptingValueForSpecifier to implement that.
However, if your goal is to make a more efficient form of whose test, you're probably going to have to implement appropriate methods from the NSScriptingComparisonMethods protocol. These are the routines that AppleScript uses to evaluate scripting object comparisons through NSSpecifierTest (which is what NSWhoseSpecifier) relies on). Again, you'd override these methods on your object(s) to provide different methods for doing evaluations.
As a last resort, you might try subclassing NSWhoseSpecifier or NSSpecifierTest, with the understanding that these are opaque classes for which Apple discourages subclassing. I'm not entirely certain how you would implement those subclasses; you'd probably have to register your subclass with NSScriptSuiteRegistry commands.
It looks like it will be possible to override -scriptingValueForSpecifier: and then ask the NSScriptObjectSpecifier for its descriptor. This produces an NSAppleEventDescriptor that has the needed information, but it has to be interpreted manually.

Replace lots of switches with polymorphism but no type code

I have a class which could benefit with the state pattern. However the common "Replace Type Code with State/Strategy" refactoring does not seem to fit well in my case: the state is calculated by watching other objects, there is no type code variable.
Most of my class code is just "calculating" some state when it is called, and running the functions for that state.
Forcing a type code variable feels wrong because:
I will be forced to call an "updateState()" function in every place where the polymorphic functions are used.
My class will no longer be 100% behavior, which I would rather habe instead of some internal state.
Since the state must be calculated every single time its functions are called, I am wonder if I am thinking about the wrong pattern.
Normally I refactor this:
if (this.someOtherThingIsRunning()) {
...
} else {
...
}
like this:
typecode.doSomething()
// that being polymorphic
it seems strange doing:
updateTypeCode()
typecode.doSomething()
Does the state pattern applies to this case? Is there any alternative strategy pull from polymorphism without a type code?
While writing my question, I realized that maybe I could just make the type code a function and return a temporal (function scope) type code. Like:
typecode().doSomething()
This solution would never store the state, which is what I want to avoid. However I am still wondering if my problem started because I am using the wrong pattern.
If you're open to storing the state, maybe think about combining State and Observer to modify the state as the dependent classes change (rather than checking on every call). There's only certain models that this will work for though.
Otherwise you might as well say object.doSomething() and have the checks inside doSomething(). In this case using design patterns doesn't present any significant advantages (though if you loosen up slightly on the definitions of design patterns, many things would be considered such). I'd probably go with:
doSomething()
{
if (someOtherThingIsRunning())
doOneThing();
else
doAnotherThing();
}
The alternative (that you already suggested) is to have the above checks in typecode() and to return another class that contains the method doSomething().

Ruby: slow down evaluation

I'm interested in simply slowing down the evaluation of ruby code. Of course I know about using sleep(), but that does not solve my problem.
Rather, I want to slow down every single object instantiation and destruction that happens in the VM.
Why? So I can learn about how particular procedures in ruby work by watching them being carried out. I recently learned about ObjectSpace and the ability to see/inspect all the objects currently living in a Ruby VM. It seems that building a simple realtime display of the objects and properties of those objects within the ObjectSpace and then slowing down the evaluation would achieve this.
I realize there may be ways of viewing in realtime more detailed logs of what is happening inside the ruby process, including many procedures that are implemented at low-level, below the level of actual ruby code. But I think simply seeing the creation and destruction of objects and their properties in realtime would be more edifying and easier to follow.
You could be interested in the answer to this question: getting in-out from ruby methods
With small edits to the code reported there, you could add a sleep to each method call and follow the code execution.
If you want to output some information every time an object is instantiated, you could do that by overriding Class#new. Here's an example:
class Class
alias old_new new
def new(*args)
puts "Creating: #{self.inspect}"
sleep 0.1
old_new(*args)
end
end
class Point
end
class Circle
end
The alias old_new new line creates a backup new method, so we can have the old behaviour. Then, we override the new method and put some code to inspect the subject class and sleep for just a bit for the sake of better readability. Now, if you invoke Point.new, you'll see "Creating: Point". Circle.new will display a "Creating: Circle" and so on. Any objects that are created will be logged, or at least their classes, with a small delay.
The example is a modified version of the one from here.
As for destruction of objects, I'm not sure if there's a sensible way to do it. You could try to override some method in the GC module, but garbage collection is only initiated when it's necessary (as far as I'm aware), so you could easily play with ruby for a while without it ever happening. It probably wouldn't be very useful anyway.
I think the problem is not that ruby is too fast.
In your case you should use some software architecture, for example Model-View-Controller.
It could be in this way. In View you can show options at which speed the Controller should show information for you or you're able to slow down or increase the speed of showing information. Then Controller evaluate small steps (calling methods in Model) and rendered the results of evaluation in the View.
The View is not always the browser or window application, it could be also just a simple terminal.

Best practices when writing glue code

I asked this question to get some opinions on the subject of glue code.
For example, imagine you have a class (pseudocode):
class MyClass
int attribute a
string attribute b
And to represent that data model, you have BOTH a slider and a text box to represent a, and a text box and say... the window label to represent b.
Obviously, when one of these view objects is changed, you want to update the others. However, updating the entire view is obviously inefficient.
method onSomethingHappened(uiObject)
model.appropriateAttribute = uiObject.value
The question is, what is your opinion on what to do next? Should the model object implement a callback that notifies a listener when the value has been changed, allowing one to write glue code like:
method modelChangedCallback(model, attribute)
uiObject1.value = model.a
uiObject2.value = model.a
Where you might examine what the attribute that changed is, and respond accordingly? This is the model in Objective-C and Cocoa on Mac, for the most part.
OR, would you rather have the responsibility lie completely in the glue code?
method onSomethingHappened(uiObject)
model.appropriateAttribute = uiObject.value
self.updateForAttribute("appropriateAttribute")
Both of these approaches can get pretty hairy (as is the problem with glue code) when your project gets large. Maybe there are other approaches. What do you think?
Thanks for any input!
For me I think it comes down to where the behavior is needed. In the situation you describe, the fact that you are binding multiple controls to a property is what is driving the requirement, so it doesn't make sense to add code to the model to support that.
In a web-based model I would probably put the logic in the web page since that can be done rather cheaply using Javascript. If I don't have that luxury (i.e. I'm dealing with a "dumb" view), then it would probably make sense to do it in the controller, or model glue code. If this sort of thing becomes common enough, I may go as far as creating some form of generic helper to reduce the amount of boiler-plate code I have to deal with.

TDD and DI: dependency injections becoming cumbersome

C#, nUnit, and Rhino Mocks, if that turns out to be applicable.
My quest with TDD continues as I attempt to wrap tests around a complicated function. Let's say I'm coding a form that, when saved, has to also save dependent objects within the form...answers to form questions, attachments if available, and "log" entries (such as "blahblah updated the form." or "blahblah attached a file."). This save function also fires off emails to various people depending on how the state of the form changed during the save function.
This means in order to fully test out the form's save function with all of its dependencies, I have to inject five or six data providers to test out this one function and make sure everything fired off in the right way and order. This is cumbersome when writing the multiple chained constructors for the form object to insert the mocked providers. I think I'm missing something, either in the way of refactoring or simply a better way to set the mocked data providers.
Should I further study refactoring methods to see how this function can be simplified? How's the observer pattern sound, so that the dependent objects detect when the parent form is saved and handle themselves? I know that people say to split out the function so it can be tested...meaning I test out the individual save functions of each dependent object, but not the save function of the form itself, which dictates how each should save themselves in the first place?
First, if you are following TDD, then you don't wrap tests around a complicated function. You wrap the function around your tests. Actually, even that's not right. You interweave your tests and functions, writing both at almost exactly the same time, with the tests just a little ahead of the functions. See The Three Laws of TDD.
When you follow these three laws, and are diligent about refactoring, then you never wind up with "a complicated function". Rather you wind up with many, tested, simple functions.
Now, on to your point. If you already have "a complicated function" and you want to wrap tests around it then you should:
Add your mocks explicitly, instead of through DI. (e.g. something horrible like a 'test' flag and an 'if' statement that selects the mocks instead of the real objects).
Write a few tests in order to cover the basic operation of the component.
Refactor mercilessly, breaking up the complicated function into many little simple functions, while running your cobbled together tests as often as possible.
Push the 'test' flag as high as possible. As you refactor, pass your data sources down to the small simple functions. Don't let the 'test' flag infect any but the topmost function.
Rewrite tests. As you refactor, rewrite as many tests as possible to call the simple little functions instead of the big top-level function. You can pass your mocks into the simple functions from your tests.
Get rid of the 'test' flag and determine how much DI you really need. Since you have tests written at the lower levels that can insert mocks through areguments, you probably don't need to mock out many data sources at the top level anymore.
If, after all this, the DI is still cumbersome, then think about injecting a single object that holds references to all your data sources. It's always easier to inject one thing rather than many.
Use an AutoMocking container. There is one written for RhinoMocks.
Imagine you have a class with a lot of dependencies injected via constructor injection. Here's what it looks like to set it up with RhinoMocks, no AutoMocking container:
private MockRepository _mocks;
private BroadcastListViewPresenter _presenter;
private IBroadcastListView _view;
private IAddNewBroadcastEventBroker _addNewBroadcastEventBroker;
private IBroadcastService _broadcastService;
private IChannelService _channelService;
private IDeviceService _deviceService;
private IDialogFactory _dialogFactory;
private IMessageBoxService _messageBoxService;
private ITouchScreenService _touchScreenService;
private IDeviceBroadcastFactory _deviceBroadcastFactory;
private IFileBroadcastFactory _fileBroadcastFactory;
private IBroadcastServiceCallback _broadcastServiceCallback;
private IChannelServiceCallback _channelServiceCallback;
[SetUp]
public void SetUp()
{
_mocks = new MockRepository();
_view = _mocks.DynamicMock<IBroadcastListView>();
_addNewBroadcastEventBroker = _mocks.DynamicMock<IAddNewBroadcastEventBroker>();
_broadcastService = _mocks.DynamicMock<IBroadcastService>();
_channelService = _mocks.DynamicMock<IChannelService>();
_deviceService = _mocks.DynamicMock<IDeviceService>();
_dialogFactory = _mocks.DynamicMock<IDialogFactory>();
_messageBoxService = _mocks.DynamicMock<IMessageBoxService>();
_touchScreenService = _mocks.DynamicMock<ITouchScreenService>();
_deviceBroadcastFactory = _mocks.DynamicMock<IDeviceBroadcastFactory>();
_fileBroadcastFactory = _mocks.DynamicMock<IFileBroadcastFactory>();
_broadcastServiceCallback = _mocks.DynamicMock<IBroadcastServiceCallback>();
_channelServiceCallback = _mocks.DynamicMock<IChannelServiceCallback>();
_presenter = new BroadcastListViewPresenter(
_addNewBroadcastEventBroker,
_broadcastService,
_channelService,
_deviceService,
_dialogFactory,
_messageBoxService,
_touchScreenService,
_deviceBroadcastFactory,
_fileBroadcastFactory,
_broadcastServiceCallback,
_channelServiceCallback);
_presenter.View = _view;
}
Now, here's the same thing with an AutoMocking container:
private MockRepository _mocks;
private AutoMockingContainer _container;
private BroadcastListViewPresenter _presenter;
private IBroadcastListView _view;
[SetUp]
public void SetUp()
{
_mocks = new MockRepository();
_container = new AutoMockingContainer(_mocks);
_container.Initialize();
_view = _mocks.DynamicMock<IBroadcastListView>();
_presenter = _container.Create<BroadcastListViewPresenter>();
_presenter.View = _view;
}
Easier, yes?
The AutoMocking container automatically creates mocks for every dependency in the constructor, and you can access them for testing like so:
using (_mocks.Record())
{
_container.Get<IChannelService>().Expect(cs => cs.ChannelIsBroadcasting(channel)).Return(false);
_container.Get<IBroadcastService>().Expect(bs => bs.Start(8));
}
Hope that helps. I know my testing life has been made a whole lot easier with the advent of the AutoMocking container.
You're right that it can be cumbersome.
Proponent of mocking methodology would point out that the code is written improperly to being with. That is, you shouldn't be constructing dependent objects inside this method. Rather, the injection API's should have functions that create the appropriate objects.
As for mocking up 6 different objects, that's true. However, if you also were unit-testing those systems, those objects should already have mocking infrastructure you can use.
Finally, use a mocking framework that does some of the work for you.
I don't have your code, but my first reaction is that your test is trying to tell you that your object has too many collaborators. In cases like this, I always find that there's a missing construct in there that should be packaged up into a higher level structure. Using an automocking container is just muzzling the feedback you're getting from your tests. See http://www.mockobjects.com/2007/04/test-smell-bloated-constructor.html for a longer discussion.
In this context, I usually find statements along the lines of "this indicates that your object has too many dependencies" or "your object has too many collaborators" to be a fairly specious claim. Of course a MVC controller or a form is going to be calling lots of different services and objects to fulfill its duties; it is, after all, sitting at the top layer of the application. You can smoosh some of these dependencies together into higher-level objects (say, a ShippingMethodRepository and a TransitTimeCalculator get combined into a ShippingRateFinder), but this only goes so far, especially for these top-level, presentation-oriented objects. That's one less object to mock, but you've just obfuscated the actual dependencies via one layer of indirection, not actually removed them.
One blasphemous piece of advice is to say that if you are dependency injecting an object and creating an interface for it that is quite unlikely to ever change (Are you really going to drop in a new MessageBoxService while changing your code? Really?), then don't bother. That dependency is part of the expected behavior of the object and you should just test them together since the integration test is where the real business value lies.
The other blasphemous piece of advice is that I usually see little utility in unit testing MVC controllers or Windows Forms. Everytime I see someone mocking the HttpContext and testing to see if a cookie was set, I want to scream. Who cares if the AccountController set a cookie? I don't. The cookie has nothing to do with treating the controller as a black box; an integration test is what is needed to test its functionality (hmm, a call to PrivilegedArea() failed after Login() in the integration test). This way, you avoid invalidating a million useless unit tests if the format of the login cookie ever changes.
Save the unit tests for the object model, save the integration tests for the presentation layer, and avoid mock objects when possible. If mocking a particular dependency is hard, it's time to be pragmatic: just don't do the unit test and write an integration test instead and stop wasting your time.
The simple answer is that code that you are trying to test is doing too much. I think sticking to the Single Responsibility Principle might help.
The Save button method should only contain a top-level calls to delegate things to other objects. These objects can then be abstracted through interfaces. Then when you test the Save button method, you only test the interaction with mocked objects.
The next step is to write tests to these lower-level classes, but thing should get easier since you only test these in isolation. If you need a complex test setup code, this is a good indicator of a bad design (or a bad testing approach).
Recommended reading:
Clean Code: A Handbook of Agile Software Craftsmanship
Google's guide to writing testable code
Constructor DI isn't the only way to do DI. Since you're using C#, if your constructor does no significant work you could use Property DI. That simplifies things greatly in terms of your object's constructors at the expense of complexity in your function. Your function must check for the nullity of any dependent properties and throw InvalidOperation if they're null, before it begins work.
When it is hard to test something, it is usually symptom of the code quality, that the code is not testable (mentioned in this podcast, IIRC). The recommendation is to refactor the code so that the code will be easy to test. Some heuristics for deciding how to split the code into classes are the SRP and OCP. For more specific instructions, it would be necessary to see the code in question.

Resources