Please answer this with \"C++\"!!!!!!!!!!! No other languages. You will create a
ID: 3705773 • Letter: P
Question
Please answer this with "C++"!!!!!!!!!!! No other languages.
You will create a problem that takes in a board with chess pieces from file. For this exercise, the board will only contain pawns and rooks. The dimensions of the board will be some MxN dimensions where both M and N are greater than 1.
Given a board, you will mark all pawns that can be attacked by a rook. Recall, a rook can move horizontally or vertically through empty spaces until it reaches an end of the board or another piece.
You job is to read in the file, find all the pawns that can be attacked, and print an updated board to the screen.
Piece and Board Representations
Rooks: 'R'
Pawns: 'P'
Empty spaces: '*'
When you find a pawn that can be attacked, change it from a 'P' to a '!'
Sample file
The files will contain the dimensions on the first line of the file then contain a board with a mix of empty spaces, pawns, and rooks.
Command-line argument:
Contents of sample.txt input file:
Output to terminal:
Notes:
The pawn at position (3,0) cannot be attacked because there is no rook in its row or column
The pawn at position (3,4) cannot be attacked because there is a piece between it and the rook in its column
Explanation / Answer
Executable Code:
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
void displayBoard(char **board, int row, int col)
{
for(int r = 0; r < row; r++)
{
for(int c = 0; c < col; c++)
cout<<board[r][c];
cout<<endl;
}
}
void rowAttack(char **board, int row, int col)
{
int foundP, foundR;
int pCol;
for(int r = 0; r < row; r++)
{
foundP = 0; foundR = 0; pCol = 0;
for(int c = 0; c < col; c++)
{
if(board[r][c] == 'P')
{
foundP = 1;
pCol = c;
}
if(board[r][c] == 'R')
foundR = 1;
}
if(foundP == 1 && foundR == 1)
board[r][pCol] = '!';
}
}
void columnAttack(char **board, int row, int col)
{
int foundP, foundR;
int pRow;
for(int r = 0; r < col; r++)
{
foundP = 0; foundR = 0; pRow = 0;
for(int c = 0; c < row; c++)
{
if(board[c][r] == 'P')
{
foundP = 1;
pRow = c;
break;
}
if(board[c][r] == 'R')
foundR = 1;
}
if(foundP == 1 && foundR == 1)
board[pRow][r] = '!';
}
}
void checkAttach(char **board, int row, int col)
{
cout<<" After Row Attack ";
rowAttack(board, row, col);
columnAttack(board, row, col);
displayBoard(board, row, col);
}
void readFile(string fileName)
{
char **board;
int row, col;
ifstream rFile;
rFile.open(fileName.c_str());
if(!rFile.is_open())
{
cout<<" Error: Unable to open the file! "<<fileName;
return;
}
rFile>>row;
rFile>>col;
board = new char*[row];
for(int r = 0; r < row; ++r)
board[r] = new char[col];
for(int r = 0; r < row; r++)
{
for(int c = 0; c < col; c++)
rFile>>board[r][c];
}
cout<<" Original Board "<<endl;
displayBoard(board, row, col);
checkAttach(board, row, col);
// Close the file
rFile.close();
}
int main()
{
readFile("chessBoard.txt");
}