I’m trying to create a basic chess board in C++ and output it.
I set up a multidimensional board array of characters as an initial test, and put characters in to represent each piece. This output odd results, so I stripped down the code to the following, which is intended to create a board with two rows of pawns and a rook in each corner, labelled a, b, c and d.
#include <string>
using namespace std;
class Game
{
public:
int turn;
char player;
char board[7][7];
Game()
{
turn = 1;
player = 'w';
int x,y;
for(y=0;y<=7;y++) for(x=0;x<=7;x++) board[x][y] = '.';
board[0][0] = 'a';
board[7][0] = 'b';
board[0][7] = 'c';
board[7][7] = 'd';
for(x=0;x<=7;x++) board[x][1] = 'p';
for(x=0;x<=7;x++) board[x][6] = 'p';
}
string getBoard()
{
string result = "";
int x,y;
for(y=0;y<=7;y++)
{
for(x=0;x<=7;x++) result += board[x][y];
result += "\n";
}
return result;
}
};
I’m using the following to test:
Game game;
cout << game.getBoard();
and am getting the following result:
ac.....b
pppppppp
........
........
........
........
pppppppp
c.....bd
Any ideas why the rooks are duplicated and not just appearing in the corners? I can not seem to track down the issue.
Since a chess board has 8×8 size change your board declaration to:
Your current array is of size 7×7,
Since C++ arrays are 0-based 7 is not a valid index for both the dimensions. So you can’t do:
or