Suggested flow-control structure for order-dependant operations - c++

I've run into the following issue which is not difficult to solve by any stretch of the imagination but I would like to know what the best / most elegant solution is.
I have the following method that the prototype of looks like this:
bool Team::isEveryoneDead(int teamOnTurn);
There are two teams available and depending on what instance of the team is currently on turn, I would like to check whether every Character in the team is dead in this very particular order:
Loop trough all the Characters in the team that's not on turn first. Should there be any character that's alive, stop looping (and goto step 2.). Should there be noone alive, terminate the function and return.
Now that I know that the team that's not on turn contains at least one character that's alive, loop trough the team that's currently on turn and check for the same thing. Should I find someone alive, stop looping and terminate / return.
The argument int teamOnTurn allows me to resolve the instance of Team that's currently on turn. The order in which i evaluate the "alive condition" is of great importance here.
Now, there are several approaches that can be taken, say hardcoding the order (since there are only 2 possible orders) and resolving the order by checking who's on turn and then executing the branch that already has the specific order like this:
bool Team::isEveryoneDead(int teamOnTurn) {
if (Team::Blue == teamOnTurn) {
checkThis();
checkThat();
} else {
checkThat();
checkThis();
}
}
This solution however wouldn't quite work for say 5! permutations for specific call-ordering for more items. What technique should one deploy to solve this with the utmost elegance :) ?
Thanks in advance, Scarlet.

Try creating another internal method that actually does the checking, and let the isEveryoneDead() method orchestrate the order in which the teams are checked, maybe something like this:
bool Team::isEveryoneDead(int teamOnTurn) {
bool isFound = isEveryoneDeadInternal( /* params for team not on turn */ );
if(isFound) {
isFound = isEveryoneDeadInternal( /* params for team on turn */ );
}
return isFound;
}
// This method know nothing about on turn or off turn
bool Team:isEveryoneDeadInternal() {
// Loop through all characters in the team, checking if any are alive
// When the first live character is found, return true
// else return false
}
This is a concept called DRY : Dont Repeat Yourself

Related

'identifier undefined' in C++11 for-loop with USTRUCT

I am implementing logging functionality in Unreal Engine 4.27 (in C++). A key part of my code is a function that is called once per game-tick. This function is responsible for iterating over an array of actors that I would like to log data for, checking whether a new log entry should be written at this point in time and calling the necessary functions to do that.
I am iterating over elements of a TArray of UStructs: LogObject->LoggingInfo = TArray<FActorLoggingInformation>. This array is defined as a UProperty of LogObject. In the loop I have to change the values of the elements so I want to work with the original items and "label" the current item as "ActorLoggingInfo". I have seen this done generally in cpp and also with TArrays. And yet my code does not work, there is no error message, but ActorLoggingInfo is undefined, thus the if-condition is never met.
This is the for-loop:
for (FActorLoggingInformation& ActorLoggingInfo : LogObject->LoggingInfo) {
if (ActorLoggingInfo.LogNextTick == true) {
ActorLoggingInfo.LogNextTick = false;
...
}
...
}
This is the definition of FActorLoggingInformation:
USTRUCT(BlueprintType)
struct FActorLoggingInformation
{
GENERATED_BODY()
public:
FActorLoggingInformation()
{
}
FActorLoggingInformation(int32 LogTimer, AActor* Actor, FString LogName)
{
this->LogTimer = LogTimer;
this->LogNextTick = false;
...
}
// Specifies Logging Frequency in ms
UPROPERTY(BlueprintReadOnly, VisibleAnywhere)
int32 LogTimer;
bool LogNextTick;
...
};
This is the debugger at run-time:
Additional Notes:
1. Something that consistently works for me is omitting the &, using:
for (FActorLoggingInformation ActorLoggingInfo : LogObject->LoggingInfo)
However, this is creating useless duplicates on a per-tick basis and complicates applying changes to the original objects from within in the for-loop, so it is not a viable option.
2. I have also tried auto& instead of FActorLoggingInformation& as used in the examples above, but I encountered the same issue, so I thought it would be best to be as explicit as possible.
I would be very thankful if you had any ideas how I can fix this :)
Thanks in advance!
Thanks to Avi Berger for helping me find my problem!
In fact, ActorLoggingInfo was actually never undefined and the code within the body of the if-clause was also executed (it just didn't do what it was intended to do).
When stepping through the code in the debugger it never showed the steps within the if-body and ActorLoggingInfo was shown as undefined so when no logs were written, I assumed it was something to do with that instead of my output function not working properly. So lesson learnt, do not blindly trust the debugger :)

What are some of the rules of thumb to split a test into multiple tests?

Okay, so I have this piece of code:
public TbMtUserDTO RecoverUser(long userId, UpdateTbMtUserDTO updatedData)
{
TbMtUser user = _usersRepository.FindUserById(userId);
if (user == null ||
(updatedData.IdRecSet == "Password" && String.IsNullOrEmpty(updatedData.DsUpdatedPassword)))
{
return null;
}
switch (updatedData.IdRecSet)
{
case "Username":
return _mapper.Map<TbMtUserDTO>(user);
case "Password":
user.DsPassword = PasswordHasher.Hash(updatedData.DsUpdatedPassword);
_usersRepository.SaveChanges();
return _mapper.Map<TbMtUserDTO>(user);
}
throw new InvalidOperationException(
String.Format(RECOVER_USER_ERROR, updatedData.IdRecSet));
}
And while I was writing the test cases for that chunk of code, when I had to write the test for one of the "Password" case, this is what I did:
[Fact]
public void UpdatesPasswordSuccessfully()
{
string oldPassword = _user.DsPassword;
UpdateTbMtUserDTO updateTbMtUserDto = new UpdateTbMtUserDTO()
{
IdRecSet = "Password",
DsUpdatedPassword = "new_password"
};
_usersRepositoryMock
.Setup(x => x.FindUserById(It.IsAny<long>()))
.Returns(_user);
_mapperMock
.Setup(x => x.Map<TbMtUserDTO>(It.IsAny<TbMtUser>()))
.Returns(new TbMtUserDTO());
TbMtUserDTO userDto = _usersService.RecoverUser(_user.CdUser, updateTbMtUserDto);
_usersRepositoryMock.Verify(x => x.SaveChanges(), Times.Once);
Assert.NotNull(userDto);
Assert.True(oldPassword != _user.DsPassword);
}
As you can see, there are three asserts at the bottom of that test. I first check if SaveChanges was called, and then I verify that the method actually returned something, hence the NotNull assertion and that it actually modifies the password (the True assertion).
But I kind of feel that's not the right way to do it. But in my head those tests are related, but I'm unsure if I should split them into three different tests. The thing is that I must arrange the same pieces together for the three cases, which to be honest, I don't think it's a good idea either.
What do you guys think? I've been implementing unit-testing for a couple of months now so what are some of your rules of thumb in scenarios like these?
Maybe if you think about split a test into multiple tests, you should split your method to multiple classes/methods and write tests for them? I do not want to go deep into architecture, but this can be a solution. Especially i would separate this:
if (user == null || (updatedData.IdRecSet == "Password"
&& String.IsNullOrEmpty(updatedData.DsUpdatedPassword)))
{
return null;
}
And this
user.DsPassword = PasswordHasher.Hash(updatedData.DsUpdatedPassword);
_usersRepository.SaveChanges();
There is a rule that each test should test one specific aspect. However, that leaves open a bit the question, what makes an aspect? For me, a rule of thumb is, that two asserts represent two different aspects if there is a plausible change in the SUT that could impact only one of the two asserts.
To give you an example: Assume in some game you always start at a certain space location (maybe a space station) with a defined 3D coordinate. To test the initialization function, you check if that initial coordinate has the expected values. These three values together form an aspect: If you decide at some point in time that the game should starts at a different place, all three coordinates will change at once (well, in theory not all need to change, but that would be a strange coincidence).
In your example, the situation is additionally complicated by the fact, that your function does more than one thing and uses the returning of null for different purposes. To be more specific, depending on the content of the argument, the function just does a lookup (user name), or additionally makes some change (password). Thus, it is not only a question of splitting the tests, but probably also of splitting the functionality.
I could imagine splitting it up into two parts: One function that does the lookup:
TbMtUser user = _usersRepository.FindUserById(userId);
if (user != null) {
return _mapper.Map<TbMtUserDTO>(user);
} else {
return null;
}
And a second one that changes the password for an already looked-up user - which in your case may not be straightforward, because the internally used type is TbMtUser whereas the returned type is TbMtUserDTO and is not clear for me how they are related...

splitting tasks to categories

I have a class (lets call it checker) and diffrent kind of classes that execute tasks (lets call them tasks). each tasks belongs to several categories
each task runs and at some point asks checker if they are allowed to do something. checker answers according to system state and according to their category. a task can be in multiple categories
how would you implement that? (cpp but I don't really think its language specific).
I was thinking adding a list of categories in each task and have a function that gets a category and answers if the task belongs to it.
class checker {
bool is_allowed(Task * task);
}
class Task
{
bool is_belongging_to_category(Category cat);
void some_task_to_do()
{
...
if (checker::is_allowed(this)) { ....}
else {....}
}
}
Is there a better way to solve this? Maybe some known design pattern...
This looks like questionable design. You're making tasks the objects.
Let's say your tasks are: Eat, Drink, and Be_Merry
If you make each of those tasks objects, they'll have to maintain a reference to the actual individual that they operate on, then when the condition is met they'll need to modify state on the given individual.
This is a violation of Object Oriented Design which defines an object as:
A tight coupling or association of data structures with the methods or functions that act on the data
Notice that you have split the "methods or functions that act on the data" from the object. Instead you should have modeled the objects Jack and Jill which had methods: Eat, Drink, and BeMerry
As far as checker, whether it's parceled out will depend upon whether you're using a push or a pull coding. If you're doing push coding, then checker is simply a holding area for the behavioral properties of Jack and Jill, in such a case the properties should be pushed to Jack and Jill rather than held in checker. If they are properties for all Jack or Jill objects, use a static property. If however you are using pull coding then the information is unavailable until you attempt to execute the task. In this case the checker should probably be a singleton that Jack and Jill access in the process of performing their tasks.
EDIT:
Your comment reveals further tragedy in the design. It seems as though you've kicked off a bunch of threads which are doing busy waiting on checker. This indicates that you need to be using a pull coding. You're Jack and Jill objects need to maintain booleans for which tasks they are actively involved in, for example m_is_going_to_school, then when checker gets the condition that would stop your busy waiting in your design, instead kick off the goToSchool method.
You could make a vector to store all the possible allowed options. You can make a bool function (like you have) called IsAllowed with argument string and that will check if the option its going to do is allowed. If not, return false. That's just my idea though. Of course there's a zillion different ways to implement this. If you want multiple choices. Then you can make a 2d vector, and see if the corresponding row has any of the options. Good luck!
If you know the maximum number of categories in advance, I'd recommend using Bit Flags to do this.
enum Category {
CATEGORY_A = 1,
CATEGORY_B = 1 << 1,
CATEGORY_C = 1 << 2,
CATEGORY_D = 1 << 3,
};
class Task {
int32_t categories_;
public:
Task() : categories_(0) {}
void add_category(Category cat) {
categories_ |= cat;
}
void run() {
checker::can_run(categories_);
}
}
This allows to test for multiple categories all at once:
namespace checker {
bool can_run(int32_t categories) {
int32_t cannot_run_right_now = CATEGORY_A | CATEGORY_C;
if(categories & cannot_run_right_now != 0) {
return false;
}
...
}
}
Well, it depends. If you are 100% sure that you know how many categories there are to be and that is not some gigantic number then you might store this information as an integer. If n-th bit is 1 then task belongs to n-th category. Then depends on the state of system you might create some another integer that would serve as a mask. In the end you would just do some bit-AND ( mask & categories != 0 ) operation to determine if task and mask share common bit.
On the other hand if there will be unknown number of categories you might just make a list of categories it belongs to. Make a dictionary of [SYSTEM_STATE] => [CATEGORIES_AVAILABLE] and check
bool is_allowed(Task * task){
foreach (Category sysC in stateCategories[sys.GetState()])
{
foreach (Category taskC in task.GetCategories())
{
if(sysC == taskC) return true;
}
}
return false;
}
That would of course be slow for a big number of categories.
You could improve this method by making this list of categories some another data structure, in which searching is not O(n) such that the code would look like this :
bool is_allowed(Task * task){
foreach (Category sysC in stateCategories[sys.GetState()])
{
if task.GetCategories().Contains(sysC) {
return true;
}
}
It depends

How to test asynchronuous code

I've written my own access layer to a game engine. There is a GameLoop which gets called every frame which lets me process my own code. I'm able to do specific things and to check if these things happened. In a very basic way it could look like this:
void cycle()
{
//set a specific value
Engine::setText("Hello World");
//read the value
std::string text = Engine::getText();
}
I want to test if my Engine-layer is working by writing automated tests. I have some experience in using the Boost Unittest Framework for simple comparison tests like this.
The problem is, that some things I want the engine to do are just processed after the call to cycle(). So calling Engine::getText() directly after Engine::setText(...) would return an empty string. If I would wait until the next call of cycle() the right value would be returned.
I now am wondering how I should write my tests if it is not possible to process them in the same cycle. Are there any best practices? Is it possible to use the "traditional testing" approach given by Boost Unittest Framework in such an environment? Are there perhaps other frameworks aimed at such a specialised case?
I'm using C++ for everything here, but I could imagine that there are answers unrelated to the programming language.
UPDATE:
It is not possible to access the Engine outside of cycle()
In your example above, std::string text = Engine::getText(); is the code you want to remember from one cycle but execute in the next. You can save it for later execution. For example - using C++11 you could use a lambda to wrap the test into a simple function specified inline.
There are two options with you:
If the library that you have can be used synchronously or using c++11 futures like facility (which can indicate the readyness of the result) then in your test case you can do something as below
void testcycle()
{
//set a specific value
Engine::setText("Hello World");
while (!Engine::isResultReady());
//read the value
assert(Engine::getText() == "WHATEVERVALUEYOUEXPECT");
}
If you dont have the above the best you can do have a timeout (this is not a good option though because you may have spurious failures):
void testcycle()
{
//set a specific value
Engine::setText("Hello World");
while (Engine::getText() != "WHATEVERVALUEYOUEXPECT") {
wait(1 millisec);
if (total_wait_time > 1 sec) // you can put whatever max time
assert(0);
}
}

Using Lua to define NPC behaviour in a C++ game engine

I'm working on a game engine in C++ using Lua for NPC behaviour. I ran into some problems during the design.
For everything that needs more than one frame for execution I wanted to use a linked list of processes (which are C++ classes). So this:
goto(point_a)
say("Oh dear, this lawn looks really scruffy!")
mowLawn()
would create a GotoProcess object, which would have a pointer to a SayProcess object, which would have a pointer to a MowLawnProcess object. These objects would be created instantly when the NPC is spawned, no further scripting needed.
The first of these objects will be updated each frame. When it's finished, it will be deleted and the next one will be used for updating.
I extended this model by a ParallelProcess which would contain multiple processes that are updated simultaneously.
I found some serious problems. Look at this example: I want a character to walk to point_a and then go berserk and just attack anybody who comes near. The script would look like that:
goto(point_a)
while true do
character = getNearestCharacterId()
attack(character)
end
That wouldn't work at all with my design. First of all, the character variable would be set at the beginning, when the character hasn't even started walking to point_a. Then, then script would continue adding AttackProcesses forever due to the while loop.
I could implement a WhileProcess for the loop and evaluate the script line by line. I doubt this would increase readability of the code though.
Is there another common approach I didn't think of to tackle this problem?
I think the approach you give loses a lot of the advantages of using a scripting language. It will break with conditionals as well as loops.
With coroutines all you really need to do is:
npc_behaviour = coroutine.create(
function()
goto(point_a)
coroutine.yield()
say("Oh dear, this lawn looks really scruffy!")
coroutine.yield()
mowLawn()
coroutine.yield()
end
)
goto, say and mowLawn return immediately but initiate the action in C++. Once C++ completes those actions it calls coroutine.resume(npc_behaviour)
To avoid all the yields you can hide them inside the goto etc. functions, or do what I do which is have a waitFor function like:
function waitFor(id)
while activeEvents[id] ~= nil do
coroutine.yield()
end
end
activeEvents is just a Lua table which keeps track of all the things which are currently in progress - so a goto will add an ID to the table when it starts, and remove it when it finishes, and then every time an action finishes, all coroutines are activated to check if the action they're waiting for is finished.
Have you looked at Finite State Machines ? If I were you I wouldn't use a linked list but a stack. I think the end result is the same.
stack:push(action:new(goto, character, point_a))
stack:push(action:new(say, character, "Oh dear, this lawn was stomped by a mammoth!"))
stack:push(action:new(mowLawn, character))
Executing the actions sequentially would give something like :
while stack.count > 0 do -- do all actions in the stack
action = stack:peek() -- gets the action on top of the stack
while action.over ~= true do -- continue action until it is done
action:execute() -- execute is what the action actually does
end
stack:pop() -- action over, remove it and proceed to next one
end
The goto and other functions would look like this :
function goto(action, character, point)
-- INSTANT MOVE YEAH
character.x = point.x
character.y = point.y
action.over = true -- set the overlying action to be over
end
function attack(action, character, target)
-- INSTANT DEATH WOOHOO
target.hp = 0
action.over = true -- attack is a punctual action
end
function berserk(action, character)
attack(action, character, getNearestCharacterId()) -- Call the underlying attack
action.over = false -- but don't set action as done !
end
So whenever you stack:push(action:new(berserk, character)) it will loop on attacking a different target every time.
I also made you a stack and action implementation in object lua here. Haven't tried it. May be bugged like hell. Good luck with your game !
I don't know the reasons behind you design, and there might be simpler / more idiomatic ways to it.
However, would writing a custom "loop" process that would somehow take a function as it's argument do the trick ?
goto(point_a)
your_loop(function ()
character = getNearestCharacterId()
attack(character)
end)
Since Lua has closures (see here in the manual), the function could be attached to your 'LoopProcess', and you call this same function at each frame. You would probably have to implement your LoopProcess so that that it's never removed from the process list ...
If you want your loop to be able to stop, it's a bit more complicated ; you would have to pass another function containing the test logic (and again, you LoopProcess would have to call this every frame, or something).
Hoping I understood your problem ...