Question: C coding: Write a function win() with the following prototype: int win(char board[6][6], char player) The function win should return a 1 if the character
C coding:
Write a function win() with the following prototype:
int win(char board[6][6], char player)
The function win should return a 1 if the character player is found in three consecutive positions in the board.
Consecutive for this lab means in the same row, or in the same column, NOT on a diagonal.
For the board shown below,
Z A B G G E Z B A G G G Z Z X G K K X X O K O W X X O O W W
The following values should be returned by win() if called as:
win(board,'A') would return 0
win(board,'B') would return 0
win(board,'D') would return 0
win(board,'G') would return 1
win(board,'O') would return 0
win(board,'X') would return 0
win(board,'Z') would return 1
GIVEN:
#include
int win(char a[6][6], char player) { int i,j;
for(i=0;i<6;i++) { for(j=0;j<6;j++) { if(j==4) { if(a[i][j]==player && a[i][j+1]==player && a[i+1][0]==player) { return 1; } } if(j==5) { if(a[i][j]==player && a[i+1][0]==player && a[i+1][1]==player) { return 1; } } if(a[i][j]==player && a[i][j+1]==player && a[i][j+2]==player) { return 1; } } }
for(i=0;i<6;i++) { for(j=0;j<6;j++) { if(i==4) { if(a[j][i]==player && a[j][i+1]==player && a[j][0]==player) { return 1; } } if(i==5) { if(a[j][i]==player && a[j][0]==player && a[j][1]==player) { return 1; } } if(a[j][i]==player && a[j+1][i]==player && a[j+2][i]==player) { return 1; } } } return -1; }
int main() { char board[6][6]; int i,j; char user; int gameresult;
printf("Enter 36 values for the 6x6 game board "); for(i=0;i<6;i++){ for(j=0;j<6;j++) { scanf("%c ",&(board[i][j])); } }
// print the gamr board for(i=0;i<6;i++) { for(j=0;j<6;j++) { printf("%c ",(board[i][j])); } printf(" "); } do { fflush(stdin); printf("Enter the uesr's token to see if they won the game!"); scanf(" %c",&user); printf(" "); gameresult = win(board,user); if (gameresult == 1) { printf("Player %c won the game!",user); } else if (gameresult == -1) { printf("Player %c didn't win.",user); } else { printf("invalid response from win() "); printf(" "); } while(user!='x'); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
