/// <summary> /// Cpus the move for winning. /// </summary> /// <param name="boardPositions">The board positions.</param> /// <param name="choosingCharacter">The choosing character.</param> /// <returns> int which gives position of winning of cpu or either blocking of winning of user.</returns> public static int CpuMoveForWinning(char[] boardPositions, char[] choosingCharacter) { //returning the position of winning of cpu. for (int i = 1; i <= 9; i++) { if (boardPositions[i] == ' ') { boardPositions[i] = choosingCharacter[1]; if (TicTacToe.CheckingForWinning(boardPositions) == 0) { boardPositions[i] = ' '; return(i); } boardPositions[i] = ' '; } } //returning the position where cpu blocks the winning position of user. for (int j = 1; j <= 9; j++) { if (boardPositions[j] == ' ') { boardPositions[j] = choosingCharacter[0]; if (TicTacToe.CheckingForWinning(boardPositions) == 0) { boardPositions[j] = ' '; return(j); } boardPositions[j] = ' '; } } return(0); }
/// <summary> /// Adding the positions in array filled by user and cpu and displaying it on board. /// </summary> /// <param name="boardPositions">The board positions.</param> /// <param name="choosingCharacter">The choosing character.</param> /// <param name="tossResult">The toss result.</param> public static void MarkingPositions(char[] boardPositions, char[] choosingCharacter, int tossResult) { int checkForWin; int index = tossResult; //do while loop moves until game is drawn or any player wins. do { //switches input values between cpu and player one by one. Index value starts from toss result. switch (index % 2) { //input by user. case 0: { Console.WriteLine("Please enter the position between 1 to 9 where you want to fill your character"); while (true) { int positionEnteredByUser = Convert.ToInt32(Console.ReadLine()); if (positionEnteredByUser <= 9 && positionEnteredByUser >= 1) { //if position in array and board is vacant, character is added. if (boardPositions[positionEnteredByUser] == ' ') { boardPositions[positionEnteredByUser] = choosingCharacter[index % 2]; TicTacToe.Board(boardPositions); break; } else { Console.WriteLine("The position is already occupied, please enter position again"); } } else { Console.WriteLine("Please enter the correct position to fill"); } } break; } // input done by user. case 1: { //calling CpuMove method which processes input by cpu and enters in array and displays it on board. TicTacToe.CpuMove(boardPositions, choosingCharacter, index); break; } default: break; } // calling CheckingForWinning method to see if game is ending or not. checkForWin = TicTacToe.CheckingForWinning(boardPositions); //if checkForWin ==0, one of the player has win the game. if (checkForWin == 0) { if (index % 2 == 0) { Console.WriteLine("You have won the game"); } else { Console.WriteLine("Cpu has won the game"); } break; } index++; //if checkforWin= -1, than game is neither draw nor won by any player, positions are vacant in board. } while (checkForWin == -1); }