I've searched my best on here in order to find the answer to my question but there's either no results or I'm not searching the right thing, but anyway...
The battleships game I need to create has to have: 1 Aircraft Carrier of length 5, 2 battleships of length 4, 3 destroyers of length 3 and 4 submarines of length 2.
I have a ship class which holds data such as the id, name, x, y and direction.
I then have a board class which then needs to instantiate all these ships. I'm doing this by making a vector of type Ship and pushing ship objects onto that.
However each ship objects needs to store all the x and y values of that ship and I'm stuck on how to do that. I wanted to post code but it's non functional and looks messy at the moment which is probably not beneficial to anyone. However if necessary I can write the skeleton again and post it up here.
Thanks in advance.
If you have x, y and direction then the points of the ship can be calculated from it's size
Each ship could just have a vector<Point> inside. Checking for hit could be then:
Point guess;
for (auto& ship : ships) {
for (auto& point : ship.points) {
if (point == guess)
// hit
}
}
That would make sense if you are aiming for a version where you need to hit the ship once in each of its parts.
The inner loop can also be easily changed to std::find, making it arguably more clear.
Related
I have an assignment for my class where we are attempting to find the best (cheapest) path to a destination. The description is as follows:
Each tech has a name, a cost to buy that tech, a boolean saying whether or not the player has the tech already, and a list of 0 to N techs that are available for purchase when the player buys this tech. There are three categories of tech in Tactigo: Social, Military, and Science. Each of the three starts with a basic tech that the player must purchase before purchasing more advanced techs. These basic techs are special because they are always available for purchase.
Looking at the diagram, you will note that a few techs are unlocked by multiple techs. Remember that techs are unlocked as soon as ANY tech unlocks them. In other words, you need either "Being Nice to Animals" OR "Being a Dick to People" in order to buy "Attack Animal Training". You don't need both, just one. Your task is to find the cheapest way to get any given technology. The player might own any set of techs already, so you must account for that. For example, if the player already owns "Being Nice to People" and wants to find the cheapest way to get "Making Friends", the path returned should just be "Making Friends". They don't need to purchase anything else.
The Graph looks as follows:
I originally thought of doing a depth-first-search on each of the 3 categories while calculating the cost of each path taken. My Code for this function is as follows:
//---------------------------------------------------------------------------------------------------------------------
// This function finds the best path to the tech we want.
// * goalTech: The index of the tech we're looking for. Call GetTechByIndex() to get the actual Tech instance.
// * bestPath: The best path to the goal tech. This is an array sorted in the order of the best path from the
// start to the goal. This is an output variable; it's what you need to populate with this function.
//---------------------------------------------------------------------------------------------------------------------
void TechTree::FindBestPath(int goalTech, Path& bestPath)
{
//First ensure that best path is cleared out
bestPath.clear();
//Get Tech Instance for this Goal Tech
const Tech* pGoalTech = GetTechByIndex(goalTech);
//make sure we get a valid tech
assert(pGoalTech != nullptr);
//Check first if user already has this unlocked.
if (pGoalTech->HasTech())
{
//just return
return;
}
//Check if the goal tech is one of the three starting techs.
if (pGoalTech == GetBasicSocialTech()|| pGoalTech == GetBasicScienceTech() || pGoalTech == GetBasicMilitaryTech())
{
//now we know that one of the basic techs are the goal, so we just add one of those to the path
if (pGoalTech == GetBasicSocialTech())
bestPath.push_back(GetBasicSocialTech());
else if (pGoalTech == GetBasicMilitaryTech())
bestPath.push_back(GetBasicMilitaryTech());
else
bestPath.push_back(GetBasicScienceTech());
return; //now return
}
//my process will be as follows.
//1. Since all the edges are directed we need to traverse down three different graphs: Social (starting at index 0), Military (starting at index 4) and Science (starting at index 8)
//2. I am going to perform a depth-first search starting at Social and then moving down to Military and then Science.
//3. As I am performing a depth-first I am going to keep track of a path and its respective cost, if a search gets to the goal I will make sure to register that and then move onto the next graph.
//4. When there are no more paths to search I send the lowest cost one back.
///start with social at index 0
const Tech* pStartSocialTech = GetBasicSocialTech();
std::pair<int, std::vector<const Tech*>> bestCurrentPath;
//get starting cost for this category before we move into neighbors,
// if player already has this tech we set this to zero if not we get the cost of buying into this category
int startingCost = pStartSocialTech->HasTech() ? 0 : pStartSocialTech->GetCost();
/*pStartSocialNeighbors = get all neighbors for starting point at social
while (destination is not found AND there are more neighbors to pStartSocialNeighbors)
{
DFS(neighbor, dest) //if this finds the destination we store a path and its cost, otherwise it doesnt do anything and we move on to next basic tree
}
//do the same thing for military and science...
*/
}
I have a lot of comments on it but I am just wondering if this is the best route to take. Other options are Dijkstras or A* but I don't know how you would traverse the path of this directed graph. I am not looking for a direct answer since this is a homework assignment but I am looking for some guidance.
Thanks!
Going from the target to source using Dijkstras, you need to modify the stop condition if you want to stop before searching all paths. I don't see any heuristic for A* in this case.
Adding a node with a path to all known techs
You can now use Dijkstras / Bellman-Ford.
Using A* has the problem you need to find a heuristic that works. You could use depth times min cost of all edges. that requires you to already have traversed the graph to assign depth.
I am using veins 5.0 and i am trying to calculate the distance between the vehicles and setting their speed. I want to calculate it every second and i want to do it by sending wsm messages.My goal is to have for example 5 vehicles, each vehicle will communicate with the front vehicle and get its position with the intention of calculating their distance and keep it static. I am new to this and i don't know how to approach it.
I tried to do something like this on handlePositionUpdate
void TraCIDemo11p::handlePositionUpdate(cObject* obj)
{
DemoBaseApplLayer::handlePositionUpdate(obj);
// stopped for for at least 10s?
if (x<simTime()){
TraCIDemo11pMessage* wsm1 = new TraCIDemo11pMessage();
populateWSM(wsm1);
wsm1->setPosition(mobility->getPositionAt(simTime()));
wsm1->setSpeed(mobility->getSpeed());
if (dataOnSch) {
startService(Channel::sch2, 42, "Traffic Information Service");
message to self to send later
scheduleAt(computeAsynchronousSendingTime(1,ChannelType::service), wsm1);
}
else {
sendDown(wsm1);
}
}
You are describing what is, effectively, a platooning application. You might want to base your source code on Plexe, the platooning extension to Veins. It already comes with state-of-the-art distance controllers like PATH or Ploeg. More information can be found on http://plexe.car2x.org/
I'm still confused about unit testing. Suppose I have something as trivial as this:
class x {
zzz someMethod(some input...) {
BufferedImage image = getter.getImageFromFile(...);
// determine resize mode:
int width = image.getWidth();
int height = image.getHeight();
Scalr.Mode resizeMode = (width > height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
return ScalrWrapper.resize(image, resizeMode);
}
}
Going by rules, Scalr.Mode resizeMode = should probably be a in a separate class for better unit testability of the aforementioned method, like so:
class xxx {
mode getResizeMode(int width, int height)
{
return (width > height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
}
}
class x {
zzz someMethod(some input...) {
BufferedImage image = getter.getImageFromFile(...);
// determine resize mode:
int width = image.getWidth();
int height = image.getHeight();
Scalr.Mode resizeMode = xxx.getResizeMode(width, height);
return ScalrWrapper.resize(image, resizeMode);
}
}
But it looks like such an overkill... I'm not sure which one is better but I guess this way is better. Suppose I go this route, would it be even better to do it this way?
class xxx {
mode getResizeMode(Image image)
{
return (image.getWidth() > image.getHeight()) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
}
}
class x {
void someMethod(some input...) {
BufferedImage image = getter.getImageFromFile(...);
// determine resize mode:
Scalr.Mode resizeMode = xxx.getResizeMode(image);
return ScalrWrapper.resize(image, resizeMode);
}
}
From what I understand, the correct way is the one where getResizeMode accepts integers as it is decoupled from the type of data whose properties are width and height. However, personally to me, the use of getResizeMode(BufferedImage) actually justifies the creation of a separate class better as some more work is removed from the main method. And since I am not going to be using getResizeMode for any sort of data other than BufferedImage in my application anyway, there is no problem of reusability. Also, I don't think I should be doing getResizeMode(int, int) simply for reusability if I see no need for it due to YAGNI principle.
So my question is: would getResizeMode(BufferedImage) be a good way according to OOD in real world? I understand it's text book good OOD, but then I have been lead to believe that 100% text book OOD is impracticle in real world. So as I am trying to learn OOD, I just want to know which path I should follow.
...Or maybe I should I just leave everything in one method like in the very first code snippet?
I don't think that resize mode calculation influences testability a lot.
As to Single Responsibility:
"A class should have only one reason to change" (https://en.wikipedia.org/wiki/Single_responsibility_principle).
Do you think that resizing mode calculation is going to change?
If not then just put in the class where this mode is needed.
This won't add any reasons to change for that class.
If the calculation is likely to change (and/or may have several versions)
then move it to a separate class (make it a strategy)
Achieving the Single Responsibility Principle (SRP) is not about creating new classes every time, one extracting a method. Moreover the SRP depends on the context.
A module should concern to the SRP.
A class should concern to the SRP.
A method should concern to the SRP.
The message from Uncle Bob is: Extract till you Drop
Beyond he said:
Perhaps you think this is taking things too far. I used to think so too. But after programming for over 40+ years, I’m beginning to come to the conclusion that this level of extraction is not taking things too far at all.
When it comes to the decision to create new classes, keep the metric high cohesion in mind. Cohesion is the degree to which the elements of a module belong together. If all methods work in one specific context and on the same set of variables, they belong to one class.
Back to your case. I would extract all the methods and put them in on class. And this one class is also nicely testable.
Little bit late to the party, but here's my 2c.
To my mind, class x is not adhering to the SRP for a different reason.
It's currently responsible for
Getting an image from a file (getter.getImageFromFile)
Resizing that image
TL;DR
The TL;DR on this is that both of your approaches are fine and both do in fact stick - with varying degrees of stickiness - to the SRP. However if you want to adhere very tightly to the SRP (which tends to lead to very testable code), you could split this into three classes first:
Orchestrator
class imageResizeService
{
ImageGetter _getter;
ImageResizer _resizer;
zzz ResizeImage(imageName)
{
image=_getter.GetImage(imageName);
resizedImage=_resizer.ResizeImage(image);
return resizedImage;
}
}
This class has a single responsibility; namely, given an image name,
return a resized version of it based on some criteria.
To do so, it orchestrates two dependencies. But it only has a single reason to change which is that the process used to get and resize an image in
general , has changed.
You can easily unit test this by mocking the getter and resizer and testing that they are called in order, that the resizer is called with the data given by the getter, and that the final return value equals that returned by the resizer, and so on (i.e. "White Box" testing)
ImageGetter
class ImageGetter
{
BufferedImage GetImage(imageName)
{
image=io.LoadFromDisk(imageName) or explode;
return image;
}
}
Again, we have a single responsiblity (load an image from disk, and return it).
The only reason to change this class would be if the mechanics of loading the image were to change - e.g. you are loading from a Database, not a Disk.
An interesting note here is that this class is ripe for further generalisation - for example to be able to compose it using a BufferedImageBuilder and a RawImageDataGetter abstraction which could have multiple implementations for Disk, Database, Http, etc. But that's YAGNI right now and a conversation for another day :)
Note on testability
In terms of unit testing this, you may run into a small problem, namely that you can't quite "unit test" it - unless your framework as a mock for the file system. In that case, you can either further abstract the loading of the raw data (as per the previous paragraph) or accept it and just perform an integration test off a known good file. Both approaches are perfectly valid and you should not worry about which you choose - whatever is easier for you.
ImageResizer
class ImageResizer
{
zzz ResizeImage(image)
{
int width = image.getWidth();
int height = image.getHeight();
Scalr.Mode resizeMode = getResizeMode(width, height);
return ScalrWrapper.resize(image, resizeMode);
}
private mode getResizemode(width, height)
{
return (width > height) ? Scalr.Mode.FIT_TO_WIDTH : Scalr.Mode.FIT_TO_HEIGHT;
}
}
This class also has but a single job, to resize an image.
The question of whether or not the getResizeMode method - currently just a private method to keep the code clean - should be a separate responsiblity has to be answered in the context of whether or not that operation is somehow independent of the image resizing.
Even if it's not, then the SRP is still being followed, because it's part of the single responsibility "Resize an Image".
Test-wise this is also really easy to test, and because it doesn't even cross any boundaries (you can create and supply the sole dependency - the image - during test runtime) you probably won't even need mocks.
Personally I would extract it to a separate class, just so that I could, in isolation, verify that given a width larger than a height, I was returned a Scalr.Mode.FIT_TO_WIDTH and vice-versa; it would also mean I could adhere to the Open Closed Principle whereby new scaling modes could be introduced without having to modify the ImageResizer class.
But really
The answer here has to be that that it depends; for example if you have a simple way to verify that, given a width of 100 and a height of 99, then the resized image is indeed scaled to "Fit to Width" then you really don't need to.
That being said I suspect you'll have an easier time testing this if you do extract that to a separate method.
Just bear in mind that if you're using a decent IDE with good refactoring tools, that should really not take you more than a couple of keystrokes, so don't worry about the overhead.
I wanted to know if anyone has idea how to do the following:
we have a 3D model of a character ..
Now I need to make, is that this "character" have interchangeable parts ...
For example, if you want to add a helmet or armor to the model, I guess I should replace the vertex of the torso or head vertex for the armor or helmet vertex.
That's where the problem comes, as I can know where "the part" starts and where finish and start another part? (in blender so I have separate the character in "groups", arm, foot, head, etc..
I think a possible solution:
i had thought to create an object for each "part" and load as separate models (arm on one side, head for the other and so) and handle all parts as "one model".
but I think it is not right... you can tell me what is the correct way ? tell me your experience in this case (if you know any tutorial on this subject. thanks!)
i Working in C ++ and OpenGL 3+ on Windows
For modeling using Blender.
Ive never done it from scratch in opengl but in unity what you do is, if you want for exemple a sword in your characters hand, you give the sword model the position and rotation of the bone that is in the characters hand, and the object(sword) will movea cordingly to the hand.
You can obviously do the same for armor, hair and all kinds of cosmetics.
If you want to change body parts like an arm or hand the prenciple is the same, you can for exemple use a tranparente texture for the part you want to switch and simple put the new hand as mentioned above.
Introduction
First of, I must say this is being done for an online game server, which keeps track of every object in a map, be it a player or an AI (NPC or however you want to call it).
It must not only keep track of them, but notify among the players their near players. I've solved this, and I'm currently using a multi-threaded approach, which perfectly works.
My problem
I'm storing all that objects in an hash table. We could consider that hash table to be an unordered_map, though I'm in fact using the rde::hash_map, as it is faster on inserting and fetching (self tested), though takes more RAM (not an issue now).
The thing is, that map stores a unique ID for the object (64 bits), plus the object pointer, something like:
rde::hash_map<UInt64, Object*>
My problem is:
My application (a server) must run in a loop (inside a thread) which must be called every ~50ms, as to keep things runing smooth. The loop code looks as follows:
void loop()
{
UInt32 prev = clock();
UInt32 prevSleep = 0;
while (1)
{
UInt32 diff = clock() - prev;
prev = clock();
maps.update() // Suppose map is a class, which stores the objects map
if (diff <= 50 + prevSleep)
{
prevSleep = 50 + prevSleep - diff;
sleep(prevSleep);
}
else
prevSleep = 0;
}
}
And now, to the point, the function map::update() which is the one causing the loop increasing to values of 4500ms.
Each time an update is called, the map object must check for new object being added to the store, if an object is added, that object must notify all the other objects of it being added, which I do by (pseudocode):
foreach obectsToBeAdded as joiner:
foreach objectsList as object:
joiner->notify(object);
object->notify(joiner);
Later on, an internal update of each object must be called, I do it by (pseudocode again):
foreach objectsList as object:
object->update();
And, if that was not enough, the above loop must be expanded to:
foreach objectsList as object:
object->update()
// Visit all the other objects
// Called once every 1 sec for the object, not on every call
foreach objectsList as other:
if other != object:
object->visit(other)
My attemp to optimize this
Merge the first loop (adding and notifying) with the update loop, as it follows:
foreach objectsList as object:
foreach objectsToBeAdded as joiner:
object->notify(joiner)
joiner->notify(object)
object->update()
// Called once every 1 sec for the object, not on every call
foreach objectsList as other:
if other != object
object->visit(other)
This works while the objects count is not big, as soon as it increases the loops start to take up to 4 seconds, which goes far beyond to the 50ms I'm looking for.
My question
Is there any other way of optimizing this even more? I've though about using octrees to keep track of the objects positions in the map, but then came to the conclusion that it would only worsen the problem.
I've also divided each map to 35 units (35 is the "view range", LOS) of an entity, so that a given rde::hash_map only contains units which are to be seen by each other, thus that need updates. Works as long as objects count is low...
What else could I do? Thank you!
Note
All those foreach are loops using iterators, like rde::hash_map<...>::iterator from objects.begin() to objects.end()
Other optimitzations, such as not updating if there's is no player (a real user, and not a NPC), freeing memory when no player is on a given map, and such, are already being taken into account.
The first optimization that comes to mind besides spatial segmentation so objects are only informed about changes near them (such as with a quadtree) is: Does EVERY object have to be informed about EVERY change? Why not tell each object, 'Every frame, I'll run your update method. In your update method you can look for everything you want to (for example, there might be a buffer of all changes that occurred this frame/in recent frames) and update yourself as you please'. This way you don't spend CPU cycles notifying objects about things they don't actually need to know or care about.
Also, have you run a CPU profiler on your program, and verified that the hot spots (where the most CPU time is being spent) are where you think they are?
See comments for further discussion:
|
|
\|/
V