How can I check chess rules without a circular dependency? - chess

I'm writing a chess program in C++. I ran into an issue that I probably should have foreseen. The way the program finds all possible moves is by trying to move each piece to every square on the board. The function that does that is called calculateAllPossibleMoves. Each move is tested by cloning the game, and calling move on the piece being tested. The move function will throw an exception when a move is invalid. If no exception is thrown, then that move is valid, and it's added to the list of possible moves.
A move is not valid if it results in your king being in check. So I have a function that uses the find-all-possible moves function (let's call it inCheck) to see whether one of the opponent's pieces checks the king.
The problem is, the aforementioned move function relies on the inCheck function to find out whether the move results in check. inCheck uses calculateAllPossibleMoves to find all the moves that could potentially lead to the king. calculateAllPossibleMoves finds all the possible moves by simulating the move using the normal move function. This code runs forever because it's mutually recursive.
To try to fix it, what I did was introduce an edge case by passing in an integer. So when I call move, it decrements the integer and passes it along, and when move is called again, it is called with a lower number. That way, infinite recursion is not possible.
Still, the results seem to vary, and when I increase the number, the program takes a very long time to run. Is there a cleaner way to solve this problem?

Why don't you have an abstract class ChessPiece inherited by all chess pieces, and 32 of those objects or something in an array of another class Game supporting a class BoardPosition, or something.
Then to list all moves, just go thru the active (not captured) pieces and for each cycle thru their moves (most are direction + number of squares). A move is valid if (1) there is no piece on the way and no same-color piece at the target position AND (2) no opponent's piece not taken by the tested move has in its possible moves the chance to capture your king in the updated board (because that's what check is -- mate just means that you cannot avoid the opponent taking your king)

What you really need is a calculateIntersectingMoves function which simply detects if any pieces have a valid move which intersects the square in question, and call it for check detection.
If calculateAllPossibleMoves is accurately named, it's horribly inefficient to use simply to see if there are any pieces which can reach a specific square; worse, it leads to the exact circularity you mentioned.

Related

Optaplanner, update shadow variables after every step

I am trying to add moves selectors which consider the state of the current working solution. For example, suppose in the cloud balancing problem I was trying to make a move which preferentially moved a process onto a computer which already holds few processes. I have a shadow variable which tracks the number of processes on the computer, then I have a valueSelector which implements SelectionProbabilityWeightFactory that gives a higher weight to computers with fewer processes.
This setup works fine and produces the moves that I want. But it is terribly slow because it is updating the shadow variable far more often than I need it to. Since I am not using this shadow variable for scoring, I don't need it to be updated after every move attempted during the step. I only need the shadow variable to be updated after each accepted move (i.e. the end of the step).
Alternately, I could use a custom move factory, but that requires that every computer have its process count fully re-calculated at each step. This means I would lose the incremental calculation benefit I get with the shadow variables.
So is there a way to force shadow variables to update after each step, rather than after each move. Or is there a better way to track the status of the working solution for use in move selectors?
Bad news first:
It's not possible to have VariableListener only update a shadow variable per step and not per move. And it's unlikely we'll ever want to allow that particular change, as it would hurt the predictability and integrity of the state of the domain model between move iterations. This could create a lot of havoc, including multiple forms of corruptions, if used slightly incorrectly.
Good news next:
Yes, you need to calculate some state per step to generate moves efficiently. This is a common problem I've run into a few times before too.
But why put that on the domain model? It doesn't belong there.
It belongs on the the move selector. For example, if you use a MoveIteratorFactory, that has a method called phaseStarted() (called when the phase starts) and a method createRandomMoveIterator() (called when a step starts even with SelectionCacheType.JIT).
Some something like this should do the trick:
public class MyMoveIteratorFactory implements MoveIteratorFactory<...> {
default void phaseStarted(ScoreDirector<...> scoreDirector) {
}
Iterator<Move_> createRandomMoveIterator(ScoreDirector<...> scoreDirector, Random workingRandom) {
List<Computer> alreadyUsedComputerList = ...; // runs once per step
return new MyIterator(alreadyUsedComputerList, workingRandom);
}
Now, the plot thickens when multiple move selectors need to reuse the same calculation. That's where SupplyManager comes into play, which is not public API. But this is definitely a good requirement for our "move streams API" experiment that we'll do next year.

Simple game design: I'm scared of tons of loops

I started making a simple 2D game than runs on LAN using C++ and SFML library. The game uses a typical update function every frame with its loop to change state of the objects. The game class stores a vector/list of players and monsters and two maps (one for tileset - just graphics, 2nd one holding terrain mechanics - wall, ground etc).
In loop, I call a Think() function (which does move/jump/attack, etc) on every monster (different monsters behave differently but all are inherited from abstract class Monster with theirs appropriate override).
The problem is:
For every monster I need to loop through every other object to check collision
For every monster I need to find near objects (by its coords) so the monster can behave according to what it is seeing
For every non-living object (like flying fireball, any other projectile) I need to update its coords according to passed time (this is easy) but again check collision
For every player I need to loop through all other players/non-lived/monsters to collect information about near objects to send appropriate state of the game to them.
I'm scared how many loops/nested loops this game would have.
I've already seen that some games implement small-instance-based maps world so the loops are always going through small amount of data and since every map is separated its easy to find anything/send update to players.
I could apply this approach to every floor with ease but the floor 0 would be still really huge (array around 5000x5000 tiles to walk on).
I'm thinking now of changing world map array to class that stores references to each object by its coordinates. I just came up with an idea that sorting objects by theirs coords would improve performance of loops or even replace them.
Is this a correct design? Or does exist a better idea?
You should not worry to much about many loops. You can always optimize once you run into problems.
However for the collision you should avoid to check each object against all others, as this will require n^2 checks. Still, this only applies if you really run into performance problems. If this happens, the default approach is to use a grid, which is updated once per frame (or less) to calculate each object's position in the grid. This means each of your cells will know about all objects in it.
Then, if you want to find collisions for a single object, you just check it, with the objects in the same cell and in adjacent cells.
If you have a big amount of objects, you might consider a dynamically adjusting grid, which can be achieved via a quadtree for example. But in most cases a simple statically defined grid should be sufficient.

Colour Highlighting of SIMILAR or ALTERNATIVE blocks of Code

Is there some way to highlight similar or alternative code blocks in xCode or alternative Obj-C program? At the attached picture you can quickly realise which block runs after another or which is an alternative (if-else). (The code on the picture is just example). It seems to be the task related to {}-counting, so I expect there is some implementation.
Actually, I could understand the FLOW of the code on the picture only after I highlighted it as you see.
What you are asking for is scope highlighting. Xcode does not do this to my knowledge. However, you can mouse over the code folding column to the left and see the scope briefly.
Since this is kind of a non-answer, I originally wrote it as a comment. But it got too long, so I'm putting it here. Apologies in advance for avoiding the question. But I'm trying to address the problem behind the question…
If you have to color-code a method to understand it, the method is too long. Extract methods and give them meaningful names that clearly state their purpose (though not their implementation).
Here are rules-of-thumb I follow:
If a method has many local variables, or a number of different indentations, first use Extract Class to pull the method into a new class that works as a function object. Then promote the local variables to ivars.
Despite many who state the dangers, if an inner scope has one line, I omit the braces. This reduces the vertical distance of the code, which makes it more readable. Readability is more important. (But this may be risky if your code isn't covered by unit tests. So make sure the method is well-covered.)
When I see braces inside a method, I try to extract that portion into another (well-named) method.
Look for opportunities to extract the contents of if statements into predicate methods that express the what (burying the how inside the method).
I try to keep methods under six lines. Any more than that, and I start eyeing it critically: Is it doing more than one thing? Is it operating at more than one level of abstraction?
For much, much more on these principles, I highly recommend Clean Code episode 3.

Some doubts about the graph generated by gprof and gprof2dot

I used gprof2dot to generate the graph below, which visualized my program's profiling output.
I have some doubts about the graph:
First, why the root of the call tree isn't main(), and the root Bat_Read() even not appeared in my program, but is declared in the .h file.
Second, GMatrix is a C++ class without explicitly destructor, and it is unreasonable for it to call the two functions in the graph. Almost half of time spending is also illogic.
Third, What is the long function at the bottom of the graph, which spends 6.94 percentages of time ?
You can read the graph in a new tab and magnify it, so you can see it clearly.
I just magnified the image so I could read it.
The function at the bottom is very wide only because it has an extremely long name, but it is only a method _M_Erase of a red-black tree. It is called half a million times from galois_w16_region_multiply. Its size draws your attention to it, but in fact it only appears on about 7% of samples.
If you take every block in the diagram that has no parents, and add up their inclusive percents, you get 100%.
All of this indicates that gprof's method of propagating time upwards through the call graph is flaky, so it thinks things are at the top, when in fact it just couldn't figure out who the caller was.
You can't tell much from this. You might consider alternatives to gprof.
ADDED: Gprof puts some entry code into every function compiled with the -pg flag. So when A calls B, the code in B tries to figure out what routine called it, by using the return address and looking it up in a table of functions. It uses that to increment a counter saying how many times A called B. If for some reason it cannot figure out the correct caller, you get mistakes like you see in this graph. For example, it says that routines
~vector
~GMatrix
galois_w32_region_multby_2
galois_get_log_table
Bat_Read
are at the tops of call chains (have no callers among your functions).
What's more, it thinks that main was called by Bat_Read.
This is typical of gprof.

Getting the world's contactListener in Box2D

I'm writing a game for Mac OS using cocos2D and Box2D. I've added a b2ContactListener subclass to my world as follows:
contactListener = new ContactListener();
world->SetContactListener(contactListener);
This works perfectly, but I am unsure of the best/accepted way to access the contact listener from other classes that don't currently have a direct reference to the contact listener.
I know I can pass a reference to other classes that need it, but what I was wondering is if there is a better way. More specifically, although I can't find a method to do this, is there some equivalent of this:
world->GetContactListener();
in Box2D?
The reason I am trying to do this is simply because I would prefer to move some game logic (i.e. whether a body is able to jump based on information from the contact listener) to the relevant classes themselves, rather than putting everything in the main gameplay class.
Thanks!
A contact listener just serves as an entry point for the four functions BeginContact, EndContact, PreSolve and PostSolve. Typically it has no member variables, so there is no reason to get it, because there is nothing to get from it.
When one of these functions is called during a world Step, you can make a note of which two things touched/stopped touching etc, but you should not change anything in the world right away, until the time step is complete.
I think the crux of this question is the method used to 'make a note' of which things touched, but that's really up to you and depends on what kind of information you need. For example if you're only interested in BeginContact, then the absolute simplest way might be to just store which two fixtures touched as a list of pairs:
std::vector< std::pair<b2Fixture*, b2Fixture*> > thingsThatTouched;
//in BeginContact
thingsThatTouched.push_back( make_pair(contact->GetFixtureA(), contact->GetFixtureB()) );
//after the time step
for (int i = 0; i < thingsThatTouched.size(); i++) {
b2Fixture* fixtureA = thingsThatTouched[i].first;
b2Fixture* fixtureB = thingsThatTouched[i].second;
// ... do something clever ...
}
thingsThatTouched.clear(); //important!!
For this to work you'll need to make the thingsThatTouched list visible from the contact listener function, so it could either be a global variable, or you could set a pointer to it in the contact listener class, or maybe have a global function that returns a pointer to the list.
If you need to keep track of more information such as what things stopped touching, or do something after the time step based on how hard things impacted when they touched etc, it will take a bit more work and becomes more specific. You might find these tutorials useful:
This one uses BeginContact/EndContact to update a list of which other things a body is touching, and uses it to decide if a player can jump at any given time:
http://www.iforce2d.net/b2dtut/jumpability
This one uses a similar method to look at what type of surfaces are currently under a car tire, to decide how much friction the surface has:
http://www.iforce2d.net/b2dtut/top-down-car
This one uses PreSolve to decide whether two bodies (arrow and target) should stick together when they collide, based on the speed of the impact. The actual 'sticking together' processing is done after the time step finishes:
http://www.iforce2d.net/b2dtut/sticky-projectiles
I think you simply can call GetContactList and then process all the contacts using iterator if you need to do it in some other place