I'm making a chess game. I had it pretty much working, but when a player took a piece weird stuff happened. Anyway the way my object were set up sucked, so I have been trying to redesign it.
The 'board' object has an 8*8 array which either holds a null value or a pointer to a 'piece' object. When the board is constructed the grid is initialized:
Code:
void NewPiece(int x, int y, bool i)
{
cell[x][y] = new piece;
cell[x][y]->SetOwner(i);
if(y==0 || y==7)
if(x==0 || x==7) cell[x][y]->SetType('R', 'k');
else if(x==1 || x==6) cell[x][y]->SetType('K', 't');
else if(x==2 || x==5) cell[x][y]->SetType('B', 's');
else if(x==4) cell[x][y]->SetType('K', 5);
else if(x==3) cell[x][y]->SetType('Q', 6);
else
cell[x][y]->SetType('P', 'n');
}
board()
{
int x, y;
go=0; turn=1;
for(y=0; y<2; y++) pl[y] = new player;
for(y=0; y<8; y++) for(x=0; x<8; x++) cell[x][y]=NULL;
for(y=0; y<2; y++) for(x=0; x<8; x++) NewPiece(x, y, false);
for(y=6; y<8; y++) for(x=0; x<8; x++) NewPiece(x, y, true);
}
The chess board is then drawn when the program begins:
Code:
void board::DrawBoard()
{
for(int y=0; y<18; y++)
for(int x=0; x<26; x++)
if(y==0)
if(x==25) printf(" \n");
else if(x%3==2) putchar(65+(x/3));
else putchar(' ');
else if (y==1)
if(x==0) putchar(' ');
else if(x==1) putchar(218);
else if(x==25) printf("%c\n", 191);
else if(x%3==1) putchar(194);
else putchar(196);
else if(y==17)
if(x==0) putchar(' ');
else if(x==1) putchar(192);
else if(x==25) printf("%c\n", 217);
else if(x%3==1) putchar(193);
else putchar(196);
else if(y%2==1)
if(x==0) putchar(' ');
else if(x==1) putchar(195);
else if(x==25) printf("%c\n", 180);
else if(x%3==1) putchar(197);
else putchar(196);
else
if (x==0) putchar(48+(y/2));
else if(x==25) printf("%c\n", 179);
else if(x%3==1) putchar(179);
else if(x%3==2) DrawCell(x/3, (y/2)-1);
}
void board::DrawCell(int x, int y)
{
int i;
bool own;
if(cell[x][y]==NULL) //Empty Cell
{
if(x%2==0 && y%2==0 || x%2==1 && y%2==1) SetConsoleTextAttribute ( h, BACKGROUND_BLUE | 0 );
else SetConsoleTextAttribute ( h, BACKGROUND_GREEN | 0 );
printf(" ");
}
else //There is a piece in the Cell
{
own=GetOwner(x, y);
if(own == true)//Check owner colour
if(x%2==0 && y%2==0 || x%2==1 && y%2==1)//Check tile colour
SetConsoleTextAttribute ( h, BACKGROUND_BLUE | 8 );
else
SetConsoleTextAttribute ( h, BACKGROUND_GREEN | 8 );
else
if(x%2==0 && y%2==0 || x%2==1 && y%2==1)
SetConsoleTextAttribute ( h, BACKGROUND_BLUE | 0 );
else
SetConsoleTextAttribute ( h, BACKGROUND_GREEN | 0 );
putchar(cell[x][y]->GetType(0));
putchar(cell[x][y]->GetType(1));
}
SetConsoleTextAttribute ( h, 8 );
}
When the program runs I get a MAV when I try an access a piece through the pointer in the grid cell. (in bold)
Also here is the get owner function:
Code:
bool GetOwner(int x, int y) { return cell[x][y]->GetOwner(); }
Any suggestions on how I could fix this?
Cheers.