<p>What data structures would you use to represent a chessboard for a computer chess program?</p>

[{'answer_id': 39881, 'author': 'slm', 'author_id': 4262, 'author_profile': 'https://Stackoverflow.com/users/4262', 'pm_score': 3, 'selected': False, 'text': "<p>The simple approach is to use an 8x8 integer array. Use 0 for empty squares and assign values for the pieces:</p>\n\n<pre><code>1 white pawns\n2 white knights\n3 white bishops\n4 white rooks\n5 white queens\n6 white king\n\nBlack pieces use negative values\n-1 black pawn\n-2 black knight\netc\n\n8| -4 -2 -3 -5 -6 -3 -2 -4\n7| -1 -1 -1 -1 -1 -1 -1 -1\n6|  0  0  0  0  0  0  0  0\n5|  0  0  0  0  0  0  0  0\n4|  0  0  0  0  0  0  0  0\n3|  0  0  0  0  0  0  0  0\n2|  1  1  1  1  1  1  1  1 \n1|  4  2  3  5  6  3  2  4\n  -------------------------\n   1  2  3  4  5  6  7  8\n</code></pre>\n\n<p>Piece moves can be calculated by using the array indexes. For example the white pawns move by increasing the row index by 1, or by 2 if it's the pawn's first move. So the white pawn on [2][1] could move to [3][1] or [4][1].</p>\n\n<p>However this simple 8x8 array representation of has chessboard has several problems. Most notably when you're moving 'sliding' pieces like rooks, bishops and queens you need to constantly be checking the indexes to see if the piece has moved off the board. </p>\n\n<p>Most chessprograms today, especially those that run on a 64 bit CPU, use a bitmapped approach to represent a chessboard and generate moves. x88 is an alternate board model for machines without 64 bit CPUs.</p>\n"}, {'answer_id': 39883, 'author': 'Larsenal', 'author_id': 337, 'author_profile': 'https://Stackoverflow.com/users/337', 'pm_score': -1, 'selected': False, 'text': '<p>An array would probably be fine.  If you wanted more convenient means of "traversing" the board, you could easily build methods to abstract away the details of the data structure implementation.</p>\n'}, {'answer_id': 39885, 'author': 'Marcel', 'author_id': 2554, 'author_profile': 'https://Stackoverflow.com/users/2554', 'pm_score': 0, 'selected': False, 'text': '<pre><code>int[8][8]\n\n0=no piece\n1=king\n2=queen\n3=rook\n4=knight\n5=bishop\n6=pawn\n</code></pre>\n\n<p>use positive ints for white and negative ints for black</p>\n'}, {'answer_id': 39896, 'author': 'Niyaz', 'author_id': 184, 'author_profile': 'https://Stackoverflow.com/users/184', 'pm_score': 4, 'selected': False, 'text': '<p>Initially, use an <strong>8 * 8 integer array</strong> to represent the chess board.</p>\n\n<p>You can start programing using this notation. Give point values for the pieces. For example:</p>\n\n<pre><code>**White**\n9 = white queen\n5 = white rook\n3 = bishop\n3 = knight\n1 = pawn\n\n**black**\n-9 = white queen\n-5 = white rook\n-3 = bishop\n-3 = knight\n-1 = pawn\n\nWhite King: very large positive number\nBlack King: very large negative number\n</code></pre>\n\n<p>etc. (Note that the points given above are approximations of trading power of each chess piece)</p>\n\n<p>After you develop the basic backbones of your application and clearly understand the working of the algorithms used, try to improve the performance by using bit boards.</p>\n\n<p>In bit boards, you use eight 8 -bit words to represent the boards. This representation needs a board for each chess piece. In one bit board you will be storing the position of the rook while in another you will be storing the position of the knight... etc</p>\n\n<p>Bit boards can improve the performance of your application very much because manipulating the pieces with bit boards are very easy and fast.</p>\n\n<p>As you pointed out,</p>\n\n<blockquote>\n  <p>Most chessprograms today, especially\n  those that run on a 64 bit CPU, use a\n  bitmapped approach to represent a\n  chessboard and generate moves. x88 is\n  an alternate board model for machines\n  without 64 bit CPUs.</p>\n</blockquote>\n'}, {'answer_id': 39899, 'author': 'Binarytales', 'author_id': 319, 'author_profile': 'https://Stackoverflow.com/users/319', 'pm_score': 1, 'selected': False, 'text': '<p>I would use a multidimensional array so that each element in an array is a grid reference to a square on the board.</p>\n\n<p>Thus</p>\n\n<pre><code>board = arrary(A = array (1,2,3,4,5,5,6,7,8),\n               B = array (12,3,.... etc...\n               etc...          \n               )\n</code></pre>\n\n<p>Then <em>board[A][1]</em> is then the board square A1.</p>\n\n<p>In reality you would use numbers not letters to help keep your maths logic for where pieces are allowed to move to simple.</p>\n'}, {'answer_id': 39926, 'author': 'Ed Guiness', 'author_id': 4200, 'author_profile': 'https://Stackoverflow.com/users/4200', 'pm_score': 2, 'selected': False, 'text': '<p>There are of course a number of different ways to represent a chessboard, and the best way will depend on what is most important to you.</p>\n\n<p>Your two main choices are between speed and code clarity.</p>\n\n<p>If speed is your priority then you must use a 64 bit data type for each set of pieces on the board (e.g. white pawns, black queens, en passant pawns).  You can then take advantage of native bitwise operations when generating moves and testing move legality.</p>\n\n<p>If clarity of code is priority then forget bit shuffling and go for nicely abstracted data types like others have already suggested.  Just remember that if you go this way you will probably hit a performance ceiling sooner.</p>\n\n<p>To start you off, look at the code for <a href="http://en.wikipedia.org/wiki/Crafty" rel="nofollow noreferrer">Crafty</a> (C) and <a href="http://sharpchess.com/" rel="nofollow noreferrer">SharpChess</a> (C#).</p>\n'}, {'answer_id': 39964, 'author': 'Esa', 'author_id': 4224, 'author_profile': 'https://Stackoverflow.com/users/4224', 'pm_score': 2, 'selected': False, 'text': "<p>Well, not sure if this helps, but Deep Blue used a single 6-bit number to represent a specific position on the board. This helped it save footprint on-chip in comparison to it's competitor, which used a 64-bit bitboard. </p>\n\n<p>This might not be relevant, since chances are, you might have 64 bit registers on your target hardware, already. </p>\n"}, {'answer_id': 524497, 'author': 'Nixuz', 'author_id': 61793, 'author_profile': 'https://Stackoverflow.com/users/61793', 'pm_score': 2, 'selected': False, 'text': '<p>Using a bitboard would be an efficient way to represent the state of a chess board. The basic idea is that you use 64bit bitsets to represent each of the squares on the board, where first bit usually represents A1 (the lower left square), and the 64th bit represents H8 (the diagonally opposite square). Each type of piece (pawn, king, etc.) of each player (black, white) gets its own bit board and all 12 of these boards makes up the game state. For more information check out this Wikipedia <a href="http://en.wikipedia.org/wiki/Bitboard" rel="nofollow noreferrer">article</a>. </p>\n'}, {'answer_id': 524505, 'author': 'Henry B', 'author_id': 6414, 'author_profile': 'https://Stackoverflow.com/users/6414', 'pm_score': 0, 'selected': False, 'text': "<p>I actually wouldn't model the chess board, I'd just model the position of the pieces.\nYou can have bounds for the chess board then.</p>\n\n<pre><code>Piece.x= x position of piece\nPiece.y= y position of piece\n</code></pre>\n"}, {'answer_id': 749948, 'author': 'Adam Berent', 'author_id': 90793, 'author_profile': 'https://Stackoverflow.com/users/90793', 'pm_score': 2, 'selected': False, 'text': '<p>When creating my chess engine I originally went with the [8][8] approach, however recently I changed my code to represent the chess board using a 64 item array.  I found that this implementation was about 1/3 more efficient, at least in my case.  </p>\n\n<p>One of the things you want to consider when doing the [8][8] approach is describing positions.  For example if you wish to describe a valid move for a chess piece, you will need 2 bytes to do so.  While with the [64] item array you can do it with one byte.  </p>\n\n<p>To convert from a position on the [64] item board to a [8][8] board you can simply use the following calculations:</p>\n\n<p>Row= (byte)(index / 8)</p>\n\n<p>Col = (byte)(index % 8)</p>\n\n<p>Although I found that you never have to do that during the recursive move searching which is performance sensitive.</p>\n\n<p>For more information on building a chess engine, feel free to visit my blog that describes the process from scratch: <a href="http://www.chessbin.com" rel="nofollow noreferrer">www.chessbin.com</a></p>\n\n<p>Adam Berent</p>\n'}, {'answer_id': 1185812, 'author': 'David Plumpton', 'author_id': 16709, 'author_profile': 'https://Stackoverflow.com/users/16709', 'pm_score': 3, 'selected': False, 'text': "<p>Array of 120 bytes.</p>\n\n<p>This is a chessboard of 8x8 surrounded by sentinel squares (e.g. a 255 to indicate that a piece can't move to this square). The sentinels have a depth of two so that a knight can't jump over.</p>\n\n<p>To move right add 1. To move left add -1. Up 10, down -10, up and right diagonal 11 etc. Square A1 is index 21. H1 is index 29. H8 is index 99.</p>\n\n<p>All designed for simplicity. But it's never going to be as fast as bitboards.</p>\n"}, {'answer_id': 18475233, 'author': 'bytefire', 'author_id': 1719372, 'author_profile': 'https://Stackoverflow.com/users/1719372', 'pm_score': 4, 'selected': False, 'text': '<p>For a serious chess engine, using bitboards is an efficient way to represent a chess board in memory. Bitboards are faster than any array based representation, specially in 64-bit architectures where a bitboard can fit inside a single CPU register.</p>\n\n<p><strong>Bitboards</strong></p>\n\n<p>Basic idea of bitboards is to represent every chess piece type in 64 bits. In C++/C# it will be <code>ulong/UInt64</code>. So you\'ll maintain 12 <code>UInt64</code> variables to represent your chess board: two (one black and one white) for each piece type, namely, pawn, rook, knight, bishop, queen and king. Every bit in a <code>UInt64</code> will correspond to a square on chessboard. Typically, the least significant bit will be a1 square, the next b1, then c1 and so on in a row-major fashion. The bit corresponding to a piece\'s location on chess board will be set to 1, all others will be set to 0. For example, if you have two white rooks on a2 and h1 then the white rooks bitboard will look like this: </p>\n\n<pre><code>0000000000000000000000000000000000000000000000000000000110000000\n</code></pre>\n\n<p>Now for example, if you wanted to move your rook from a2 to g2 in the above example, all you need to do is XOR you bitboard with:</p>\n\n<pre><code>0000000000000000000000000000000000000000000000000100000100000000\n</code></pre>\n\n<p>Bitboards have a performance advantage when it comes to move generation. There are other performance advantages too that spring naturally from bitboards representation. For example you could use <a href="http://www.cis.uab.edu/hyatt/hashing.html" rel="noreferrer">lockless hash tables</a> which are an immense advantage when parallelising your search algorithm.</p>\n\n<p><strong>Further Reading</strong></p>\n\n<p>The ultimate resource for chess engine development is the <a href="http://chessprogramming.wikispaces.com/Bitboards" rel="noreferrer">Chess Programming Wiki</a>. I\'ve recently written <a href="https://github.com/bytefire/Shutranj/blob/master/Shutranj.Engine/Board.cs" rel="noreferrer">this chess engine</a> which implements bitboards in C#. An even better open source chess engine is <a href="https://github.com/mcostalba/Stockfish/tree/master/src" rel="noreferrer">StockFish</a> which also implements bitboards but in C++.</p>\n'}, {'answer_id': 20709640, 'author': 'Wayne', 'author_id': 592746, 'author_profile': 'https://Stackoverflow.com/users/592746', 'pm_score': 2, 'selected': False, 'text': '<p>An alternative to the standard <a href="http://chessprogramming.wikispaces.com/8x8+Board" rel="nofollow">8x8 board</a> is the <a href="http://chessprogramming.wikispaces.com/10x12+Board" rel="nofollow">10x12</a> mailbox (so-called because, uh, I guess it looks like a mailbox). This is a one-dimensional array that includes <a href="http://en.wikipedia.org/wiki/Sentinel_value" rel="nofollow">sentinels</a> around its "borders" to assist with move generation. It looks like this:</p>\n\n<pre><code>-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n-1, "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8", -1,\n-1, "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7", -1,\n-1, "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6", -1,\n-1, "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5", -1,\n-1, "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4", -1,\n-1, "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", -1,\n-1, "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", -1,\n-1, "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", -1,\n-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n-1, -1, -1, -1, -1, -1, -1, -1, -1, -1\n</code></pre>\n\n<p>You can generate that array like this (in JavaScript):</p>\n\n<pre class="lang-js prettyprint-override"><code>function generateEmptyBoard() {\n    var row = [];\n    for(var i = 0; i &lt; 120; i++) {\n        row.push((i &lt; 20 || i &gt; 100 || !(i % 10) || i % 10 == 9) \n            ? -1 \n            : i2an(i));\n    }\n    return row;\n}\n\n// converts an index in the mailbox into its corresponding value in algebraic notation\nfunction i2an(i) {\n    return "abcdefgh"[(i % 10) - 1] + (10 - Math.floor(i / 10));\n}\n</code></pre>\n\n<p>Of course, in a real implementation you\'d put actual piece objects where the board labels are. But you\'d keep the negative ones (or something equivalent). Those locations make move generation a lot less painful because you can easily tell when you\'ve run off the board by checking for that special value.</p>\n\n<p>Let\'s first look at generating the legal moves for the knight (a non-sliding piece):</p>\n\n<pre class="lang-js prettyprint-override"><code>function knightMoves(square, board) {\n    var i = an2i(square);\n    var moves = [];\n    [8, 12, 19, 21].forEach(function(offset) {\n        [i + offset, i - offset].forEach(function(pos) {\n            // make sure we\'re on the board\n            if (board[pos] != -1) {\n                // in a real implementation you\'d also check whether \n                // the squares you encounter are occupied\n                moves.push(board[pos]);\n            }\n        });\n    });\n    return moves;\n}\n\n// converts a position in algebraic notation into its location in the mailbox\nfunction an2i(square) {\n    return "abcdefgh".indexOf(square[0]) + 1 + (10 - square[1]) * 10;\n}\n</code></pre>\n\n<p>We know that the valid Knight moves are a fixed distance from the piece\'s starting point, so we only needed to check that those locations are valid (i.e. not sentinel squares).</p>\n\n<p>The sliding pieces aren\'t much harder. Let\'s look at the bishop:</p>\n\n<pre class="lang-js prettyprint-override"><code>function bishopMoves(square, board) {\n    var oSlide = function(direction) {\n        return slide(square, direction, board);\n    }\n    return [].concat(oSlide(11), oSlide(-11), oSlide(9), oSlide(-9)); \n}\n\nfunction slide(square, direction, board) {\n    var moves = [];\n    for(var pos = direction + an2i(square); board[pos] != -1; pos += direction) {\n        // in a real implementation you\'d also check whether \n        // the squares you encounter are occupied\n        moves.push(board[pos]);\n    }\n    return moves;\n}\n</code></pre>\n\n<p>Here are some examples:</p>\n\n<pre class="lang-js prettyprint-override"><code>knightMoves("h1", generateEmptyBoard()) =&gt; ["f2", "g3"]\nbishopMoves("a4", generateEmptyBoard()) =&gt; ["b3", "c2", "d1", "b5", "c6", "d7", "e8"]\n</code></pre>\n\n<p>Note that the <code>slide</code> function is a general implementation. You should be able to model the legal moves of the other sliding pieces fairly easily.</p>\n'}, {'answer_id': 21966534, 'author': 'rpd', 'author_id': 247135, 'author_profile': 'https://Stackoverflow.com/users/247135', 'pm_score': 0, 'selected': False, 'text': '<p>I know this is a very old post which I have stumbled across a few times when googling chess programming, yet I feel I must mention it is perfectly feasible to model a chessboard with a 1D array e.g. chessboard[64]; </p>\n\n<p>I would say this is the simplest approach to chessboard representation...but of course it is a basic approach. </p>\n\n<p>Is a 1D chessboard array structure more efficient than a 2D array (which needs a nested for loop to access and manipulate the indices)?</p>\n\n<p>It is also possible to use a 1D array with more than 64 squares to represent OffBoard squares also e.g. chessboard[120]; (with the array sentinel and board playing squares correctly initialised).</p>\n\n<p>Finally and again for completeness for this post I feel I must mention the 0x88 board array representation. This is quite a popular way to represent a chessboard which also accounts for offboard squares.</p>\n'}]
['https://Stackoverflow.com/questions/39874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4262/']