In: Computer Science
For a game that takes user input of certain letters, Upper: O,C,I,Z; Lower: o,c,i,z. The board is a 4 by 4 matrix and the numbers on the right are the positon that correspond with the dots. So if player 2 statisfies the requirement for the winning condition. Winning conditions being 4 letters in a row of (all upper case-- Z I C O ), (all straight-line-- Z I i I), (all consonants - Z z C c), (all curved-- C o O c), (all vowels-- I i O o). Using C++, how does one create a function that returns if there winning condition in the board.
--------- Square # | . . . . | 1 2 3 4 | o I i O | 5 6 7 8 | . . . . | 9 10 11 12 | . . . . | 13 14 15 16 ---------
^^ this shows a possible winning move. You can win with a row or a column or diagonal or corners if it matches winning conditions. So you can also win if those letters were vertically or diagonally or even in four corners.
Screenshot
Program
#include <iostream>
#include<string>
using namespace std;
//Function prototype
bool checkWinner(char board[4][4]);
int main()
{
//Test board
char board[4][4] = {
{'.','.','.','.'},{'o','I','i','O'},{'.','.','.','.'},{'.','.','.','.'}
};
//Check winner
if (checkWinner(board)) {
cout << "Game
completed!!!\n";
}
else {
cout << "Game not
completed!!!\n";
}
}
//Function check winning condition
bool checkWinner(char board[4][4]) {
string str = "";
string winningStr1 = "ZICO", winningStr2 = "ZIiI",
winningStr3 = "ZzCc", winningStr4 = "CoOC", winningStr5 =
"IiOo";
//Horizontal check
for (int i = 0; i < 4; i++) {
str = "";
for (int j = 0; j < 4; j++)
{
str +=
board[i][j];
}
if (str == winningStr1 || str ==
winningStr2 || str == winningStr3 || str == winningStr4 || str ==
winningStr5) {
return
true;
}
}
//Vertical check
for (int i = 0; i < 4; i++) {
str = "";
for (int j = 0; j < 4; j++)
{
str +=
board[j][i];
}
if (str == winningStr1 || str ==
winningStr2 || str == winningStr3 || str == winningStr4 || str ==
winningStr5) {
return
true;
}
}
//Diagonal
str = "";
for (int j = 0; j < 4; j++) {
str += board[j][j];
}
if (str == winningStr1 || str == winningStr2 || str ==
winningStr3 || str == winningStr4 || str == winningStr5) {
return true;
}
//Backword
str = "";
for (int j = 3; j >=0; j--) {
str += board[j][j];
}
if (str == winningStr1 || str == winningStr2 || str ==
winningStr3 || str == winningStr4 || str == winningStr5) {
return true;
}
return false;
}