Precondition and class containment - preconditions

Assume I have the following class:
public class Player {
private Board board;
private int roundsPlayed = 0;
public void play() {
while (board.isAvailable() && roundsPlayed < 10) {
// playing on the board
roundsPlayed++;
}
}
}
What is the Pre/Post condition of my Player's play() method ?
My answer for the precondition would be centered around the roundsPlayed variable,
However I'm wondering whether or not my pre/post condition should include the fact that I'm using the Board and probably its variables in my method
Should my pre / post condition consider Board in my answer ?

Yes, you have a precondition that board is not null.

Related

How to get the instance of an injected dependency, by its type using Umbraco.Core.Composing (Umbraco 8)

I need to find a way to get an instance of DataProcessingEngine without calling it's constractor.
I am trying to find a way to do so using the registered DataProcessingEngine in composition object (please see the following code). But I could not find a way to do so.
Anyone have a suggestion? Thanks in advance.
public class Composer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<IDataProcessingEngine, DataProcessingEngine>(Lifetime.Singleton);
//DataProcessingEngine dataProcessing = compostion.Resolve<IDataProcessingEngine>()??//no resolve function exists in Umbraco.Core.Composing
SaveImagesThread(dataProcessingEngine);
}
public Task SaveImagesThread(IDataProcessingEngine dataProcessingEngine)//TODO - decide async
{
string dataTimerTime = WebConfig.SaveProductsDataTimer;
double time = GetTimeForTimer(dataTimerTime);
if (time > 0)
{
var aTimer = new System.Timers.Timer(time);
aTimer.Elapsed += new ElapsedEventHandler(dataProcessingEngine.SaveImages);
aTimer.Start();
}
return default;
}
}
For all of you who are looking for a way to call a function (that's defined in another class in your code, an Engine or ...) from the composer(where the app starts) and want to avoid calling this function's class' constractor. I've found another way to do so:
public class QueuePollingHandler
{
[RuntimeLevel(MinLevel = RuntimeLevel.Run)]
public class SubscribeToQueuePollingHandlerComponentComposer :
ComponentComposer<SubscribeToQueuePollingHandler>
{ }
public class SubscribeToQueuePollingHandler : IComponent
{
private readonly IDataProcessingEngine _dataProcessingEngine;
public SubscribeToQueuePollingHandler(IDataProcessingEngine
dataProcessingEngine)
{
_dataProcessingEngine = dataProcessingEngine;
SaveImagesThread(_dataProcessingEngine);
}
public void SaveImagesThread(IDataProcessingEngine
dataProcessingEngine)
{
....
}
}
And the logic explenation: You create a class (SubscribeToQueuePollingHandlerComponentComposer from the example) and define its base class to be ComponentComposer<Class_that_inherits_IComponent>.
And when you start the application you could see that it gets to the registered class' constractor (SubscribeToQueuePollingHandler constructor).
That's the way that I found to be able to call a function right when the application starts without needing to call its class constractor and actualy use dependency injection.

How can I initialize a mixin's immutable data in Dart?

I am programming in Flutter using Dart 2.1.0, and come across this situation:
mixin Salt {
final int pinches; // Immutable, and I want to delay initialization.
// Cannot declare constructors for mixin
}
class Meat with Salt {
Meat(int pinches) ... // How to initialize it?
}
Salt has no constructor, so I cannot use initializer list. pinches is final, so I cannot set it in Meat's constructor.
I don't want to make Salt a class because Meat may need to extend from something else.
And I want to keep pinches immutable.
Any way to do it? Thanks in advance.
You can change the declaration of your mixin to:
mixin Salt {
int get pitches;
}
And then define the field inside the implementation class
class Meat with Salt {
final int pitches;
Meat(this.pitches);
}
By design it is not possible to declare a final member into a mixin because it is not possible to declare a constructor for initializing the final member,
citing the docs:
However, in this proposal, a mixin may only be extracted from a class that has no declared constructors. This restriction avoids complications that arise due to the need to pass constructor parameters up the inheritance chain.
A compromise may be to declare a private member and implement only a getter.
_pinches is visible only inside the library, it is read-only for library users.
mixin Salt {
int _pinches;
get pinches => _pinches;
}
class Meat with Salt {
Meat(int pinches) {
_pinches = pinches;
}
}
Note: the above pattern, because of the visibility rules, works only if the mixin and the mixed classes reside in the same library.
I offer my take on a solution to this. By marking the variable late you can make it final. No warning will appear if you fail to initialize it so use with caution.
mixin Salt {
late final int pinches;
}
class Vegetable with Salt {
Vegetable(int pinches) {
this.pinches = pinches;
}
}
Similar to attdona's suggestion, but a little bit closer to what you really wanted, you could do it like
mixin Salt {
int _pinches;
int get pinches => _pinches;
void initSalt(int pinches) {
assert(_pinches == null);
_pinches = pinches;
}
}
class Meat with Salt {
Meat(int pinches) {
initSalt(pinches);
}
}
It's still not strictly final, but (so long as the mixin's in a different library so you can't change the private member directly) it's immutable at runtime. Not as good as if it could be properly final, but maybe close enough.
The following method allows you to set the data at a later time, and gets rid of the warning:
This class (or a class that this class inherits from) is marked as '#immutable', but one or more of its instance fields aren't final
mixin Salt {
final SaltData _saltData = SaltData();
int get pinches => _saltData.pinches;
set pinches(int extraData) {
_saltData.pinches = extraData;
}
}
class SaltData {
int pinches = 0;
}
So what I did is create a class SaltData. This will store all the variables you need.
The private _saltData variable is final, this will stop the warning.
Then use a getter and setter to retrieve and update the data.
int get pinches => _saltData.pinches;
set pinches(int extraData) {
_saltData.pinches = extraData;
}
If you want you can could expose the entire saltData object as well:
SaltData get saltData => _saltData;

Whats the best way to completely disable every play at runtime?

I want to disable everyplay, built in unity, when running iphone4/3G/3GS
but I'm not sure of the easiest place to just globally disable it. Any suggestions?
if (iPhone.generation == iPhoneGeneration.iPhone4 || iPhone.generation == iPhoneGeneration.iPhone3G || iPhone.generation == iPhoneGeneration.iPhone3GS )
You can easily disable single core devices (3GS/4/iPad1) by calling Everyplay.SharedInstance.SetDisableSingleCoreDevices(true) in the first scene of your game. After that you don't have to worry if you are calling StartRecording on a single core device since the calls are ignored by Everyplay. 3G (and Unity editor) does not support the recording in the first place.
In case you need to support recording on iPad 1 one approach is to create an Everyplay singleton wrapper which simply does not call recording functions on devices which you have have defined to be not supported.
Simple wrapper example (untested but gives you the idea):
using UnityEngine;
public static class MyEveryplayWrapper {
private static iPhoneGeneration[] unsupportedDevices = {
iPhoneGeneration.iPad1Gen,
iPhoneGeneration.iPhone,
iPhoneGeneration.iPhone3G,
iPhoneGeneration.iPhone3GS,
iPhoneGeneration.iPodTouch1Gen,
iPhoneGeneration.iPodTouch2Gen,
iPhoneGeneration.iPodTouch3Gen
};
private static bool CheckIfRecordingSupported() {
bool recordingSupported = !Application.isEditor;
foreach(iPhoneGeneration device in unsupportedDevices) {
if(device == iPhone.generation) {
recordingSupported = false;
break;
}
}
Debug.Log ("Everyplay recording support: " + recordingSupported);
return recordingSupported;
}
public static bool IsRecordingSupported = CheckIfRecordingSupported();
public static void StartRecording() {
if(IsRecordingSupported) {
Everyplay.SharedInstance.StartRecording();
}
}
public static void StopRecording() {
if(IsRecordingSupported) {
Everyplay.SharedInstance.StopRecording();
}
}
}
To use it you just call MyEveryplayWrapper.MethodName instead of Everyplay.SharedInstance.MethodName. When rendering your UI you can take the IsRecordingSupported into account to show/hide Everplay related buttons etc.

Game AI - Behavior Trees

How do you make a robust AI/scripting system for a game?
1) For all NPC's/environment/entities do you give them a SEPARATE single behavior tree (etc. patrolBehavior, allyBehavior, vendorBehavior, doorBehavior)? If there are 500 units on the screen, should I do a full pass on the tree (going from root -> node/action) or should I do 1-node progress for all the units?
2) I am doing the AI logic in the update() function... but I heard some games have their separate AI thread, any ideas?
3) I'm wondering how to divide my game into sections/chapters... do I use a simple variable (EVENT="Mission 3") to denote how for the player's been, and make it all linear? And then utilize variable in the trees above?
I'll try to answer your question.
I do all branching logic and behavior trees in a static class for example:
public static class Behavior
{
//Branch
public static Action Selector(Func<bool> cond, Action ifTrue, Action ifFalse) {
return () => { if (cond()) { ifTrue(); } else { ifFalse(); } };
}
public static Action Sequencer(Action a, Action b) {
return () => { a(); b(); }
}
//Example trees
public static Func<bool> ifPlayerIsInSight = () => { return true; /*...true iff WorldState shows guard can see player...*/};
public static Action shootAtPlayer = () => { /*...aim guard's weapon at player and fire...*/ };
public static Func<bool> ifUnderFire = () => { return true; /*...true iff WorldState shows guard hears player gunfire...*/};
public static Action takeCover = () => { /*...guard runs for nearest shelter... */};
public static Action walkBackAndForthGuardingDoorway = () => { /*...default guard patrol behaviour...*/ };
public static Action patrollingGuardBehaviour =
Selector(Behavior.ifPlayerIsInSight, Behavior.shootAtPlayer,
Selector(Behavior.ifUnderFire, Behavior.takeCover,
Behavior.walkBackAndForthGuardingDoorway));
}
Do it in LateUpdate() or last so it does not lag the main loop.
It is upto you. You could implement a "State" in each behavior tree or split it out and manage which get used at what time.
each NPC/Agent has its own behavior tree. The tree is updated and it 'knows' where to continue, so the efficiency is usually quite good.
AIs can be updated in the main thread, it can also be updated in a separated thead. it depends and up to you.
it depends and up to you.
behaviac is a really excellent one.
behaviac supports the behavior tree, finite state machine and hierarchical task network. Behaviors can be designed and debugged in the designer, exported and executed by the game.
The C++ version is suitable for the client and server side.
and, it is open sourced!

inject different implementations by logged User Role

public class TheController : Controller
{
IThe the;
public TheController( IThe the)
{
//when User.IsInRole("r1") The1 should be injected else r2
this.the = the;
}
}
public class The1 : IThe{}
public class The2 : IThe{}
//anybody knows a good way of doing this ?
IHandlerSelector is the way to go. See this post for an example of usage.
Alternatively if you prefer AutoFac-like experience you can use factory for that:
container.Register(Component.For<IThe>().UsingFactoryMethod(
c => HttpContext.Current.User.IsInRole("r1") ?
c.Resolve<IThe>("r1") :
c.Resolve<IThe>("r2"));
Or if you want to use specific IThe just in one context, you can use DynamicParameters:
container.Register(Component.For<TheFactory>().Lifestyle.Transient.DynamicParameters(
(c, d) => HttpContext.Current.User.IsInRole("r1") ?
d["the"] = c.Resolve<IThe>("r1") :
c.Resolve<IThe>("r2"));
However the most correct way of doing this is IHandlerSelector
The container-agnostic approach obviously employs an Abstract Factory:
public interface ITheFactory
{
IThe Create(IPrincipal user);
}
You can take a dependency on ITheFactory instead of IThe:
public class TheController : Controller
{
private readonly IThe the;
public TheController(ITheFactory theFactory)
{
if (theFactory == null)
{
throw new ArgumentNullException("theFactory");
}
this.the = theFactory.Create(this.User);
}
}
I can't really remember if this.User is populated at this time, but if it isn't, you can just keep a reference to the factory and lazily resolve your dependency the first time it's requested.
However, Controller.User is a bit special because it ought to be available as Thread.CurrentPrincipal as well. This means that in this special case you don't actually have to introduce an Abstract Factory. Instead, you can write a Decorator that performs the selection every time it's used:
public class UserSelectingThe : IThe
{
private readonly IThe the1;
private readonly IThe the2;
public UserSelectingThe(IThe the1, IThe the2)
{
if (the1 == null)
{
throw new ArgumentNullException("the1");
}
if (the2 == null)
{
throw new ArgumentNullException("the2");
}
this.the1 = the1;
this.the2 = the2;
}
// Assuming IThe defines the Foo method:
public Baz Foo(string bar)
{
if (Thread.CurrentPrincipal.IsInRole("r1"))
{
return this.the1.Foo(bar);
}
return this.the2.Foo(bar);
}
}
In this case, you would be able to use your original TheController class unchanged.
In Autofac:
var builder = new ContainerBuilder();
// Give the different implementations names
builder.RegisterType<The1>.Named<IThe>("r1");
builder.RegisterType<The2>.Named<IThe>("r2");
// Use a function for the default IThe
builder.Register(
c => HttpContext.Current.User.IsInRole("r1") ?
c.Resolve<IThe>("r1") :
c.Resolve<IThe>("r2"))
.As<IThe>()
.ExternallyOwned();
If you have a lot of roles, you can use a method instead of the inline expression, e.g.:
builder.Register(c => ChooseTheImplementation(c))
(BTW, The "ExternallyOwned" modifier tells the container that the result of the function is disposed elsewhere, e.g. via the concrete components. You can usually leave it out but it makes good documentation :))

Resources