I'm developing tic-tac-toe game, and I need algorithm to check when game ends(and who win). In 3x3 game I would check each possible win-situation(there is 8 capabilities). But in 7x7(needed 4 signs in a row or collumn, or diagonal)is a lot of possible win patterns.
相关问题
- Finding k smallest elements in a min heap - worst-
- binary search tree path list
- High cost encryption but less cost decryption
- How to get a fixed number of evenly spaced points
- Space complexity of validation of a binary search
相关文章
- What are the problems associated to Best First Sea
- Coin change DP solution to keep track of coins
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Algorithm for maximizing coverage of rectangular a
- How to measure complexity of a string?
- Select unique/deduplication in SSE/AVX
- How to smooth the blocks of a 3D voxel world?
While a very basic approach is to look at runs in all the directions from every single cell, here are an approach then only ever checks a cell in a single "line" once. A "line" is a row, column, or diagonal that can possibly win, like in a Vegas slot machine :)
Important Edit: If the cell contains neither P1 or P2, reset counter to 0 (doh!). I omitted this trivial but required step. Otherwise "11-11" would be counted as a win.
The "lines" can be traversed given a starting point and row/column offset per iteration (e.g. start at (0,0) and advance (1,1) for longest diagonal from NW to SE). Diagonals with lengths less than 4 can avoid being checked entirely, of course.
Happy coding.
loop though all positions. For each position check the four fields down diagonal-down-right and right (always including the field itself). Put in apropriate checks to avoid blowing up you app when you are checking fields that don't exist.
If you are using a bitboard for each player, you can use bit shift operations to test a board for a win.
The bitboard would have following structure:
If the player occupies a position in the game board, then the associated bit would be
1
otherwise0
(notice that bits 7, 15, 23, ... are0
). To check if the player has a winning board you could use following function:With the help of a example I will try to explain: The following bitboard of one player includes beside vertical and diagonal wins a winning combination in the first row.
The steps for the horizontal check are:
y = board & (board >> 8)
y & (y >> 2 * 8)
The horizontal check results in a board with one bit set, this means the board includes a win and the function returns
true
.I have used a similar function to check a connect four game for a win. I saw this fascinating function in the sources to The Fhourstones Benchmark from John Tromp.
Simple. Make 4
for
loops, for all rows, columns, increasing diagonals, decreasing diagonals. In each, test if there are 4 consecutive pieces.