I'm doing a self-educational research on finite state machines. And currently stumbled upon interesting but non-trivial task to accomplish. It is really hard to define state machine for the rules of game of chess.
Though the rules seem simple the game itself is hard to approach using FSM. I was thinking about encoding game state as a state of board, where each square is either empty or contains some piece. But it becomes hard to define transitions, because the transition should be aware of facts that concern the neighborhood of the subject cell. It is also hard to define transitions for cases like en-passant or castling, especially when castling is blocked by some other piece. The same way it is hard to define move limitations for pieces that are blocked by other pieces and are not capable to jump them, i.e. pawns, bishops, rooks, queens.
How would you approach this problem? Or maybe there are some extensions to FSM that I'm not aware of. I'm pretty sure that there are a lot of similar applications where FSM will be impractical to use. How would you deal with this problem in general case.
Thank you in advance,
In your approach each state would be a matrix of fields, where each field has a specific state, which is a composition of the color and the chess piece that is placed on it and chess pieces themselves are a composition of the color of the chess-piece and it's type (pawn, rook, etc.). So you can easily define rules by utilizing these matrices:
Example for pawn:
Initial state:
C D E
5 (W , (X , ?)) (B , (P , B)) (W , (P , B))
4 (B , (P , W)) (W , (X , ?)) (B , (P , W))
Now we can evalute rules for moving the two white figures based on this rule:
A pawn can move straight forward, if it's not blocked by another figure, or it can beat the figure that is placed diagonally one block away from it. Building the transition-table for the above state with a white move next can be done in the following way:
S1->(a)X (just the standard way to define a transition)
a would be the figure, we want to move and S2 the resulting state
X are the reachable state.
a = Pawn at C4
we have two options evaluating the field:
C5 is free, so we can move the pawn to that field
D5 is held by a black pawn, so we can beat it and move to that field
a = Pawn at E4
E5 not free, we can't move ahead
D5 is held by a black pawn, which we can beat
Translating this into math shouldn't be too hard. The state transition-table for each state would include all possible moves for all figures. The resulting machine would be a NFA.
Another option would be to define transitions as a pair of the chess piece you want to move and where you want to move it. That'd allow you to construct a DFA.
Related
I built conway's game of life and its working fine but my game after many generations is either ending with no lives or reaching a stable pattern which it can't escape.
For example I have followed these rules
Any live cell with fewer than two live neighbours dies, as if by underpopulation.
(live_cell = True and neighourhood < 2)
Any live cell with two or three live neighbours lives on to the next generation.
(live_cell = True and neighourhood == 2 or neighourhood == 3)
Any live cell with more than three live neighbours dies, as if by overpopulation.
(live_cell = True and neighourhood > 3)
Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
(live_cell = False and neighourhood == 3)
This is my game of life matrix where 1 is life and 0 not
000000
001000
010100
001000
000000
000000
and this is its corresponding neighbourhood maps created by my programe
011100
122210
124210
122210
011100
000000
After reaching this pattern even after thousands of generation its still stuck in this pattern itself. I dont know how to escape this pattern ?
If the space is finite, then the number of possible configurations is finite and then the GoL will end either in a stable pattern or in a loop. If the space is very small (as it looks like) then you will observe only stupid behavior. You need at least to use a much bigger space (500x500), fill it with 1's at many places and look; that is the basic play with GoL. The next step is to build interesting configurations, and there exists a lot that have been discovered over time, for examples see GoL Pattern Library. Basic well-known patterns are gliders, glider-guns, oscillators... You will discover that GoL is in fact a very interesting way of programming: the initial configuration is a program code executed by the machine that you can see evolving on your screen. But that programming is not so easy, especially if you want to obtain a specific behavior!
I am given the above system for atomic propositions {a,b,c}.
I'm then meant to say if certain LTL formulae hold (such as ♢☐c).
I understand what the LTL formulae mean (eventually forever c holds) but I have no idea how to read the diagram and relate it to the LTL.
I assume it's like a flow chart in that we start from the top left, /{a} and can go through the different states. But what does each of it mean divided by a?
Looks like FSM/transduser rather than a Kripke structure. Input/output or more generally precondition/postcondition is a common notation for FSM and its kin. precondition/postcondition (a and b and ...) / (x and y and...). So a in the state q1. In next states either only b in q4 or b and c or q3. Might be of course or instead of and in precondition, otherwise the system might halt..
I'm working on a game in Yoyo Game Maker where I have items moving along conveyor belts. As the items only move in one direction, I thought it would make most sense to use a queue or queue-like data structure to store the items. However, to be able to render the items, I need to be able to read all of them at any point in the queue, not just the head or tail.
[[a] [b] [c] [d]]
|
V
a <- [[ ] [b] [c] [d]] <- e
|
V
[[b] [c] [d] [e]]
| | | |
V V V V
b c d e
I could simply use an array that manually moves all its values forward by one slot every turn (using a for loop), but somehow that seems inefficient, laggy, or at the very least, bad form. My programming instincts recoil at the thought of using such a system, anyway.
Is this a correct assumption to make? Is an array really the best way of implementing a structure like this? Should I even be worried about efficiency, or are the differences in this case negligible?
Some advice or examples (in any programming language) would be greatly appreciated.
It might "seem" inefficient to use an array, but it most likely won't be. Take into consideration how many items will actually be on the conveyor belt at any single time. If you want quick random access to any index in a data structure, you must use an array, a DS List or a DS Grid(wouldn't make sense here, tough).
Using a DS List, you can use ds_list_delete(your_list, 0) to 'dequeue', much like a DS Queue, and ds_list_insert(your_list, 0, value) to 'enqueue' an item.
Iterating through the list is then very simple:
for ( var i = 0; i < ds_list_size( your_list ); i++ ) {
var item = your_list[|i];
}
It might also be relevant to add, that, in a game I'm working on, objects are build using components, which basically means that all of the enemies, the player, and such have a for-loop in their Step events to iterate through and update all components if need be. At most I have about 80 such objects in the game at any time and performance hasn't been a problem yet.
You should always first try to get a working solution, then testing it in conditions specific to your game: eg. if you are going to need a 100 items in the structure, try that, and if the performance is not satisfactory, only then optimize.
I had made a game in game maker which had a similar requirement. If you know about the frog game it had some woods floating on a river.
Movement: For that, I had created some number of the wood object which moves in the particular direction. when frog collides with any one of them he/she starts to float in that direction. Also, if it goes out if window in one direction I would place it back at the other side of window.
Picking: I think to pick up one of the item, You will need to define the collision inside each object. After collision you can define you next steps.
I was given a brain puzzle from lonpos.cc as a present. I was curius of how many different solutions there were, and I quite enjoy writing algorithms and code, so I started writing an application to brute force it.
The puzzle looks like this : http://www.lonpos.cc/images/LONPOSdb.jpg / http://cdn100.iofferphoto.com/img/item/191/498/944/u2t6.jpg
It's a board of 20x14 "points". And all puzzle pieces can be flipped and turned. I wrote an application where each piece (and the puzzle) is presented like this:
01010
00100
01110
01110
11111
01010
Now my application so far is reasonably simple.
It takes the list of pieces and a blank board, pops of piece #0
flips it in every direction, and for that piece tries to place it for every x and y coordinate. If it successfully places a piece it passes a copy of the new "board" with some pieces taken to a recursive function, and tries all combinations for their pieces.
Explained in pseudocode:
bruteForce(Board base, List pieces) {
for (Piece in pieces.pop, piece.pop.flip, piece.pop.flip2...) {
int x,y = 0;
if canplace(piece, x, y) {
Board newBoard = base.clone();
newBoard.placePiece(piece, x, y);
bruteForce(newBoard, pieces);
}
## increment x until x > width, then y
}
}
Now I'm trying to find out ways to make this quicker. Things I've thought of so far:
Making it solve in parallel - Implemented, now using 4 threads.
Sorting the pieces, and only trying to place the pieces that will fit in the x,y space we're trying to fit. (Aka if we're on the bottom row, and we only have 4 "points" from our position to the bottom, dont try the ones that are 8 high).
Not duplicating the board, instead using placePiece and removePiece or something like it.
Checking for "invalid" boards, aka if a piece is impossible to reach (boxed in completely).
Anyone have any creative ideas on how I can do this quicker? Or any way to mathematically calculate how many different combinations there are?
I don't see any obvious way to do things fast, but here are some tips that might help.
First off, if you ignore the bumps, you have a 6x4 grid to fill with 1x2 blocks. Each of the blocks has 6 positions where it can have a bump or a hole. Therefore, you're trying to find an arrangement of the blocks such that at each edge, a bump is matched with a hole. Also, you can represent the pieces much more efficiently using this information.
Next, I'd recommend trying all ways to place a block in a specific spot rather than all places to play a specific block anywhere. This will reduce the number of false trails you go down.
This looks like the Exact Cover Problem. You basically want to cover all fields on the board with your given pieces. I can recommend Dancing Links, published by Donald Knuth. In the paper you find a clear example for the pentomino problem which should give you a good idea of how it works.
You basically set up a system that keeps track of all possible ways to place a specific block on the board. By placing a block, you would cover a set of positions on the field. These positions can't be used to place any other blocks. All possibilities would then be erased from the problem setting before you place another block. The dancing links allows for fast backtracking and erasing of possibilities.
I'm working on a game where on each update of the game loop, the AI is run. During this update, I have the chance to turn the AI-controlled entity and/or make it accelerate in the direction it is facing. I want it to reach a final location (within reasonable range) and at that location have a specific velocity and direction (again it doesn't need to be exact) That is, given a current:
P0(x, y) = Current position vector
V0(x, y) = Current velocity vector (units/second)
θ0 = Current direction (radians)
τmax = Max turn speed (radians/second)
αmax = Max acceleration (units/second^2)
|V|max = Absolute max speed (units/second)
Pf(x, y) = Target position vector
Vf(x, y) = Target velocity vector (units/second)
θf = Target rotation (radians)
Select an immediate:
τ = A turn speed within [-τmax, τmax]
α = An acceleration scalar within [0, αmax] (must accelerate in direction it's currently facing)
Such that these are minimized:
t = Total time to move to the destination
|Pt-Pf| = Distance from target position at end
|Vt-Vf| = Deviation from target velocity at end
|θt-θf| = Deviation from target rotation at end (wrapped to (-π,π))
The parameters can be re-computed during each iteration of the game loop. A picture says 1000 words so for example given the current state as the blue dude, reach approximately the state of the red dude within as short a time as possible (arrows are velocity):
Pic http://public.blu.livefilestore.com/y1p6zWlGWeATDQCM80G6gaDaX43BUik0DbFukbwE9I4rMk8axYpKwVS5-43rbwG9aZQmttJXd68NDAtYpYL6ugQXg/words.gif
Assuming a constant α and τ for Δt (Δt → 0 for an ideal solution) and splitting position/velocity into components, this gives (I think, my math is probably off):
Equations http://public.blu.livefilestore.com/y1p6zWlGWeATDTF9DZsTdHiio4dAKGrvSzg904W9cOeaeLpAE3MJzGZFokcZ-ZY21d0RGQ7VTxHIS88uC8-iDAV7g/equations.gif
(EDIT: that last one should be θ = θ0 + τΔt)
So, how do I select an immediate α and τ (remember these will be recomputed every iteration of the game loop, usually > 100 fps)? The simplest, most naieve way I can think of is:
Select a Δt equal to the average of the last few Δts between updates of the game loop (i.e. very small)
Compute the above 5 equations of the next step for all combinations of (α, τ) = {0, αmax} x {-τmax, 0, τmax} (only 6 combonations and 5 equations for each, so shouldn't take too long, and since they are run so often, the rather restrictive ranges will be amortized in the end)
Assign weights to position, velocity and rotation. Perhaps these weights could be dynamic (i.e. the further from position the entity is, the more position is weighted).
Greedily choose the one that minimizes these for the location Δt from now.
Its potentially fast & simple, however, there are a few glaring problems with this:
Arbitrary selection of weights
It's a greedy algorithm that (by its very nature) can't backtrack
It doesn't really take into account the problem space
If it frequently changes acceleration or turns, the animation could look "jerky".
Note that while the algorithm can (and probably should) save state between iterations, but Pf, Vf and θf can change every iteration (i.e. if the entity is trying to follow/position itself near another), so the algorithm needs to be able to adapt to changing conditions.
Any ideas? Is there a simple solution for this I'm missing?
Thanks,
Robert
sounds like you want a PD controller. Basically draw a line from the current position to the target. Then take the line direction in radians, that's your target radians. The current error in radians is current heading - line heading. Call it Eh. (heading error) then you say the current turn rate is going to be KpEh+d/dt EhKd. do this every step with a new line.
thats for heading
acceleration is "Accelerate until I've reached max speed or I wont be able to stop in time". you threw up a bunch of integrals so I'm sure you'll be fine with that calculation.
I case you're wondering, yes I've solved this problem before, PD controller works. don't bother with PID, don't need it in this case. Prototype in matlab. There is one thing I've left out, you need to have a trigger, like "i'm getting really close now" so I should start turning to get into the target. I just read your clarification about "only accelerating in the direction we're heading". that changes things a bit but not too much. that means to need to approach the target "from behind" meaning that the line target will have to be behind the real target, when you get near the behind target, follow a new line that will guide you to the real target. You'll also want to follow the lines, rather than just pick a heading and try to stick with it. So don't update the line each frame, just say the error is equal to the SIGNED DISTANCE FROM THE CURRENT TARGET LINE. The PD will give you a turn rate, acceleration is trivial, so you're set. you'll need to tweak Kd and Kp by head, that's why i said matlab first. (Octave is good too)
good luck, hope this points you in the right direction ;)
pun intended.
EDIT: I just read that...lots of stuff, wrote real quick. this is a line following solution to your problem, just google line following to accompany this answer if you want to take this solution as a basis to solving the problem.
I would like to suggest that yout consider http://en.wikipedia.org/wiki/Bang%E2%80%93bang_control (Bang-bang control) as well as a PID or PD. The things you are trying to minimise don't seem to produce any penalty for pushing the accelerator down as far as it will go, until it comes time to push the brake down as far as it will go, except for your point about how jerky this will look. At the very least, this provides some sort of justification for your initial guess.