Question

Please develop the following code using C programming and using the specific functions, instructi...

Please develop the following code using C programming and using the specific functions, instructions and format given below. Again please use the functions given especially. Also don't copy any existing solution please write your own code.

This is the first part of a series of two labs (Lab 7 and Lab 8) that will complete an implementation for a board-type game called Reversi (also called Othello). The goal of this lab is to write code that sets up the input and checks the legality of moves in this game. These two labs make use of two-dimensional arrays, as well as all of the previous material covered before two-dimensional arrays in this course. They require some careful thinking about how to convert human-thinking into working software.

Objective: Part of the Code for a Reversi Game:

The goal of this lab is to write a program that will be used (in Lab 8) as part of a Reversi game, as well as a little bit of the ‘thinking’ code that will be used in that lab to have the computer play against a human opponent. Here is a brief description of the full Reversi game. Reversi is played on a board (like a chess board or a checkers board) that has dimensions n × n, where n is even. In the picture below n = 4. The game uses tiles that are white on one side, and black on the other side (they can be “flipped” over to change their colour). One player plays white; the other player plays black. The picture below shows the initial board configuration, which has two white and two black tiles placed in advance at the centre. Observe that rows and columns are labelled with letters.

A “turn” consists of a player laying a tile of his/her own colour on a candidate empty board position, subject to the following two rules: 1. There must be a continuous straight line of tile(s) of the opponent’s colour in at least one of the eight directions from the candidate empty position (North, South, East, West, and diagonals). 2. In the position immediately following the continuous straight line mentioned in #1 above, a tile of the player’s colour must already be placed. After playing a tile at a position that meets the above critera, all of the lines of the opponent’s tiles that meet the criteria above are flipped to the player’s colour. In the picture below, all of the candidate positions for White’s next move are shown shaded.

If the White player decides to play at row c, column a, the Black tile at row c, column b is flipped and the board looks like the image.

The picture below shows the possible move positions for the Black player. If the Black player lays a tile at (b, a), the board appears like this. Finally, if the White player lays a tile at (a, c) the board appears like this:

The teams alternate between the players, unless one player has no available move, in which case the only player with an available move is allowed to continue to make moves until a move becomes available for the opponent, at which point, the opponent is allowed to take a turn and the alternating turns between the players resumes. The game ends when either: 1) the entire board is full, or 2) neither player has an available move. For this lab, you will implement part of the game-playing functionality. You will complete the game in Lab 7, using the functionality you have built in this lab, so please be mindful to build clean and re-usable code for this lab!

For this lab, you will write a C program that will do the following: (Note that the specific details of input and output will be given in the example runs below this section) (1) The first input to the program will be n, giving the size of the n ⇥ n board. You may assume that the size of n will be even and will never be larger than 26, and should declare a static 2-dimensional array. Your program should initialize the board as shown above and print it. (2). The next sequence of inputs will describe a board configuration, representing a situation part-way through a game of Reversi. Each line of input will consist of three characters with no spaces in between. The first character will be a colour: B or W; the second character will be the row (a-z); the third character will be the column (a-z). The three characters represent a tile of the specified colour placed at the specified row and column. The three-character sequence !!! ends the board configuration entry phase. Character arithmetic can be used to translate the rows/columns into array indices, e.g. 'b' - 'a' equals 1. Note: your program should not check for move legality during this phase. This phase is simply to input an intermediate board configuration. (3). Then, your program should print a list of the available moves for the White player, followed by a list of the available moves for the Black player, given the board configuration input in the previous step. The available moves for each player should be printed in the order of increasing rows, then in the order of increasing columns (for available moves in the same row). (4). Next, your program should ask the user to input a move, represented in the same three-character format. Your program should check if the move is valid, and if so, make the move, flipping the tiles correspondingly. If the move is invalid, your program should indicate so. (5). Your program should print the final board configuration and terminate.

Your program must use the following characters to represent the state of each board position: U - for unoccupied; B - occupied by black; W - occupied by white.

For example, after the entire board above is entered, it would be printed as follows:
abcd
a UUWU
b BWWU
c WWWU
d UUUU
To print the board, your program should contain a function with the following prototype: void printBoard(char board [ ] [26], int n); where board is the 2D array representing the current board state, and n is the board dimensions.

Here is an example execution of the program:
Enter the board dimension: 4
abcd
a UUUU
b UWBU
c UBWU
d UUUU
Enter board configuration:
Bba
Wca
Bac
!!!
abcd
a UUBU
b BWBU
c WBWU
d UUUU
Available moves for W:
aa
bd
db
Available moves for B:
ab
cd
da
dc
Enter a move:
Wdb
Valid move.
abcd
a UUBU
b BWBU
c WWWU
d UWUU

Here is another example execution of the program where the final move is invalid:
Enter the board dimension: 6
abcdef
a UUUUUU
b UUUUUU
c UUWBUU
d UUBWUU
e UUUUUU
f UUUUUU
Enter board configuration:
Bbd
Bad
Wde
Wcb
!!!
abcdef
a UUUBUU
b UUUBUU
c UWWBUU
d UUBWWU
e UUUUUU
f UUUUUU
Available moves for W:
ae
bc
ce
db
ec
ed
Available moves for B:
ba
bc
ca
db
df
ed
ef
Enter a move:
Bbe
Invalid move.
abcdef
a UUUBUU
b UUUBUU
c UWWBUU
d UUBWWU
e UUUUUU
f UUUUUU
We strongly encourage you to break up your program into separate functions, and to carefully test each function separately, before connecting it into the larger program. To help with this, you are required to create the following helper functions and use them in your implementation: bool positionInBounds(int n, int row, int col); which checks whether the specified (row, col) lies within the board dimensions. It is very error prone to write separate code to check each of the eight possible line directions that begin at a given tile. To simplify this, you are required to write and use the following function: bool checkLegalInDirection(char board[ ][26], int n, int row, int col, char colour, int deltaRow, int deltaCol);which checks whether (row, col) is a legal position for a tile of colour by “looking” in the direction specified by deltaRow and deltaCol. deltaRow and deltaCol take on values of -1, 0, and 1, with the restriction that they cannot both be 0. For example, if deltaRow = 1 and deltaCol = 0, the function searches the South line. If deltaRow = -1 and deltaCol = 1, the function searches the Northeast line. The idea is that, elsewhere in your program, you will call the helper function 8 times to search the lines in the 8 possible directions.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>
#include <stdbool.h>

void printBoard (char board[][26], int n);
void initialBoardConfig (char board[][26], int n);
bool positionInBounds(int dimen, char row, char col);
bool checkUnoccupied (char board[][26], char row, char col);
bool checkLegalInDirection(char board[][26], int dimen, char row, char col,
char colour, int deltaRow, int deltaCol);
bool checkLegalMove (char board[][26], int dimen, char colour, char row, char col);
void printAvailableMoves(char board[][26], int dimen, char colour);
char opponentColour (char selfColour);
void flipTiles(char board[][26], int dimen, char row, char col, char colour);

int main(int argc, char **argv)
{
char board[26][26];
int dimen;

// three characters to specify moves and configuration
char colour;
char row;
char col;

printf("Enter the board dimension: ");
scanf("%d", &dimen);
initialBoardConfig(board, dimen);
printBoard(board, dimen);
printf ("Enter board configuration: \n");
while (colour != '!' && row != '!' && col != '!') {

scanf (" %c %c %c", &colour, &row, &col);

board[row-'a'][col-'a'] = colour;
}
printBoard(board, dimen);

printf ("Available moves for W: \n");
printAvailableMoves(board, dimen, 'W');
printf("Available moves for B: \n");
printAvailableMoves(board, dimen, 'B');

printf("Enter a move: ");
scanf(" %c%c%c", &colour, &row, &col);

// check if entered move is legal in any of the eight direction
if (checkLegalMove(board, dimen, colour, row, col)) {
// flip pieces
flipTiles(board, dimen, row, col, colour);
printf("Valid move. \n");
} else {
printf ("Invalid move. \n");
}

printBoard(board, dimen);

return 0;
}

/ prints out board configuration
first param board array
second param board dimension
/
void printBoard (char board[][26], int n) {

char alphabet = 'a';
printf(" ");
// prints first line
for (int i = 0; i < n; i ++) {
printf (" %c", alphabet);
alphabet = alphabet + 1;
}
printf("\n");

alphabet = 'a';
for (int i = 0; i < n; i ++) {
// prints first column
printf(" %c", alphabet);
// prints board
for (int j = 0; j < n; j ++) {
printf(" %c", board[i][j]);
}
alphabet = alphabet + 1;
printf("\n");
}

}

/ creates initial board configuration
first param board array
second param board dimension
/
void initialBoardConfig (char board[][26], int n) {

for (int i = 0; i < n; i ++) {
for (int j = 0; j < n; j ++) {
board[i][j] = 'U';
}
}

// setting initial positions
board[(n-1)/2][(n-1)/2] = 'W';
board[(n-1)/2 + 1][(n-1)/2 + 1] = 'W';
board[(n-1)/2][(n-1)/2 + 1] = 'B';
board[(n-1)/2 + 1][(n-1)/2] = 'B';

}

/ check whether the specified (row, col) is within board dimension
first param dimension of board
second param row character index
third param column character index
/
bool positionInBounds(int dimen, char row, char col) {

// true if both row and col are smaller than specified dimension
if (row -'a' >= dimen || col - 'a' >= dimen || row - 'a' < 0 || col - 'a' < 0) {
// printf("out of bound\n");
return false;
} else {
// printf("in bound\n");
return true;
}

}

/ check if position is unoccupied
first param board array
second param row character index
third param colum character index
/
bool checkUnoccupied (char board[][26], char row, char col) {

return board[row - 'a'][col - 'a'] == 'U';

}

/ checks if move is legal in specified direction
first param board array
second param dimension
third param row character index
fourth param column character index
fifth param change in row
sixth param change in column
/
bool checkLegalInDirection(char board[][26], int dimen, char row, char col,
char colour, int deltaRow, int deltaCol) {

// check occupancy of specified location
if (!checkUnoccupied(board, row, col)) {
return false;
}

// immediate adjacent location
row = row + deltaRow - 'a';
col = col + deltaCol - 'a';

// check if immediate adjacent position is in bound
if (!positionInBounds(dimen, row + 'a', col + 'a')) {
return false;
}

if (board[row][col] == opponentColour(colour)) {
// next position in direction
row = row + deltaRow;
col = col + deltaCol;

// if next position in direction is in bound and occupied and is black
while (positionInBounds(dimen, row + 'a', col + 'a') && board[row][col] != 'U') {
if (board[row][col] == colour) {
return true;
} else {
// continues checking next position
row = row + deltaRow;
col = col + deltaCol;
}
}

}

return false;

}

/ checks if move is valid
first param board array
second param dimension
third param player's colour
fourth param row's character index
fifth param column's character index
/
bool checkLegalMove (char board[][26], int dimen, char colour, char row, char col) {
if (checkLegalInDirection(board, dimen, row, col, colour, -1, -1)){
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, -1, 0)) {
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, -1, 1)) {
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, -1, 0)) {
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 0, -1)) {
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 0, 1)) {
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 1, -1)) {
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 1, 0)) {
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 1, 1)) {
return true;
} else {
return false;
}
}

/* finds opponent colour
* param is colour for player*/
char opponentColour (char selfColour) {
if (selfColour == 'B') {
return 'W';
} else {
return 'B';
}
}

/ prints available moves for a colour
first param: board array
second param: dimension
third param: colour for player
/
void printAvailableMoves(char board[][26], int dimen, char colour) {

for (char row = 'a'; row < 'a' + dimen; row ++) {
for (char col = 'a'; col < 'a' + dimen; col ++) {

// left up corner
if (checkLegalInDirection(board, dimen, row, col, colour, -1, -1)) {
printf("%c%c \n", row, col);
} else if (checkLegalInDirection(board, dimen, row, col, colour, -1, 0)) {
// up
printf("%c%c \n", row, col);
} else if (checkLegalInDirection(board, dimen, row, col, colour, -1, 1)) {
// right up
printf("%c%c \n", row, col);
} else if (checkLegalInDirection(board, dimen, row, col, colour, 0, -1)) {
// left
printf("%c%c \n", row, col);
} else if (checkLegalInDirection(board, dimen, row, col, colour, 0, 1)) {
// right
printf("%c%c \n", row, col);
} else if (checkLegalInDirection(board, dimen, row, col, colour, 1, -1)) {
// bottom left
printf("%c%c \n", row, col);
} else if (checkLegalInDirection(board, dimen, row, col, colour, 1, 0)) {
// bottom
printf("%c%c \n", row, col);
} else if (checkLegalInDirection(board, dimen, row, col, colour, 1, 1)) {
// bottom right
printf("%c%c \n", row, col);
}
}
}
} flip tiles according to position
first param: board array
second param: dimension
third param: row character
fourth param: col character
fifth param: player's colour
/
void flipTiles(char board[][26], int dimen, char row, char col, char colour) {

int deltaRow = 0;
int deltaCol = 0;
int currentRow = 0;
int currentCol = 0;
char opponent = opponentColour(colour);

// place player move
board[row-'a'][col-'a'] = colour;

for (deltaRow = -1; deltaRow <= 1; deltaRow ++) {
for (deltaCol = -1; deltaCol <= 1; deltaCol ++) {
if (!positionInBounds(dimen, row, col)) {
continue;
}

if (board[row + deltaRow - 'a'][col + deltaCol - 'a'] == opponent) {
// move to the opponent's position
currentRow = row + deltaRow - 'a';
currentCol = col + deltaCol - 'a';


while (true) {
currentRow += deltaRow;
currentCol += deltaCol;
if (!positionInBounds(dimen, currentRow + 'a', currentCol + 'a')) {
break;
}

if (checkUnoccupied(board, currentRow+'a', currentCol + 'a')) {
break;
}

/ if player colour is found, go backwards and flip /
if (board[currentRow][currentCol] == colour) {
while (board[currentRow-=deltaRow][currentCol-=deltaCol] == opponent) {
board[currentRow][currentCol] = colour; // flip tiles
}
break; // done flipping for the direction
}
}
}
}
}
}

Lab7Part1.c

#include <stdio.h>
#include <stdbool.h>

void printBoard (char board[][26], int n);
void initialBoardConfig (char board[][26], int n);
bool positionInBounds(int dimen, char row, char col);
bool isUnoccupied (char board[][26], char row, char col);
bool checkLegalInDirection(char board[][26], int dimen, char row, char col,
char colour, int deltaRow, int deltaCol);
bool isValidMove (char board[][26], int dimen, char colour, char row, char col);
char opponentColour (char selfColour);
void flipTiles(char board[][26], int dimen, char row, char col, char colour);
bool hasAvailableMoves (char board[][26], int dimen, char colour);
void copyBoard (char board[][26], int dimen, char boardCopy[][26]);
int countBeforeFlip (char board[][26], int dimen, char colour);
int countAfterFlip (char boardCopy[][26], int dimen, char row, char col, char colour);
int calculatePositionScore(char board[][26], int dimen, char row, char col, char colour);
void bestMove (char board[][26], int dimen, char selectedRow, char selectedCol, char colour);
int countPieces (char board[][26], int dimension, char colour);
char winner (char board[][26], int dimension, char black, char white);

int main(int argc, char **argv)
{
bool gameOver = false; // if game is over
char turn = 'B'; // first player

// row and column indices
char humanRow, humanCol;
char selectedRow, selectedCol;

int dimen;
char board[26][26];
char computerColour, humanColour;

printf("Enter the board dimension: ");
scanf("%d", &dimen);
initialBoardConfig(board, dimen);

printf("Computer plays (B/W) : ");
scanf (" %c", &computerColour);

humanColour = opponentColour(computerColour);
printBoard(board, dimen);

while (!gameOver) {
if (computerColour == turn) {
// finds best move for computer
bestMove(board, dimen, &selectedRow, &selectedCol, computerColour);
// makes move and flip tiles
flipTiles(board, dimen, selectedRow, selectedCol, computerColour);
printf("Computer places %c at %c%c.\n", computerColour, selectedRow, selectedCol);
printBoard(board, dimen);
} else {
// human makes move
printf("Enter move for colour %c (RowCol): ", turn);
scanf(" %c%c", &humanRow, &humanCol);
// checks if legal, if not gameOver = true
if (!isValidMove(board, dimen, humanColour, humanRow, humanCol)) {
printf("Invalid move.\n");
printf("%c player wins.\n", opponentColour(humanColour));
gameOver = true;
} else {
flipTiles (board, dimen, humanRow, humanCol, humanColour);
printBoard(board, dimen);
}
}


if (!gameOver) {
if (hasAvailableMoves(board, dimen, opponentColour(turn))) {
// if opponent has available move for the next round
turn = opponentColour(turn);
} else if (hasAvailableMoves(board, dimen, turn)) {
// if opponent doesn't have available move
// turn is still the current player's
// printBoard(board, dimen);
printf("%c player has no valid move.\n", opponentColour(turn));
turn = turn;
} else {
// neither has available move
gameOver = true;
if (winner(board, dimen, computerColour, humanColour) == 'D') {
printf("Draw!\n");
} else {
printf("%c player wins.\n", winner(board, dimen, computerColour, humanColour));
}

}
}
}


return 0;
}

/ prints out board configuration
first param board array
second param board dimension
/

void printBoard (char board[][26], int n) {

char colLabel = 'a';
printf(" ");
// prints column label
for (int i = 0; i < n; i ++) {
printf ("%c", colLabel);
colLabel = colLabel + 1;
}
printf("\n");

char rowLabel = 'a';
for (int i = 0; i < n; i ++) {
// prints row labels
printf("%c ", rowLabel);
// prints board
for (int j = 0; j < n; j ++) {
printf("%c", board[i][j]);
}
rowLabel = rowLabel + 1;
printf("\n");
}

}

/ creates initial board configuration
first param board array
second param board dimension
/
void initialBoardConfig (char board[][26], int n) {

for (int i = 0; i < n; i ++) {
for (int j = 0; j < n; j ++) {
board[i][j] = 'U';
}
}

// setting initial positions
board[(n-1)/2][(n-1)/2] = 'W';
board[(n-1)/2 + 1][(n-1)/2 + 1] = 'W';
board[(n-1)/2][(n-1)/2 + 1] = 'B';
board[(n-1)/2 + 1][(n-1)/2] = 'B';

}

/ check whether the specified (row, col) is within board dimension
first param dimension of board
second param row character index
third param column character index
/
bool positionInBounds(int dimen, char row, char col) {

// true if both row and col are smaller than specified dimension
if (row -'a' >= dimen || col - 'a' >= dimen || row - 'a' < 0 || col - 'a' < 0) {
// printf("out of bound\n");
return false;
} else {
// printf("in bound\n");
return true;
}

}

/ check if position is unoccupied
first param board array
second param row character index
third param colum character index
/
bool isUnoccupied (char board[][26], char row, char col) {

return board[row - 'a'][col - 'a'] == 'U';

}

/ checks if move is legal in specified direction
first param board array
second param dimension
third param row character index
fourth param column character index
fifth param change in row
sixth param change in column
/
bool checkLegalInDirection(char board[][26], int dimen, char row, char col,
char colour, int deltaRow, int deltaCol) {

// check occupancy of specified location
if (!isUnoccupied(board, row, col)) {
return false;
}

// immediate adjacent location
row = row + deltaRow - 'a';
col = col + deltaCol - 'a';

// check if immediate adjacent position is in bound
if (!positionInBounds(dimen, row + 'a', col + 'a')) {
return false;
}

if (board[row][col] == opponentColour(colour)) {
// next position in direction
row = row + deltaRow;
col = col + deltaCol;

// if next position in direction is in bound and occupied
while (positionInBounds(dimen, row + 'a', col + 'a') && board[row][col] != 'U') {
// if found self colour
if (board[row][col] == colour) {
return true;
} else {
// continues checking next position
row = row + deltaRow;
col = col + deltaCol;
}
}

}

return false;

}

/ checks if move is valid
first param board array
second param dimension
third param player's colour
fourth param row's character index
fifth param column's character index
/

bool isValidMove (char board[][26], int dimen, char colour, char row, char col) {
// checks if legal in one of the eight directions
if (checkLegalInDirection(board, dimen, row, col, colour, -1, -1)){
// upper left
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, -1, 0)) {
// upper
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, -1, 1)) {
// upper right
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 0, -1)) {
// left
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 0, 1)) {
// right
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 1, -1)) {
// lower left
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 1, 0)) {
// lower
return true;
} else if (checkLegalInDirection(board, dimen, row, col, colour, 1, 1)) {
// lower right
return true;
} else {
return false;
}
}

/* finds opponent colour
* param is colour for player*/
char opponentColour (char selfColour) {
// opponent is black if self is white
if (selfColour == 'B') {
return 'W';
} else {
return 'B';
}
}

/ flip tiles according to position
first param: board array
second param: dimension
third param: row character
fourth param: col character
fifth param: player's colour
returns num of tiles flipped
/
void flipTiles(char board[][26], int dimen, char row, char col, char colour) {

int deltaRow = 0;
int deltaCol = 0;
int currentRow = 0;
int currentCol = 0;
char opponent = opponentColour(colour);

// place player move
board[row-'a'][col-'a'] = colour;

for (deltaRow = -1; deltaRow <= 1; deltaRow ++) {
for (deltaCol = -1; deltaCol <= 1; deltaCol ++) {
if (!positionInBounds(dimen, row, col)) {
continue;
}

if (board[row + deltaRow - 'a'][col + deltaCol - 'a'] == opponent) {
// move to the opponent's position
currentRow = row + deltaRow - 'a';
currentCol = col + deltaCol - 'a';


while (true) {
currentRow += deltaRow;
currentCol += deltaCol;
if (!positionInBounds(dimen, currentRow + 'a', currentCol + 'a')) {
break;
}

if (isUnoccupied(board, currentRow+'a', currentCol + 'a')) {
break;
}

/ if player colour is found, go backwards and flip /
if (board[currentRow][currentCol] == colour) {
while (board[currentRow-=deltaRow][currentCol-=deltaCol] == opponent) {
board[currentRow][currentCol] = colour; // flip tiles
}
break; // done flipping for the direction
}
}
}
}
}
}

/ checks if player has moves available
if yes return true
* else return false
/
bool hasAvailableMoves (char board[][26], int dimen, char colour) {

// loops through board
for (char row = 'a'; row < 'a' + dimen; row ++) {
for (char col = 'a'; col < 'a' + dimen; col ++) {
if (isValidMove(board, dimen, colour, row, col)) {
// found valid move
return true;
}
}
}
return false;
}

/ copies board
first param is the current board configuration
second param: board dimension
third param: copied board
/
void copyBoard (char board[][26], int dimen, char boardCopy[][26]) {

for (int i = 0; i < dimen; i ++) {
for (int j = 0; j < dimen; j ++) {
boardCopy[i][j] = board[i][j];
}
}

}


/* counts number of colour on board before flipping
* first param: board array
* second param: board dimension
* third param: colour to be counted
* returns number of colour
/
int countBeforeFlip(char board[][26], int dimen, char colour) {

int count = 0;
for (int i = 0; i < dimen; i ++) {
for (int j = 0; j < dimen; j ++) {
if (board[i][j] == colour) {
count ++;
}
}
}

return count;
}

/* counts number of colour on board after flipping
* initialize a board copy array outside function before using function
* first param: board copy array
* second param: board dimension
* third and fourth param: row and col to be flipped
* fifth param: colour to be counted
* returns number of colour
/
int countAfterFlip(char board[][26], int dimen, char row, char col, char colour) {

flipTiles (board, dimen, row, col, colour);
int count = 0;
for (int i = 0; i < dimen; i ++) {
for (int j = 0; j < dimen; j ++) {
if (board[i][j] == colour) {
count ++;
}
}
}

return count;
}

/ calculates score for position
first param is board array
second param is dimension
third and fourth param is row column character indices
fifth param is the computer's colour
/
int calculatePositionScore(char board[][26], int dimen, char row, char col, char colour) {
char boardCopy[26][26];
int score = 0;
copyBoard(board, dimen, boardCopy);
score = countAfterFlip(boardCopy, dimen, row, col, colour) - countBeforeFlip(board, dimen, colour) - 1;
return score;
}

/ finds best move for computer
first param is board array
second param is dimension
third and fourth param is the pointer to computer's selected row and column
fifth param is computer's colour
/
void bestMove (char board[][26], int dimen, char selectedRow, char selectedCol, char colour) {
int score = 0;
for (int row = dimen - 1; row >= 0; row --) {
for (int col = dimen - 1; col >= 0; col --) {
// if not a valid move, skip
if (!isValidMove(board, dimen, colour, 'a'+row, 'a'+col)){
continue;
}
if (calculatePositionScore(board, dimen, 'a'+row, 'a'+col, colour) >= score) {
*selectedRow = 'a'+row;
*selectedCol = 'a' + col;
score = calculatePositionScore(board, dimen, 'a'+row, 'a'+col, colour);
}
}
}
}

/ counts pieces for colour
first param is board
second param is dimension
third param is colour to be counted
returns num of pieces
/
int countPieces (char board[][26], int dimen, char colour) {
int numPieces = 0;
for (int i = 0; i < dimen; i ++) {
for (int j = 0; j < dimen; j ++) {
if (board[i][j] == colour)
numPieces ++;
}
}
return numPieces;
}

/ figures out winner
first param is board
second param is dimension
third and fourth param is black and white characters
/
char winner (char board[][26], int dimension, char black, char white) {
if (countPieces(board, dimension, black) > countPieces(board, dimension, white)) {
// black wins
return black;
} else if (countPieces(board, dimension, black) < countPieces(board, dimension, white)) {
// white wins
return white;
} else {
// draw
return 'D';
}
}

Add a comment
Know the answer?
Add Answer to:
Please develop the following code using C programming and using the specific functions, instructi...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This is my code for my game called Reversi, I need to you to make the...

    This is my code for my game called Reversi, I need to you to make the Tester program that will run and complete the game. Below is my code, please add comments and Javadoc. Thank you. public class Cell { // Displays 'B' for the black disk player. public static final char BLACK = 'B'; // Displays 'W' for the white disk player. public static final char WHITE = 'W'; // Displays '*' for the possible moves available. public static...

  • JAVA Only Help on the sections that say Student provide code. The student Provide code has...

    JAVA Only Help on the sections that say Student provide code. The student Provide code has comments that i put to state what i need help with. import java.util.Scanner; public class TicTacToe {     private final int BOARDSIZE = 3; // size of the board     private enum Status { WIN, DRAW, CONTINUE }; // game states     private char[][] board; // board representation     private boolean firstPlayer; // whether it's player 1's move     private boolean gameOver; // whether...

  • Must be done in Java. PROBLEM 2 INFORMATION AND THE CODE PROVIDED WITH IT AS WELL....

    Must be done in Java. PROBLEM 2 INFORMATION AND THE CODE PROVIDED WITH IT AS WELL. PROBLEM 1 INFORMATION IF YOU NEED IT AS WELL: Provide the rest of the code with full comments and explanation and with proper indentation. Use simple methods for better understanding. Must compile. At the end, show the exact Output that's shown in Problem3. CODE PROVIDED FOR PROBLEM 2: import java.util.Scanner; public class Problem2 { public static void main( String [] args ) { //N...

  • Must be done in Java. PROBLEM 1 INFORMATION AND THE CODE PROVIDED WITH IT AS WELL....

    Must be done in Java. PROBLEM 1 INFORMATION AND THE CODE PROVIDED WITH IT AS WELL. Provide the rest of the code with full comments and explanation and with proper indentation. Use simple methods for better understanding. Must compile. At the end show the exact Output that's shown in the Problem 2. CODE PROVIDED FOR PROBLEM 1: import java.util.Scanner; public class Problem1 {    public static void main( String [] args )    {        //N denoting the size of the board        int...

  • Must be done in Java. PROBLEM 1 INFORMATION AND THE CODE PROVIDED WITH IT AS WELL....

    Must be done in Java. PROBLEM 1 INFORMATION AND THE CODE PROVIDED WITH IT AS WELL. Provide the rest of the code with full comments and explanation and with proper indentation. Use simple methods for better understanding. Must compile. At the end, show the exact Output that's shown in Problem 2. CODE PROVIDED FOR PROBLEM 1: import java.util.Scanner; public class Problem1 {    public static void main( String [] args )    {        //N denoting the size of the board        int n;       ...

  • JAVA TIC TAC TOE - please help me correct my code Write a program that will...

    JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below |    1       |   2        |   3 |    4       |   5        |   6                 |    7      |   8        |   9 The program will assign X to Player 1, and O to Player    The program will ask Player 1, to...

  • Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game....

    Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game. The objective of this project is to demonstrate your understanding of various programming concepts including Object Oriented Programming (OOP) and design. Tic Tac Toe is a two player game. In your implementation one opponent will be a human player and the other a computer player. ? The game is played on a 3 x 3 game board. ? The first player is known as...

  • I need to complete the code by implementing the min function and the alpha betta pruning...

    I need to complete the code by implementing the min function and the alpha betta pruning in order to complete the tic tac toe game using pything. code: # -*- coding: utf-8 -*- """ Created on: @author: """ import random from collections import namedtuple GameState = namedtuple('GameState', 'to_move, utility, board, moves') infinity = float('inf') game_result = { 1:"Player 1 Wins", -1:"Player 2 Wins", 0:"It is a Tie" } class Game: """To create a game, subclass this class and implement actions,...

  • I have to make a Reversi game in C++ where 2 algorithms play against eachother and I do not know ...

    I have to make a Reversi game in C++ where 2 algorithms play against eachother and I do not know how to even start it. In this project you are required to: 1. Implement Reversi for a board size of n x n where 4 ≤ n ≤ 16 and n is always even. 2. Implement two different algorithms that will play Reversi against each other e.g. an algorithm that randomly chooses a valid move may be one of your...

  • Please modify the following code to NOT have "TicTacToe extends Board" (I don't want any extending)....

    Please modify the following code to NOT have "TicTacToe extends Board" (I don't want any extending). Please ensure the resulting code completes EACH part of the following prompt: "Your task is to create a game of Tic-Tac-Toe using a 2-Dimensional String array as the game board. Start by creating a Board class that holds the array. The constructor should use a traditional for-loop to fill the array with "blank" Strings (eg. "-"). You may want to include other instance data......

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT