Introduction: Tic-Tac-Toe is a very common game that is fairly easy to play. Download Free Napoleon Total War Pack File Editor Software here. The rules of the game are simple and well-known. Because of these things, Tic-Tac-Toe is fairly easy to code up. In this tutorial, we will be looking at how to code a working game of Tic-Tac-Toe in Java.
Introduction: How to Write a Tic-Tac-Toe Program in Java. In this tutorial, we will be looking at how to code a working game of Tic-Tac-Toe in Java.
This tutorial assumes that you have knowledge of the basic syntax of Java, and access to a working Java compiler. This tutorial will use the Eclipse IDE. General Outline: There are many ways to implement a game of Tic-Tac-Toe in Java, so before we begin coding, we must think about how we will implement the game specifically. For this tutorial, we will be coding a text-based version of Tic-Tac-Toe. Our Tic-Tac-Toe will start out by printing the board, and then asking for input from the first player that will specify where on the board to place that player’s mark.
After placing the mark, we will print the board state again and then ask the other player for their move. That process will be continued until one player wins or the board is filled up (indicating that a tie occurred). The input that will be taken in to specify where to place a mark will be in the format of two integers, which specify the row and column where the mark is to be placed. Below is a sample of what a game will play like. Before we can make code to run our TTT object, we need to create a working TTT object. Since a TTT object is representative of one game of Tic-Tac-Toe, it must contain two member variables. Below are the member variables that should be placed into the TTT class followed by descriptions of why they are needed.
Private char[][] board; This variable is a 2D array of characters that will be representative of the three-by-three board of a game of Tic-Tac-Toe. It will hold the state of the game inside of the TTT object at any given time. Private char currentPlayerMark; This variable will hold either an ‘x’ or an ‘o’, representing which player’s turn it is at any given point of time. The methods of the TTT class will use this when marking the board to determine which type of mark will be placed. The following is a general setup of the program. Below are all of the method headers for the methods that belong inside of the TTT class. These methods will act upon the member variables of the TTT class to make the game of Tic-Tac-Toe mutable.
Each one has a short description of what the method will do under it. These behaviours are necessary for playing a full game of Tic-Tac-Toe. Public TTT() This is the constructor. It will be responsible for ensuring the board gets initialized properly, and for setting who the first player will be. Public void initializeBoard() This method will initialize the board variable such that all slots are empty. Public void printBoard() This method will print the Tic-Tac-Toe board to standard output.
Public boolean isBoardFull() This method will check whether or not the board is full. It will return true if the board is full and a false otherwise.
Public boolean checkForWin() This method will check to see if a player has won, and if so, it will return true. Private boolean checkRowsForWin() This method will specifically check the rows for a win. Private boolean checkColumnsForWin() This method will specifically check the columns for a win. Private boolean checkDiagonalsForWin() This method will specifically check the diagonals for a win. Private boolean checkRowCol(char c1, char c2, char c3) This method will check the three specified characters taken in to see if all three are the same ‘x’ or ‘o’ letter. If so, it will return true. Note: If you code method stubs for all of the method headers into your TTT class, your compiler will likely inform you that your code has errors.
This is normal. The compiler is simply expecting for a value to be returned for all non-void methods. The initial printed board will look like the first image. It will be handled in the method public void printBoard(), which is located in the TTT class. To print the board we must access every place in the 2D array named board in our TTT class.
Because we are dealing with a 2D array, this will be handled with nested for loops. First, we just need to print a line of dashes (13 of them in this case) designating the top of the board. Below that, we need a for loop that will loop through each of the three rows.
This loop will contain a call to print a ' ' character, another for loop to loop through the columns, and a call to the System.out.println() function to print a new line and the next 13 dashes to the screen. Our inner for loop will also only loop through three columns. Since our outer for loop already printed the first character of each row of the board, we can go ahead to print the character that belongs in the box. To do this, we’ll print the character at that row and column using board[i][j] (i being the variable used for the outer for loop, which was the row, and j being the variable used for the inner loop, which is the column.) This print statement will also contain a concatenated character, to separate the boxes. The only thing left is to print the last call to print the new line to separate each row, followed by the 13 dashes.
The second attached image shows an example of what the described print function might look like. There are three different functions to check for a win: rows, columns, and diagonals. Computers have to separate these into different conditions because they are all different in terms of arrays. CheckForWin() will be our main function to test all 3 of these functions for each scenario that the user input has affected. For checkForWin() method: You simply need a return statement that calls upon the three different functions. If checking the rows for win does not return true then check the columns for win, etc.
Inside of the return statement should look like: checkRowsForWin() checkColumnsForWin() checkDiagonalsForWin() For checkRowsForWin() method: We are looping through the rows to see if there are any winners. This will require one for loop with an if statement inside of it. The for loop will be incrementing through integer i so as to check each row. For (int i = 0; i. Now we have to make sure if a player gets three in a row, he or she wins.
CheckRowCol() will be a function that will compare all three letters to each other, and if they do match, then return true. For checkRowCol() method: This method is used by the other methods to send down three values. We first check to make sure the first value is not an empty one such as ‘-’.
Then we compare the first value to the second, and the second to the third, and if and only if all three values are the same AND they are not empty statements, then this method will return true. So inside of one return() statement, our first statement will check this is not a ‘-’. (c1!= '-') Separate the first and second statements with an ‘&&’ The second statement will see if the first value is equal to the second value. (c1 == c2) Separate the second and third statements with an ‘&&’ The third statement will see if the second value is equal to the third. (c2 == c3) So your final checkRowCol() method will be one return() containing the first statement && the second statement && the third statement. Public void changePlayer() The changePlayer() method will swap the variable currentPlayerMark between x and o.
To do this, just check what the variable currently holds. If the variable is holding an 'x', then change it to an 'o'.
Otherwise, change it to an 'x'. Public boolean placeMark(int row, int col) The placeMark() method will place the correct letter onto the specified row and col in the board variable (taken in as parameters). It will return true if it was a valid placement.
Otherwise, no modification to the board variable will be made, and the player will have to try and place their letter on a different place, as an invalid spot was selected or a spot where a player already placed their letter was selected. To accomplish this behavior, a few things must be checked. First, ensure (using an if statement) that the row argument was between 0 and 2.
Next, check to ensure that the col argument was between 0 and 2. Finally, check to make sure that the spot in question currently contains a '-', signifying that no payer has marked that spot yet. If all three of these conditions check out, then place a mark (the type of which is specified by the class variable currentPlayerMark) at the location specified by row and col and then return true. If any of the three conditions are not met, then noting should happen and false should be returned. Attached to this step are images showing possible implementations of the methods mentioned above. Now that the TTT class and all of its methods are completed, a main method that runs through an entire game of Tic-Tac-Toe using out TTT object must be created. The main method must do quite a few things in order to run a full game of Tic-Tac-Toe.
First, it must create a Scanner object to take input from System.in. Also, it must instantiate a TTT object to play the Tic-Tac-Toe game with. After these things, it must initialize the board of the TTT object by calling it's initializeBoard() method. After these steps are completed, actual game play must be accounted for. To go through turns, a do while loop is required. The loop should break out when the game is over, meaning whenever the TTT object's board is full or has a winner. Inside the loop, the current board state should be printed before each turn so show the player what spaces are available and what spaces are taken.
Then, two inputs should be taken in signifying the row and column to place a mark for the turn. After this input is taken in, the mark should be placed using the TTT object's method, and the player should be changed as well using the TTT object's method. Below the while loop that handles all turns until the end of the game, it will be necessary to declare who the winner of the game is (or if the game was a tie).
To do this, check if the game was a tie first by checking if both the board was full and there was no winner. If these things are the case, then print out that the game was a tie. Otherwise, print out who won by printing out the opposite of the current state of the TTT object's currentPlayerMark variable. This can be accomplished by first calling the TTT object's changePlayer() method and then using the TTT object's getCurrentPlayerMark() method to get the state of the currentPlayerMark variable. It may also be nice to print the board out once more to show the final state of the board. An example main method has been attached as an image.
By Your mission, should you decide to accept it, is to create a Java program that can play a game of Tic-Tac-Toe with the user. As you probably know, Tic-Tac-Toe is a simple game usually played with paper and pencil. First, you make a simple 3 x 3 grid on the paper.
Then two players alternate turns by marking Xs and Os in empty spaces on the grid. The first player who makes three of his or her marks in a horizontal, vertical, or diagonal row wins. If all of the spaces in the grid are filled before any player marks three in a row, the game is a draw.
Here are the rules and instructions for this challenge: • The computer plays against the human. The human moves first and is X. The computer is O. • The program should begin by displaying a short welcome message, and then should prompt the player for his or her first move. For example: Welcome to Tic-Tac-Toe. Please enter your first move: • To designate the squares of the grid, use the letters A, B, and C for the columns and the numerals 1, 2, and 3 for the rows, like this: A1 B1 C1 A2 B2 C2 A3 B3 C3 Thus, to place an X in the top-left square, the human player would enter the text A1 when the program prompts the player for a move. After the human enters a move, the program should display the current status of the board on the console.
• Use X to mark the human’s plays and O to mark the computer’s plays. Use vertical bar characters (found on the keyboard with the backslash character, just above the Enter key) and hyphens to draw the board in a simple grid. For example, if the user has entered A1 as his or her first move, the program would display the following: X --- --- --- --- --- --- • After the human’s move, the program determines its move, announces it to the user, displays an updated board, and then prompts for the user’s move. Pokemon Black Nuzlocke Randomizer Download there. For example, you might see this: I will play A2: X O --- --- --- --- --- --- Please enter your next move: • Play continues until one player has scored three in a row or all squares have been filled with no winner.
Your program must be able to determine whether either player has scored three in a row and won the game. (This is the most difficult part of this programming challenge.) • When the game is over, the program displays a message indicating the result of the game: “You beat me!” if the human player wins, “I beat you!” if the computer player wins, or “It’s a draw!” if the game ends in a draw. • The human and computer players can play in only those squares that are not already occupied by either player. • The program ends when the game is won by either player or the game is a draw. If you want to play again, you must run the program again.
Note that you are free to use any method you wish to determine how the computer should make its moves. I suggest you have the computer always play in the first empty square. This is obviously not the best way to play Tic-Tac-Toe, and you will have no trouble beating the computer every time you play. But choosing this simple playing strategy allows you to focus on other aspects of the programming, such as how to internally represent the grid and how to determine when a player has won the game or when the game has ended in a draw. (In “Java Programming Challenge: Adding Arrays to the Simple Tic-Tac-Toe Program” you’re asked to come up with a better strategy for the program to determine its plays.) Here is an example of the console display for a complete game: Welcome to Tic-Tac-Toe.
Please enter your first move: A1 X --- --- --- --- --- --- I will play at A2: X O --- --- --- --- --- --- Please enter your next move: B1 X O --- --- --- X --- --- --- I will play at A3: X O O --- --- --- X --- --- --- Please enter your next move: C 1 X O O --- --- --- X --- --- --- X You beat me! Here are a few hints to get you started: • The best way to represent the grid is with an array. For now, use nine variables, named A1, A2, A3, B1, B2, B3, C1, C2, and C3.
• If you use the int type for the grid variables, you can then use 1 to indicate that a square contains an X and 2 to indicate that a square contains an O. • Eight possible rows can lead to a win. A player wins if any of the following combinations of squares are either 1 (for X) or 2 (for O): A1 – A2 – A3 A1 – B1 – C1 A1 – B2 – C3 B1 – B2 – B3 A2 – B2 – C2 A3 – B2 – C1 C1 – C2 – C3 A3 – B3 – C3 • There are two ways to determine whether the game is a draw. The first is to check all nine squares: If none of the squares is empty and neither player has won, the game is a draw.
The second is to count the moves: If nine moves have been made and neither player has won, the game is a draw. You can find a solution to this programming challenge on the of the Java All-in-One For Dummies, 4th Edition product page.