how to traverse a grid of numbers using AB-pruning in C++? - c++

Firstly I would like to accept that it is a homework question , but then I know how to code AB-pruning from the algorithm of it . The problem is how to apply it on a grid of numbers where the game can go on in any direction (right , left , up and down ) , thus how will be the tree formed .
Sorry for being a bit vague here , if more info is required then do inquire , I will provide it .

You question is very vague so I can only guess what you are asking:
Are you talking about a game where the player can only move in one of those 4 directions on each turn? If that is the case, your Node will be an (x, y) position of your player on the grid, and each node will branch 4 times (once for each direction) plus maybe 1 if you can stay still.
You say you already know how to code AB-pruning, so is that enough?

Related

How to create an elbow connector from scratch programatically?

An "elbow connector" in MS-Word is a 3-segment line with a control point in the middle as shown
where if I move the yellow control point sideways, then the length of the two lines on either side change accordingly while the end points remain the same. (Please ignore the "2" in the picture)
I am trying to understand how this works so that I can re-create this. Is there a "line equation" for such a line? I have some points (x,y) that are already in the shape of this elbow connector but I would like to incorporate the functionality of changing the lines on either side by controlling the control point. How would I go about re-creating this?
By dissecting the lines like:
For moving the center(M) only sideways, length of lines 2 and 3 remains the same so the problem becomes how to calculate length (and direction) of the lines 1 and 4.
That can be calculated like:
line1_length = B.x - M.x;
line4_length = M.x - A.x;
For directions a comparison should first be made like:
if(B.x > M.x)...
.
.
.
if(M.x > A.x)...
.
.
.
Beginning points is already known as the position of A and the position of B. By knowing the lengths and directions of lines 1 and 4, the end points can be determined.
Good luck!

Find coordinates in a vector c++

I'm creating a game in Qt in c++, and I store every coordinate of specific size into a vector like :
std::vector<std::unique_ptr<Tile>> all_tiles = createWorld(bgTile);
for(auto & tile : all_tiles) {
tiles.push_back(std::move(tile));
}
Each level also has some healthpacks which are stored in a vector aswell.
std::vector<std::unique_ptr<Enemy>> all_enemies = getEnemies(nrOfEnemies);
for(auto &healthPackUniquePtr : all_healthpacks) {
std::shared_ptr<Tile> healthPackPtr{std::move(healthPackUniquePtr)};
int x = healthPackPtr->getXPos();
int y = healthPackPtr->getYPos();
int newYpos=checkOverlapPos(healthPackPtr->getXPos(),healthPackPtr->getYPos());
newYpos = checkOverlapEnemy(healthPackPtr->getXPos(),newYpos);
auto healthPack = std::make_shared<HealthPack>(healthPackPtr->getXPos(), newYpos, healthPackPtr->getValue());
healthPacks.push_back(healthPack);
}
But know I'm searching for the fastest way to check if my player position is at an healthpack position. So I have to search on 2 values in a vector : x and y position. Anyone a suggestion how to do this?
Your 'real' question:
I have to search on 2 values in a vector : x and y position. Anyone a
suggestion how to do this?"
Is a classic XY question, so I'm ignoring it!
I'm searching for the fastest way to check if my player position is at
an healthpack position.
Now we're talking. The approach you are using now won't scale well as the number of items increase, and you'll need to do something similar for every pair of objects you are interested in. Not good.
Thankfully this problem has been solved (and improved upon) for decades, you need to use a spacial partitioning scheme such as BSP, BVH, quadtree/octree, etc. The beauty of the these schemes is that a single data structure can hold the entire world in it, making arbitrary item intersection queries trivial (and fast).
You can implement a callback system. Then a player moves a tile, fire a callback to that tile which the player is on. Tiles should know its state and could add health to a player or do nothing if there is nothing on that tile. Using this technique, you don`t need searching at all.
If all_leathpacks has less than ~50 elements I wouldn't bother to improve. Simple loop is going to be sufficiently fast.
Otherwise you can split the vector into sectors and check only for the elements in the same sector as your player (and maybe a few around if it's close to the edge).
If you need something that's better for the memory you and use a KD-tree to index the healtpacks and search for them fast (O(logN) time).

3D sound effects in space shooter game

I am trying to implement a 3d sound system for my space shooter game . I have everything ready (playng sound with different volume in each side etc.) but i cant find the corrent formula to calculate the correct volume for each side.
The general idea is that every time the player(ship) kill's an enemie (the cammera is always on the top of the ship) , an explotion will be heard with the correct left and right volume . So if the enemie is right of the ship then the right channel will be heard more , same with the left case.
so i have
vector ship
vector enemie
and
playSound(left ? ,right ?)
How does game engines calculate the left and right channels?
Finally i solved it. I used something similar to what Ameoo said.
Here it is:
void Play3D(int id,vector3d ship,vector3d pos,float arenaWidth,float power)
{
float disright=calculate_distance(ship.x+0.2f,ship.y,pos.x,pos.y);
float disleft=calculate_distance(ship.x-0.2f,ship.y,pos.x,pos.y);
sf.Play(2,1-disleft/arenaWidth*power,1-disright/arenaWidth*power);
}

Shortest path with figures on board

I'm having trouble with my homework assignment(C++). I'm not asking for the complete solution, but tilt in the right direction could be helpful. :)
I have a NxN board (max N = 100) and a 1x2 figure (cube) on that board. The cube is painted red on the one side and blue on the other. Default position for the cube is left upper angle of the board, blue side up:
B B . .
. . . .
. . . .
. . . .
(4x4 example, B stands for blue)
There could be stones (obstacles) on the blackboard.
Moves I can make with my figure:
rotating it for 90/180/270 degrees clockwise
you can flip the cube around its right/left/upper/lower edge, changing its ''upward color''
For an example, using flip right on the default position:
. . R R
. . . .
. . . .
. . . .
and then using rotate 90:
. . R .
. . R .
. . . .
. . . .
and then using flip left:
. B . .
. B . .
. . . .
. . . .
Of course, when rotating or flipping, you cannot land on the stone.
So, the problem is - for any given configuration of the board (figure position and stone positions) write a program that will ''bring the cube home'' in the default position (blue side upwards!) using minimal number of moves and return 1 if that's possible or return 0 if that's impossible.
I find this problem interesting, but I have to admit I'm slightly confused with it. Especially the blue side/red side part. I can't really figure out how to ''translate'' those moves I can use in the language of usual shortest path algorithms (and I never used any of these).
So, I would be grateful for every piece of advice you can give! :)
First, since you are asked to find the exact optimal path, I would go with Dijksta's algorithm.
For this algorithm, you'll need:
A function which gives the next
possible move.
A function which tell you if a position was already
visited.
A function which tell you the total cost of each path.
And of course a function which tell you when you've reached the final
position
Given an initial position, your cube can reach exactly 7 new positions. It's easy to pick which ones are possible.
G is simply the number of moves you've made so far + 1 for the next move :)
I would use a hashtable to keep track of the visited position. (This is probably the most difficult function to write), but you don't need to over think it right now. A simple vector and a term-by-term comparison would do. You can optimize this once your code is running.
And finally, you need to check if the cube is in its initial position blue side upwards.
You can interpret each possible 1x2 block and a color (red or blue) combination as a vertex and moves as edges. If it is possible to reach a particular 1x2 block and color combination (vertex) from some other combination in one move then there is a connection (edge) between those two combinations. Then you have to find shortest path between the given configuration and "home" configuration in the resulting graph (probably Breadth-first search since cost of the move is the same no matter what move you perform).
And if want to go further you can use advanced graph search algorithms that use heuristics during the graph traversal (heuristic being the minimum amount of moves needed to reach destination assuming there are no obstacles on the blackboard). For example you can use A* algorithm.
When dealing with this kind of problems, the first thing to do is to find a representation of the state of your problem.
In this case, you need:
Two integers which represents the top-left position of your figure
One boolean which represents the color of the figure (red/blue)
One boolean which represents the orientation of the figure (horizontal/vertical)
If you are familiar with bitmasks, you should use just a 32 bit integer to do this (8 bits for x position, 8 bits for y position, 2 bits for the rest).
In this way you don't need to implement a comparison operator.
OR
You define a simple struct (call it state) with these 3 information and a strict-ordering comparison on this (this is only needed to put state in std::set.
After this, you can solve this problem using a BFS.
To do that, you need:
An std::map<state,state> to store the position you already visited in the key, and the position you came from in the value (replace map with unordered_map if you can use c++11 and you use a bitmask to store your state)
A std::queue<state> in which push and pop up the states to be processed.
Some code to determine every possible state reachable from a given one (i.e. implements all the possible moves, taking care of the board dimension)
Pseudo code:
map<state,state> visited;
queue<state> to_be_processed;
visited.insert( initial_state,initial_state); //you are not coming from anywhere
to_be_processed.push ( initial_state);
while(!to_be_processed.empty()) {
state cur = to_be_processed.pop();
if ( cur == end_state) //you are done
{
//to get the path from initial_state to end_state you have just to walk visited in the inverse order.
return 1;
}
for ( i = every possible state reachable from cur) {
if (visited.count(i) != 0) continue; //already visited
to_be_processed.push(i);
visited.insert(i,cur); //i has been visited, and you reached i from cur
}
}
return 0; //if you get here, no way
The presence of obstacles make just the problem more difficult to code, but is no conceptually different.
Note that in this case BFS works because the cost you pay for going from one state to another is always the same.

BFS algorithm - shortest walk on grid with constrained steps

The problem is as follows: A wanderer begins on the grid coordinates (x,y) and wants to reach the coordinates (0,0). From every gridpoint, the wanderer can go 8 steps north OR 3 steps south OR 5 steps east OR 6 steps west (8N/3S/5E/6W).
How can I find the shortest route from (X,Y) to (0,0) using breadth-first search?
Clarifications:
Unlimited grid
Negative coordinates are allowed
A queue (linked list or array) must be used
No obstacles present
The algorithm for this problem would be:
For each axis, step towards it until your position on the other axis is 0.
Pseudocode:
while (x!=0) {
if (x>0) x-=6;
else x+=5;
}
while (y!=0) {
if (y>0) y-=8;
else y+=3;
}
However, I don't understand why you need to search for a route - it's not that complicated.
As "thejh" remarked there's no need for a search, but your assignment calls for one.
A reasonable approach is
Analyze. Is it all possible for arbitrary (x, y) starting position? Checking the allowed moves you see that they can be combined to yield 1-step horizontal moves, and 1-step vertical moves, so the answer to that is yes (for your hand-in provide the details of this).
Figure out what "breadth-first search" is. Wikipedia is your friend (although, if you have access to a university library, I really do recommend Patrick Henry Winston's old Artifical Intelligence, it's really good, very lucid explanations). Try it out with some simpler problem.
Do the assignment's problem in just about the same way. Ask here if you encounter any technical C++ problem.
Cheers & hth.,
Here's my answer (really based off of thejh's answer) that uses a queue:
//set x to start position
//set y to start position
do {
if (x<0) Queue.Push(8N);
if (x>0) Queue.Push(3S);
if (y<0) Queue.Push(5E);
if (y>0) Queue.Push(6W);
while (!Queue.Empty())
{
Move(Queue.Pop());
}
} while (x && y);
It's convoluted, but follows the directions.
I'm going to go ahead and answer my own question for future reference.
Psuedocode:
while (true) {
if (destination reached)
break;
addToQueue(go north);
addToQueue(go south);
addToQueue(go east);
addToQueue(go west);
getNextFromQueue;
}
It should also be noted that the execution time for this application grows very, very fast, so test it out with small coordinate values. For example, the coordinates (1,1) gives 7 levels of breadth and requires 16384 iterations.