IT115: Introduction to Java Programming 1 IT115: Introduction to Java Programming Tic Tac Toe Application Trina VanderLouw Professor Derek Peterson Colorado Technical University Online October 28, 2011 Highlights: Java, Building Applications, Creating Javadocs, Importing Libraries Programs Used: NetBeans IDE, CTU Virtual Campus Instructor Feedback: Thanks for letting me show-off your code during the chat. You did a superb job on the code. It is nicely formatted, you do that well which makes it easy to follow. Instructor Recommendation: I had the pleasure of having Trina in my introduction to java programming course. She was an exemplary student and took control of her learning. I have taught this course for CTU Online for more than 3 years and she stands with a very short list of people who truly were successful. As a part-time adjunct professor who works full-time as an IT Director/Vice President managing and hiring programmers, given the opportunity to recommend and/or hire Trina for an IT position; I would not hesitate. She displayed in the 11 weeks I worked with her the aptitude and capability to be successful. Final Grade: A
IT115: Introduction to Java Programming 2 Tic Tac Toe Game Code and Libraries in NetBeans IDE -------------------- UML Diagrams --------------------
IT115: Introduction to Java Programming 3 ---------------------------- ACTIVITY DIAGRAMS ---------------------------- Players move inside of the play method activity repeats until win = true then the play is over
IT115: Introduction to Java Programming 4 Main Class File
IT115: Introduction to Java Programming 5 Java File for the Public Classes
IT115: Introduction to Java Programming 6 Java File for Tic Tac Toe Board
IT115: Introduction to Java Programming 7 /* * Trina VanderLouw * October 20, 2011 * IT115: Java Programming * Professor Derek Peterson import java.util.scanner; * This reusable class is for a Tic Tac Toe Game - It constructs a game board * with three columns and three rows and sets up a Player X and a Player O - * Each player takes turns and when one person wins it will display a message - * The counts for the winners are tallied and stats are displayed at the end * of the game - If there is a tie the program will allow one more game to be * played for a tiebreaker. * @author TrinaV public class TicTacToeGame // Creates new game board with 9 set values placed in the array private boardpiece[][] board = new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(), new boardpiece(); private int count = 0; // Counts the amount of turns - determines a draw private boolean win = false; // Sets win to false so a move can be made private char turn = 'X'; // Initializes turn to X so player X goes first private int xwon = 0; // Tallies how many games are won by Player X private int owon = 0; // Tallies how many games are won by Player O private int xlost = 0; // Tallies how many games are lost by Player X private int olost = 0; // Tallies how many games are lost by Player O * This public boolean allows the value to be passed to the test method * and determines whether or not the game will be restarted in the do_while * loop in the main method. public boolean again; // Returns true or false in the main method Scanner input = new Scanner(System.in); * This constructor is empty and allows for a new instance to be created public TicTacToeGame()
IT115: Introduction to Java Programming 8 * This method welcomes the players to the game public void displaywelcome() System.out.println("Welcome to Tic Tac Toe!"); System.out.print("Good Luck!!\n"); * This method checks to see if the game has been won and if not calls the * move method which initiates the next player's turn. public void play() // If the game has not been won, the next move will be initiated while (!win) // Calls the move method to start the next turn move(); // Ends play method * This method displays the current game board - Each place on the board * will have either an _X_, _O_, or. public void displayboard() // Runs a loop to display all the rows for (int i = 0; i < 3; i++) // Runs a loop to display all the columns for (int j = 0; j < 3; j++) // Prints out each space with the current value stored there System.out.print(board[i][j].piece); System.out.println(); // Ends displayboard method * This method tells the players whose turn it is and asks for their move - * the move entered will be checked using the checkmove method and if valid * will be entered onto the board - The board gets displayed and the program * checks for a winning move - If the game is not over the turn will switch * to the next player.
IT115: Introduction to Java Programming 9 public void move() int move = 0; // Stores the game board square the player selects String valid = " "; // Set to blank so the choice can be validated // Displays whose turn and prompts for selection System.out.print("\nPlayer " + turn + ", it's your turn!\n" + "Select a move (1-9): "); // Starts a loop for the selection and vaildation do // Stores the move so it can be passed to the checkmove method move = input.nextint(); // Sets valid to the return value in checkmove valid = checkmove(move); // If the player enters a number that is not between 1 and 9 they // will get an error prompting them to enter another number if (valid.equals("error:1")) System.out.print("Please enter a space between 1-9: "); // If the player chooses a space that is already taken they will // receive an error message prompting them to select a different one if (valid.equals("error:2")) System.out.print("Sorry, that space is not available.\n" + "Please enter another space: "); // Continues the validation loop until it returns OK while (!valid.equals("ok")); // Increments number of turns taken so game will stop after 9 turns count++; // Enters the turn into the proper place and marks the space as used board[(move - 1) / 3][(move - 1) % 3].piece = "_" + turn + "_ "; board[(move - 1) / 3][(move - 1) % 3].player = turn; board[(move - 1) / 3][(move - 1) % 3].used = true; // Calls the displayboard method to show the users the current board displayboard(); // Checks to be sure game is not over and then checks for a winning
IT115: Introduction to Java Programming 10 // move by calling the checkwin method if (count <= 9) // Checks to see if there are three in a row, column, or diagonal // and ends the game if there is a winning move checkwin(move); // Switches the players' turns so they alternate if (turn == 'X') turn = 'O'; else turn = 'X'; // Ends move method * This method will validate the entry by the player - If the number entered * is not between 1 and 9 it will return an Error 1 and if the space is * already taken it will return an Error 2, otherwise the number will be * validated so the move can be marked on the board. * @param move * @return public String checkmove(int move) // Sets validator to integers 1 through 9 or else returns Error 1 if (move < 1 move > 9) return "Error:1"; // Sets validator to check for empty spot or else returns Error 2 if (board[(move - 1) / 3][(move - 1) % 3].used) return "Error:2"; // Returns OK if value entered is validated return "OK"; // Ends checkmove * This method checks for a winning move - if there are three across, three * down, or three diagonal of the same character the current game will end * and a congratulations message will be displayed to the players - At the
IT115: Introduction to Java Programming 11 * end of the game the stats will be updated by players whether they won * or lost - If the game ends in a draw no stats will be incremented. * @param move public void checkwin(int move) // Starts loop to check for winning combination of moves in rows for (int i = 0; i < 3; i++) // Checks to see if each column in the row is used and if so if // each one has the same value stored if ((board[i][0].used && board[i][1].used && board[i][2].used) && (board[i][0].player == board[i][1].player) && (board[i][1].player == board[i][2].player)) System.out.printf("\nYou WIN!!\nCongrats, Player " +turn+ "!"); // Increments the winning and losing scores if (turn == 'X') xwon++; olost++; else owon++; xlost++; // Sets win to true so the game ends win = true; return; // Starts loop to check for winning combination of moves in columns for (int j = 0; j < 3; j++) // Checks to see if each row in the column is used and if so if // each one has the same value stored if ((board[0][j].used && board[1][j].used && board[2][j].used) && (board[0][j].player == board[1][j].player) && (board[1][j].player == board[2][j].player)) System.out.printf("\nYou WIN!!\nCongrats, Player " +turn+ "!"); // Increments the winning and losing scores if (turn == 'X') xwon++; olost++;
IT115: Introduction to Java Programming 12 else owon++; xlost++; // Sets win to true to the game ends win = true; return; // Checks for winning combination of moves in diagonal [0][0] to [2][2] if ((board[0][0].used && board[1][1].used && board[2][2].used) && (board[0][0].player == board[1][1].player) && (board[1][1].player == board[2][2].player)) System.out.printf("\nYou WIN!!\nCongrats, Player " + turn + "!"); // Increments the winning and losing scores if (turn == 'X') xwon++; olost++; if (turn == 'O') owon++; xlost++; // Sets win to true so the game ends win = true; return; // Checks for winning combination of moves in diagonal [2][0] to [0][2] if ((board[2][0].used && board[1][1].used && board[0][2].used) && (board[2][0].player == board[1][1].player) && (board[1][1].player == board[0][2].player)) System.out.printf("\nYou WIN!!\nCongrats, Player " + turn + "!"); // Increments winning and losing scores if (turn == 'X') xwon++; olost++;
IT115: Introduction to Java Programming 13 if (turn == 'O') owon++; xlost++; // Sets win to true so the game ends win = true; return; // Checks to see if the count is at the maximum number of moves and // then displays message that the game was a draw with no winner if (count == 9) System.out.print("\nDRAW\nSorry, there is no winner this time!"); // Sets win to true so the game ends win = true; return; * This method initializes all the attributes so the game can continue with * a new game board - The turn is not initialized to X as it is in the first * game so that the player who lost will get the chance to start first on * the new board. public void init() // Starts a loop to initialize each piece on the game board as empty // Without resetting these a new game would think the spaces were used for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) board[i][j] = new boardpiece(); // Sets win to false so game can start over by staring another move win = false; // Resets counter to 0 so the moves can increment again to 9 // Without resetting this the game would think it is a draw
IT115: Introduction to Java Programming 14 count = 0; * This method allows the players to decide if they would like to play a * new game board - It returns the attribute 'again' to the main method so * the loop can continue or end depending on the value stored. * @return public boolean again() // Prompts user to enter 1 for yes and 2 for no to restart new game System.out.print("\n\nWould you like to play again?\n" + "Enter 1 = yes, 2 = no: "); // Stores value of number entered int newgame = input.nextint(); // If user wants to play again the board will be initialized and the // value will return true to the main method if (newgame == 1) again = true; init(); return again; // If the player did not enter 1 the value will be set false and the // loop in the main method will end again = false; return again; * This method displays the results of the games played - It shows a total * for the number of games won and lost by each player - If there is a tie * it will give the players a chance to play one more game for a tiebreaker. public void stats() // Prints out the results of the players' stats System.out.printf("\nPLAYER X Won: %d Lost: %d", xwon, xlost); System.out.printf("\nPLAYER 0 Won: %d Lost: %d\n", owon, olost); // If X won a congratulations message will be printed if (xwon > owon) System.out.println("\nCongratulations, Player X!");
IT115: Introduction to Java Programming 15 // If O won a congratulations message will be printed if (xwon < owon) System.out.println("\nCongratulations, Player O!"); // If the games won were tied it will prompt for a tiebreaker if (xwon == owon) System.out.println("\nX and O Tied!\n" + "Would you like to play a tiebreaker?\n" + "Enter 1 = yes, 2 = no: "); int tiebreaker = input.nextint(); // If the players want one more game the board will be initialized // and the play method will start once to determine the winner if (tiebreaker == 1) init(); play(); // Ends stats method * This method displays a good-bye message to the user. public void displaygoodbye() // Calls the stats method to display stats of all games won and lost stats(); System.out.print("\n\nThanks for playing.\ngood-bye!\n"); // Ends displaygoodbye method
IT115: Introduction to Java Programming 16