/** * This function first calls the AI to get a space to move to. * Next it updates the gui * Finally makes a call to determineEndgame to check if the game is over or not. */ void makeComputerMove() { computersMove = true; int compMove = TTTAI.getMove(buttons, 'O', 'X', this.difficulty); // Get computer's move. bool error = true; switch (compMove) // Update the board to reflect computer's move. { case 0: error = killButton(this.button1, 0); break; case 1: error = killButton(this.button2, 1); break; case 2: error = killButton(this.button3, 2); break; case 3: error = killButton(this.button4, 3); break; case 4: error = killButton(this.button5, 4); break; case 5: error = killButton(this.button6, 5); break; case 6: error = killButton(this.button7, 6); break; case 7: error = killButton(this.button8, 7); break; case 8: error = killButton(this.button9, 8); break; } if (!error) // An error occurred, the computer did not make a move.!!! { Form dd = new TTTDialogForm("ERROR"); dd.ShowDialog(); } determineEndgame(false); }
/** * @param userJustMoved: true if the user just made a move, false if the computer just made a move. * * This method is called each time a move is made. If the game is over as a result, show a dialog and * then reset the board. If the game is not over, then it's either the computer or the user's turn. */ void determineEndgame(bool userJustMoved) { if (isGameOver()) { // Game is over // Determine Winner. string message = ""; if (this.winner == 'X') { // User wins. if (this.AI) { this.wins++; message = "You Won!"; } else { message = "P1 Wins!"; } } else if (this.winner == 'O') { // Computer wins; user loses. if (this.AI) { this.losses++; message = "You Lost!"; } else { message = "P2 Wins!"; } } else { // There is no winner. if (this.AI) { this.ties++; } message = "You Tied!"; } // Show dialog Form endgameDialog = new TTTDialogForm(message); // Message is either "You Won!" "You Tied!" or "You Lost!" endgameDialog.ShowDialog(); // Reset the board this.gameInProgress = false; reinitializeBoard(); } else { if (userJustMoved && this.AI) { // Now the computer gets to make a move. makeComputerMove(); } else if (!this.AI) { if (!this.p2Turn) { this.p2Turn = true; } else { this.p2Turn = false; } } } }