I was wondering, which are the most commonly used algorithms applied to finding patterns in puzzle games conformed by grids of cells.
I know that depends of many factors, like the kind of patterns You want to detect, or the rules of the game...but I wanted to know which are the most commonly used algorithms in that kind of problems...
For example, games like columns, bejeweled, even tetris.
I also want to know if detecting patterns by "brute force" ( like , scanning all the grid trying to find three adyacent cells of the same color ) is significantly worst that using particular algorithms in very small grids, like 4 X 4 for example ( and again, I know that depends of the kind of game and rules ...)
Which structures are commonly used in this kind of games ?
It's always domain-dependent. But there's also two situations where you'd do these kinds of searches. Ones situation is after a move (a change to the game field made by the player), and the other would be if/when the whole board has changed.
In Tetris, you wouldn't need to scan the whole board after a piece is dropped. You'd just have to search the rows the piece is touching.
In a match-3 games like Bejeweled, where you're swapping two adjacent pieces at a time, you'd first run a localized search in each direction around each square that changed, to see if any pieces have triggered. Then, if they have, the game will dump some new, random pieces onto the board. Now, you could run the same localized search around each square that's changed, but that might involve a lot of if statements and might actually be slower to just scanning the whole board from top left to bottom right. It depends on your implementation and would require profiling.
As Adrian says, a simple 2D array suffices. Often, though, you may add a "border" of pixels around this array, to simplify the searching-for-patterns aspect. Without a border, you'd have to have if statements along the edge squares that says "well, if you're in the top row, don't search up (and walk off the array)". With a border around it, you can safely just search through everything: saving yourself if statements, saving yourself branching, saving yourself pipeline issues, searching faster.
To Jon: these kinds of things really do matter in high-performance settings, even on modern machines, if you're making a search algorithm to play/solve the game. If you are, you want your underlying simulation to run as quickly as possible in order to search as deep as possible in the fewest cycles.
Regarding algorithms: It certainly depends on the game. For example for tetris, you'd only have to scan each row if it has the same color. I can't even think of something that would not equal the brute force approach in this case. But for most casual games brute force should be perfectly fine. Pattern recognition should be negligible in comparison to graphics and sound processing.
Regarding structures: A simple 2D-Array should suffice for representing the board.
Given the average computer speed these days, if it's real-time as the user is playing the game, it probably won't matter (EDIT: for very small game boards only). Certainly, it would depend on the complexity of the game logic, but also how fast the code is going to run on the target machine (i.e., is this a JavaScript web page game, or a Windows app written in C++).
If this is for something like simulating gameplay strategies, then use an algorithm that's more efficient.
A more efficient strategy could involve keeping track of incremental changes to the game board, instead of re-scanning the whole board every time.
Related
I'm a relatively inexperienced programmer, and recently I've been getting interested in making a Checkers game app for a school project. I'm not sure where I can start (or if I should even attempt) at creating this. The project I have in mind probably wouldn't involve much more than a simple AI & a multiplayer player mode.
Can anyone give some hints / guidance for me to start learning?
To some extent I agree with some of the comments on the question that suggest 'try something simpler first', but checkers is simple enough that you may be able to get a working program - and you will certainly learn useful things as you go.
My suggestion would be to divide the problem into sections and solve each one in turn. For example:
1) Board representation - perhaps use an 8x8 array to represent the board. You need to be able to fill a square with empty, white piece, black piece, white king, black king. A more efficient solution might be to have a look at 'bit-boards' in which the occupancy of the board is described by a set of 64-bit integers. You probably want to end up with functions that can load or save a board state, print or display the board, and determine what (if anything ) is at some position.
2) Move representation - find a way to calculate legal moves. Which pieces can move and where they can move to. You will need to take into account - moving off the edges of the board, blocked moves, jumps, multiple jumps, kings moving 'backwards' etc. You probably want to end up with functions that can calculate all legal moves for a piece, determine if a suggested move is legal, record a game as a series of moves, maybe interface with the end user so by mousing or entering text commands you can 'play' a game on your board. So even if you only get that far then you have a 'product' you can demonstrate and people can interact with.
3) Computer play - this is the harder part - You will need to learn about minimax, alpha-beta pruning, iterative deepening and all the associated guff that goes into computer game AI - some of it sounds harder than it actually is. You also need to develop a position evaluation algorithm that measures the value of a position so the computer can decide which is the 'best' move to make. This can be as simple as the naive assumption that taking an opponents piece is always better than not taking one, that making a king is better than not making one, or that a move that leaves you with more future moves is better than one that leaves you with less choices for your next move. In practice, even a very simple 'greedy' board evaluation can work quite well if you can look 2-3 moves ahead.
All in all though, it may be simpler to look at something a little less ambitious than checkers - Othello is possibly a good choice and it is not hard to write an Othello player that can thrash a human who hasn't played a lot of the game. 3D tic-tac-toe, or a small dots-and-boxes game might be suitable too. Games like these are simpler as there are no kings or boundaries to complicate things, all (well most) moves are legal and they are sufficiently 'fun' to play to be a worthwhile software demonstration.
First let me state, the task you are talking about is a lot larger then you think it is.
How you should do it is break it down into very small manageable pieces.
The reasons are
Smaller steps are easier to understand
Getting fast feed back will help inspire you to continue and will help you fix things as they go wrong.
As you start think of the smallest step possible of something to do. Here are some ideas of parts to start:
Make a simple title screen- Just the title and to hit a key for it to
go away.
make the UI for an empty checkerboard grid.
I know those sound like not much but those will probably take much ore time than you think.
then add thing like adding the checkers, keeping the the gameboard data etc.,
Don't even think about AI until you have a game that two players can play with no UI.
What you should do is think about: what is the smallest increment I can do and add that, add that and then think about what the next small piece is.
Trust me this is the best way about going about it. If you try to write everything at once it will never happen.
I'm making a Sokoban style game (i.e. it's not exactly the same as Sokoban so I can't use existing levels) and would like to create random levels on it so a player could keep playing it and always have levels to try. Are there any ways I can get the computer to generate levels for me automatically or semi-automatically (by semi, I mean I could give it the initial map perhaps but without the crate positions)?
One idea I had was to randomly generate a map, place the crates in their finishing state (i.e. on the crosses) and then randomly move the crates as if they were being pulled by the game character. This guarantees me that the level should be solvable. However, the main problem would be how to know if the level is easy/hard and interesting/boring? For example, Sokoban is NP-hard so I couldn't realistically ask the machine to then check if there was an easy solution.
I know it would be hard to create random levels that would compete with human experts but I'm just looking for something that is decent.
Edit: By the way, I would be more interested in generating small but interesting Sokoban-like levels e.g. 5x5 levels instead of 50x50 levels. This may make things more computationally feasible.
This site has a number of Sokoban level generators: http://www.erimsever.com/sokoban7.htm
You may find it useful to look at how they work.
I have been playing around with Conway's Game of life and recently discovered some amazingly fast implementations such as Hashlife and Golly. (download Golly here - http://golly.sourceforge.net/)
One thing that I cant get my head around is how do coders implement the infinite grid? We can't keep an infinite array of anything, if you run golly and get a few gliders to fly off past the edges, wait for a few mins and zoom right out, you will see the gliders still there out in space running away, so how in gods name is this concept of infinity dealt with programmatically? Is there a well documented pattern or what?
Many thanks
It is possible to represent living nodes with some type of sparse matrix in this situation. For instance, if we store a list of (LivingNode, Coordinate) pairs instead of an array of Nodes where each is either living or dead, we are simply changing the Coordinates rather than increasing an array's size. Thus, the space required for this is proportional to the number of LivingNodes.
This solution doesn't work for states where the number of living nodes is constantly increasing, but it works very well for gliders.
EDIT: So that was off the top of my head. Turns out Wikipedia has an article that shows a much more well-thought out solution. Oh well! :) Enjoy.
Wikipedia explains it.
The basic idea is that Conway's Game of Life exhibits locality, since information travels at a slow speed compared to the pattern size and the maximum density of filled cells is around 1/2 of the cells in any region. (More will kill off cells due to overcrowding.)
Since there is locality, you can separate the field in different sections and simulate each section independently. If you choose your locality well, you will often see the same patterns. You can simulate how those evolve and store the results in a lookup table, so that other instances of the same pattern do not need to be simulated more than once. Combining adjacent patterns into larger 'metapatterns' allows you to precalculate those as well, and so on.
Can someone give me some pointers on how I should implement the artificial intelligence (human vs. computer gameplay) for a Puyo Puyo game? Is this project even worth pursuing?
The point of the game is to form chains of 4 or more beans of the same color that trigger other chains. The longer your chain is, the more points you get. My description isn't that great so here's a simple video of a game in progress: http://www.youtube.com/watch?v=K1JQQbDKTd8&feature=related
Thanks!
You could also design a fairly simple expert system for a low-level difficulty. Something like:
1) Place the pieces anywhere that would result in clearing blocks
2) Otherwise, place the pieces adjacent to same-color pieces.
3) Otherwise, place the pieces anywhere.
This is the basic strategy a person would employ just after becoming familiar with the game. It will be passable as a computer opponent, but it's unlikely to beat anybody who has played more than 20 minutes. You also won't learn much by implementing it.
Best strategy is not to kill every single chain as soon as possible, but assemble in a way, that when you brake something on top everything collapse and you get lot of combos. So problem is in assembling whit this combo strategy. It is also important that there is probably better to make 4 combos whit 5 peaces that 5 combos whit 4 peaces (but i am not sure, check whit scoring)
You should build big structure that allows this super combo moves. When building this structure you have also problem, that you do not know, which peace you will you get (except for next peace), so there is little probability involved.
This is very interesting problem.
You can apply:
Dynamic programming to check the current score.
Monte Carlo for probability needs.
Little heuristics (heuristics always solve problem faster)
In general I would describe this problem as optimal positioning of peaces to maximise probability of win. There is no single strategy, because building bigger "heap" brings greater risk for loosing game.
One parameter of how good your heap is can be "entropy" - number of single/buried peaces, after making combo.
The first answer that comes to mind is a lookahead search with alpha-beta pruning. Is it worth doing? Perhaps as a learning exercise.
I'm developing a game which features a sizeable square 2d playing area. The gaming area is tileless with bounded sides (no wrapping around). I am trying to figure out how I can best divide up this world to increase the performance of collision detection. Rather than checking each entity for collision with all other entities I want to only check nearby entities for collision and obstacle avoidance.
I have a few special concerns for this game world...
I want to be able to be able to use a large number of entities in the game world at once. However, a % of entities won't collide with entities of the same type. For example projectiles won't collide with other projectiles.
I want to be able to use a large range of entity sizes. I want there to be a very large size difference between the smallest entities and the largest.
There are very few static or non-moving entities in the game world.
I'm interested in using something similar to what's described in the answer here: Quadtree vs Red-Black tree for a game in C++?
My concern is how well will a tree subdivision of the world be able to handle large size differences in entities? To divide the world up enough for the smaller entities the larger ones will need to occupy a large number of regions and I'm concerned about how that will affect the performance of the system.
My other major concern is how to properly keep the list of occupied areas up to date. Since there's a lot of moving entities, and some very large ones, it seems like dividing the world up will create a significant amount of overhead for keeping track of which entities occupy which regions.
I'm mostly looking for any good algorithms or ideas that will help reduce the number collision detection and obstacle avoidance calculations.
If I were you I'd start off by implementing a simple BSP (binary space partition) tree. Since you are working in 2D, bound box checks are really fast. You basically need three classes: CBspTree, CBspNode and CBspCut (not really needed)
CBspTree has one root node instance of class CBspNode
CBspNode has an instance of CBspCut
CBspCut symbolize how you cut a set in two disjoint sets. This can neatly be solved by introducing polymorphism (e.g. CBspCutX or CBspCutY or some other cutting line). CBspCut also has two CBspNode
The interface towards the divided world will be through the tree class and it can be a really good idea to create one more layer on top of that, in case you would like to replace the BSP solution with e.g. a quad tree. Once you're getting the hang of it. But in my experience, a BSP will do just fine.
There are different strategies of how to store your items in the tree. What I mean by that is that you can choose to have e.g. some kind of container in each node that contains references to the objects occuping that area. This means though (as you are asking yourself) that large items will occupy many leaves, i.e. there will be many references to large objects and very small items will show up at single leaves.
In my experience this doesn't have that large impact. Of course it matters, but you'd have to do some testing to check if it's really an issue or not. You would be able to get around this by simply leaving those items at branched nodes in the tree, i.e. you will not store them on "leaf level". This means you will find those objects quick while traversing down the tree.
When it comes to your first question. If you only are going to use this subdivision for collision testing and nothing else, I suggest that things that can never collide never are inserted into the tree. A missile for example as you say, can't collide with another missile. Which would mean that you dont even have to store the missile in the tree.
However, you might want to use the bsp for other things as well, you didn't specify that but keep that in mind (for picking objects with e.g. the mouse). Otherwise I propose that you store everything in the bsp, and resolve the collision later on. Just ask the bsp of a list of objects in a certain area to get a limited set of possible collision candidates and perform the check after that (assuming objects know what they can collide with, or some other external mechanism).
If you want to speed up things, you also need to take care of merge and split, i.e. when things are removed from the tree, a lot of nodes will become empty or the number of items below some node level will decrease below some merge threshold. Then you want to merge two subtrees into one node containing all items. Splitting happens when you insert items into the world. So when the number of items exceed some splitting threshold you introduce a new cut, which splits the world in two. These merge and split thresholds should be two constants that you can use to tune the efficiency of the tree.
Merge and split are mainly used to keep the tree balanced and to make sure that it works as efficient as it can according to its specifications. This is really what you need to worry about. Moving things from one location and thus updating the tree is imo fast. But when it comes to merging and splitting it might become expensive if you do it too often.
This can be avoided by introducing some kind of lazy merge and split system, i.e. you have some kind of dirty flagging or modify count. Batch up all operations that can be batched, i.e. moving 10 objects and inserting 5 might be one batch. Once that batch of operations is finished, you check if the tree is dirty and then you do the needed merge and/or split operations.
Post some comments if you want me to explain further.
Cheers !
Edit
There are many things that can be optimized in the tree. But as you know, premature optimization is the root to all evil. So start off simple. For example, you might create some generic callback system that you can use while traversing the tree. This way you dont have to query the tree to get a list of objects that matched the bound box "question", instead you can just traverse down the tree and execute that call back each time you hit something. "If this bound box I'm providing intersects you, then execute this callback with these parameters"
You most definitely want to check this list of collision detection resources from gamedev.net out. It's full of resources with game development conventions.
For other than collision detection only, check their entire list of articles and resources.
My concern is how well will a tree
subdivision of the world be able to
handle large size differences in
entities? To divide the world up
enough for the smaller entities the
larger ones will need to occupy a
large number of regions and I'm
concerned about how that will affect
the performance of the system.
Use a quad tree. For objects that exist in multiple areas you have a few options:
Store the object in both branches, all the way down. Everything ends up in leaf nodes but you may end up with a significant number of extra pointers. May be appropriate for static things.
Split the object on the zone border and insert each part in their respective locations. Creates a lot of pain and isn't well defined for a lot of objects.
Store the object at the lowest point in the tree you can. Sets of objects now exist in leaf and non-leaf nodes, but each object has one pointer to it in the tree. Probably best for objects that are going to move.
By the way, the reason you're using a quad tree is because it's really really easy to work with. You don't have any heuristic based creation like you might with some BSP implementations. It's simple and it gets the job done.
My other major concern is how to
properly keep the list of occupied
areas up to date. Since there's a lot
of moving entities, and some very
large ones, it seems like dividing the
world up will create a significant
amount of overhead for keeping track
of which entities occupy which
regions.
There will be overhead to keeping your entities in the correct spots in the tree every time they move, yes, and it can be significant. But the whole point is that you're doing much much less work in your collision code. Even though you're adding some overhead with the tree traversal and update it should be much smaller than the overhead you just removed by using the tree at all.
Obviously depending on the number of objects, size of game world, etc etc the trade off might not be worth it. Usually it turns out to be a win, but it's hard to know without doing it.
There are lots of approaches. I'd recommend settings some specific goals (e.g., x collision tests per second with a ratio of y between smallest to largest entities), and do some prototyping to find the simplest approach that achieves those goals. You might be surprised how little work you have to do to get what you need. (Or it might be a ton of work, depending on your particulars.)
Many acceleration structures (e.g., a good BSP) can take a while to set up and thus are generally inappropriate for rapid animation.
There's a lot of literature out there on this topic, so spend some time searching and researching to come up with a list candidate approaches. Mock them up and profile.
I'd be tempted just to overlay a coarse grid over the play area to form a 2D hash. If the grid is at least the size of the largest entity then you only ever have 9 grid squares to check for collisions and it's a lot simpler than managing quad-trees or arbitrary BSP trees. The overhead of determining which coarse grid square you're in is typically just 2 arithmetic operations and when a change is detected the grid just has to remove one reference/ID/pointer from one square's list and add the same to another square.
Further gains can be had from keeping the projectiles out of the grid/tree/etc lookup system - since you can quickly determine where the projectile would be in the grid, you know which grid squares to query for potential collidees. If you check collisions against the environment for each projectile in turn, there's no need for the other entities to then check for collisions against the projectiles in reverse.