Introduction: Make Tic Tac Toe in Java
This Instructable will guide you, step by step, through making Tic Tac Toe in Java! This is not intended to be an overview of the Java language, but more of a guided example. The first step will go over some basic concepts to make the rest of the guide go down smoother. All other aspects will be briefly explained as they’re introduced.
You need to be competent with a computer and your chosen operating system. You do not need any prior exposure to Java or any other programming language. However, this guide may go over a bit too much, too fast, and not deep enough for some people. If you find yourself getting confused often, take the time to read over a Java overview.
You need to be competent with a computer and your chosen operating system. You do not need any prior exposure to Java or any other programming language. However, this guide may go over a bit too much, too fast, and not deep enough for some people. If you find yourself getting confused often, take the time to read over a Java overview.
Step 1: Understand Basic Java Concepts
For this Instructable, the main thing you need to know about Java is that it is an object-oriented programming language. An object-oriented programming language consists of objects that communicate with each other. Objects contain associated data fields and typically have methods that perform a variety of tasks. These tasks vary from manipulating the object’s data to communicating with other objects.
To break this down, a Java program is typically comprised of objects. These objects are defined by classes, and within these classes are instance variables and methods.
Classes
These are what you will be coding. Think of classes as the blueprints for the object. They describe what the object contains and what it can do.
Instance Variables
These are the attributes of the object. For example, a Student object would have instance variables like name, GPA, and classification.
Methods
These are the actions that an object can make. To use the Student example, these could be things like getting the GPA or taking a class.
Don’t worry if you don’t quite grasp these concepts yet. Building the program will help make these more concrete.
To break this down, a Java program is typically comprised of objects. These objects are defined by classes, and within these classes are instance variables and methods.
Classes
These are what you will be coding. Think of classes as the blueprints for the object. They describe what the object contains and what it can do.
Instance Variables
These are the attributes of the object. For example, a Student object would have instance variables like name, GPA, and classification.
Methods
These are the actions that an object can make. To use the Student example, these could be things like getting the GPA or taking a class.
Don’t worry if you don’t quite grasp these concepts yet. Building the program will help make these more concrete.
Step 2: Get the JDK
First, you need to download and install the Java Development Kit (JDK), which will provide you the backend tools for developing. This can be found here. Once you load that page up, download and install the JDK. For help, follow these:
Note: The number in parentheses signifies its location on the image above.
1. Click on the Download button (1) underneath JDK.
2. Accept the license agreement. (2)
3. Click on the link (4) that that corresponds with your operating system (3).
4. Once the file is down downloading, install it.
Note: The number in parentheses signifies its location on the image above.
1. Click on the Download button (1) underneath JDK.
2. Accept the license agreement. (2)
3. Click on the link (4) that that corresponds with your operating system (3).
4. Once the file is down downloading, install it.
Step 3: Get Eclipse
Eclipse is the program you will be programming in. Now, you don’t install Eclipse, so follow the instructions.
1. Go here.
2. Look for Eclipse IDE for Java Developers. (1)
3. If you have Windows, download from the correct link on the right. (2)
4. If you do not have Windows, click on Details. (3) Then choose the correct download link on the right.
5. Once you get to the download page, click on the green down arrow and download Eclipse.
6. This may take a while, as Eclipse is rather big.
7. After it’s done, find where you saved.
8. Extract the zip file to wherever you want. I put it in my Programs folder.
9. Run Eclipse.
1. Go here.
2. Look for Eclipse IDE for Java Developers. (1)
3. If you have Windows, download from the correct link on the right. (2)
4. If you do not have Windows, click on Details. (3) Then choose the correct download link on the right.
5. Once you get to the download page, click on the green down arrow and download Eclipse.
6. This may take a while, as Eclipse is rather big.
7. After it’s done, find where you saved.
8. Extract the zip file to wherever you want. I put it in my Programs folder.
9. Run Eclipse.
Step 4: Set Up the Files
Shortly after you start up Eclipse, it'll ask you for a workspace location. Put this wherever you want. After you choose, the Eclipse workbench will pop up. If it doesn't, click on the arrow on the right side. Take a few minutes to play around and familiarize yourself with the interface.
The Files
For this project, I wrote most of the code for you. To get it set up in your Eclipse, follow this:
1. Download the Jar file.
2. Go to File -> Import....
3. Drill down the General folder (1) and select Existing Projects into Workspace. (2) Click Next.
4. Click Select archive file. (3)
4. Click Browse... (3) and navigate to where you saved the zip file. Open it.
5. Click Finish.
The Files
For this project, I wrote most of the code for you. To get it set up in your Eclipse, follow this:
1. Download the Jar file.
2. Go to File -> Import....
3. Drill down the General folder (1) and select Existing Projects into Workspace. (2) Click Next.
4. Click Select archive file. (3)
4. Click Browse... (3) and navigate to where you saved the zip file. Open it.
5. Click Finish.
Step 5: Understand Project Structure
Packages (1)
Packages provide an organizational tool for Java projects by grouping similar classes together. A common naming convention is to use your domain backwards. As you can see, this project uses the Instructable domain. This helps to eliminate any issues when integrating Java programs. You may not run into this, but it is a good habit to get into.
The two packages in this project are game and main. The game package contains the more backend information for running the game. The main package includes the class that interacts with the user.
Classes (2)
There are three classes in this project--Board, Player, an Runner. When deciding which classes need to be made for a project, think about the elements of what you're making. In this case, Tic Tac Toe only had two notable elements--a player to play the game and a board to play the game on. More complex programs will require more classes.
Board
This represents the Tic Tac Toe board. This class handles keeping track the of the state of the board and if the board is a winning board.
Player
This represents a player in Tic Tac Toe. It's a fairly simple class. It stores the player's name and it's playing symbol It also handles marking the board.
Runner
This class is what runs the program. We'll go into an overview in the next step.
Packages provide an organizational tool for Java projects by grouping similar classes together. A common naming convention is to use your domain backwards. As you can see, this project uses the Instructable domain. This helps to eliminate any issues when integrating Java programs. You may not run into this, but it is a good habit to get into.
The two packages in this project are game and main. The game package contains the more backend information for running the game. The main package includes the class that interacts with the user.
Classes (2)
There are three classes in this project--Board, Player, an Runner. When deciding which classes need to be made for a project, think about the elements of what you're making. In this case, Tic Tac Toe only had two notable elements--a player to play the game and a board to play the game on. More complex programs will require more classes.
Board
This represents the Tic Tac Toe board. This class handles keeping track the of the state of the board and if the board is a winning board.
Player
This represents a player in Tic Tac Toe. It's a fairly simple class. It stores the player's name and it's playing symbol It also handles marking the board.
Runner
This class is what runs the program. We'll go into an overview in the next step.
Step 6: Understand the Runner
Let's look over the Runner class and try to get a feel for how it's structured.
Class Declaration
Look toward the top where it says public class Runner. This is the class declaration. The public part is an access modifier. An access modifier says who has access to this class. Access modifiers can be:
- Public
- Protected
- Private
You will almost always make a class public. Protected and private are reserved for special types of classes that we will not get into. Just know that public classes can be used by anything. The second part of the declaration--class--says we're making a class. The third part--Runner--is the name. The curly brace starts a code block. All code for this class must be within the two curly braces.
Note: Curly braces are used for all code blocks, not just classes.
Main Method
The main method, as noted in the picture, is what runs when you run the program. Don't worry about the whole public static void mess. But, do take note as to what's happening inside the main method. The first line creates a Board object called board. The rest of the lines are method calls. Method calls run the method with the given name.
Typical main methods contain more code than this, but I organized it this way for a clearer understanding of the process the program goes through.
Method Headers
Method headers are the first line of methods. They describe what the method intends to do. Let's look at private static String playGame(Board board)
private is an access modifier, just like the class one. In this case, private means that only the Runner class can call this method.
Ignore static. This is more advanced topic.
String describes what the method will give back once it finishes running. In this case, it’s a String, which means it’ll give back a word or a string of words. In this case, it's returning null, which represents nothing.
playGame is simply the name of the method.
(Board board) is called a parameter. This is outside information that the method needs to run. In this case, it needs a Board object.
Class Declaration
Look toward the top where it says public class Runner. This is the class declaration. The public part is an access modifier. An access modifier says who has access to this class. Access modifiers can be:
- Public
- Protected
- Private
You will almost always make a class public. Protected and private are reserved for special types of classes that we will not get into. Just know that public classes can be used by anything. The second part of the declaration--class--says we're making a class. The third part--Runner--is the name. The curly brace starts a code block. All code for this class must be within the two curly braces.
Note: Curly braces are used for all code blocks, not just classes.
Main Method
The main method, as noted in the picture, is what runs when you run the program. Don't worry about the whole public static void mess. But, do take note as to what's happening inside the main method. The first line creates a Board object called board. The rest of the lines are method calls. Method calls run the method with the given name.
Typical main methods contain more code than this, but I organized it this way for a clearer understanding of the process the program goes through.
Method Headers
Method headers are the first line of methods. They describe what the method intends to do. Let's look at private static String playGame(Board board)
private is an access modifier, just like the class one. In this case, private means that only the Runner class can call this method.
Ignore static. This is more advanced topic.
String describes what the method will give back once it finishes running. In this case, it’s a String, which means it’ll give back a word or a string of words. In this case, it's returning null, which represents nothing.
playGame is simply the name of the method.
(Board board) is called a parameter. This is outside information that the method needs to run. In this case, it needs a Board object.
Step 7: Set Up Objects
You will be doing most of the work in the playGame method.
First, we need to set up some necessary objects. Every game needs players. In the case of Tic Tac Toe, we need two players. Delete the TODO tag and paste in the following:
Player playerX = new Player('X', board);
Player playerO = new Player('O', board);
These lines declare and set two player objects. One has a symbol of X and the other a symbol of O. They also give the player objects the board that they will play on.
Next we need to set up a way of taking input from the user. To do this, paste the following after the players:
Scanner in = new Scanner(System.in);
This sets up a Scanner object called in. System.in simply means we’re taking input from the console.
If you see warnings, don't worry. They're supposed to be there.
First, we need to set up some necessary objects. Every game needs players. In the case of Tic Tac Toe, we need two players. Delete the TODO tag and paste in the following:
Player playerX = new Player('X', board);
Player playerO = new Player('O', board);
These lines declare and set two player objects. One has a symbol of X and the other a symbol of O. They also give the player objects the board that they will play on.
Next we need to set up a way of taking input from the user. To do this, paste the following after the players:
Scanner in = new Scanner(System.in);
This sets up a Scanner object called in. System.in simply means we’re taking input from the console.
If you see warnings, don't worry. They're supposed to be there.
Step 8: Make the Loop
Next, we need to set up a loop. Loops run sections of codes over and over until a condition is met. In this case, the loop will run until the players are done playing. First, we need to make a conditional. A good type to use for these are booleans, which can only contain true or false. Paste the following after the Scanner:
boolean keepPlaying = true;
Next, make the loop:
while (keepPlaying) {
}
This is a while loop. It'll keep running as long as the condition inside the parentheses is true.
boolean keepPlaying = true;
Next, make the loop:
while (keepPlaying) {
}
This is a while loop. It'll keep running as long as the condition inside the parentheses is true.
Step 9: Select a Player
Now we need to select which player will take a turn. To do this, we need to keep track of what turn we're currently on and which player is currently going. Paste this somewhere outside the loop:
Player currPlayer;
int turnCount = 0;
currPlayer tracks current player and turnCount stores the turn number. The int type stores integers.
Within the loop we need to increment the count before we do anything else. We do this by:
turnCount++;
This is the equivalent of turnCount = turnCount + 1. Basically, it adds one to turnCount. Next, we need to add in an if statement that decides which player will go.
if (turnCount % 2 == 0) {
currPlayer = playerO;
} else {
currPlayer = playerX;
}
When it is an even turn number, playerO will go, otherwise it’s playerX’s turn. The % is called a modulus. It finds the remainder of a number after it’s been divided. In this case, we’re getting the remainder after turnCount is divided by two. If the remainder is zero, it’s an even number.
Player currPlayer;
int turnCount = 0;
currPlayer tracks current player and turnCount stores the turn number. The int type stores integers.
Within the loop we need to increment the count before we do anything else. We do this by:
turnCount++;
This is the equivalent of turnCount = turnCount + 1. Basically, it adds one to turnCount. Next, we need to add in an if statement that decides which player will go.
if (turnCount % 2 == 0) {
currPlayer = playerO;
} else {
currPlayer = playerX;
}
When it is an even turn number, playerO will go, otherwise it’s playerX’s turn. The % is called a modulus. It finds the remainder of a number after it’s been divided. In this case, we’re getting the remainder after turnCount is divided by two. If the remainder is zero, it’s an even number.
Step 10: Get Input
We need to get the user's input as to where they want to make a move. This is where we use the Scanner object we made earlier. However, first we need to make a variable to store the input in. Paste this outside of the loop:
int play;
Next, paste this after the if statement:
System.out.print(currPlayer.getName() + ", make a move (1-9): ");
play = in.nextInt();
There's a lot going on here. First, we print out a prompt for the user to input something. System.out.println prints whatever is inside its parentheses to the console. This prints the current player’s name followed by “make a move (1 – 9)”.
Let’s stop a second at currPlayer.getName(). This is still a method call, just like the ones in the main method. However, in this case we’re calling it on an object. There is a method inside of the Player object called getName, and we’re using that to retrieve the player’s name.
After that, we have the act of taking in the input. To take in integer input, we use the nextInt method of the Scanner object. Then we store this input in our play variable.
int play;
Next, paste this after the if statement:
System.out.print(currPlayer.getName() + ", make a move (1-9): ");
play = in.nextInt();
There's a lot going on here. First, we print out a prompt for the user to input something. System.out.println prints whatever is inside its parentheses to the console. This prints the current player’s name followed by “make a move (1 – 9)”.
Let’s stop a second at currPlayer.getName(). This is still a method call, just like the ones in the main method. However, in this case we’re calling it on an object. There is a method inside of the Player object called getName, and we’re using that to retrieve the player’s name.
After that, we have the act of taking in the input. To take in integer input, we use the nextInt method of the Scanner object. Then we store this input in our play variable.
Step 11: Make a Play
Now that we have the play the player wants to make, we need to actually make it. The way I wrote the code, after a play is made on the board, it determines if that play was a winning one. So, we need to make a variable to store if a win has occurred. Outside the loop, paste this:
boolean hasWon = false;
This is set to false, as there is not a win until it happens. Next, we need to call the right method to make the play. Paste this after the input:
hasWon = currPlayer.makePlay(Player.cells[play - 1]);
This takes whatever the makePlay method of Player returns and stores it in hasWon. It will return true if the play won the game, false otherwise. Player.cells[play - 1] figures out which cell the player wants to play in. Don't worry about the technicalities of it.
boolean hasWon = false;
This is set to false, as there is not a win until it happens. Next, we need to call the right method to make the play. Paste this after the input:
hasWon = currPlayer.makePlay(Player.cells[play - 1]);
This takes whatever the makePlay method of Player returns and stores it in hasWon. It will return true if the play won the game, false otherwise. Player.cells[play - 1] figures out which cell the player wants to play in. Don't worry about the technicalities of it.
Step 12: Deal With a Win
How do we deal with a win? First, we need a variable that stores the winner. Paste this outside the loop:
String winner = "Tie";
This needs to be set to "Tie," as the default occurrence if no one wins is a tie. Now, we need to write a little if statement to handle a win. Paste this after the code to make a play:
if (hasWon) {
winner = currPlayer.getName();
keepPlaying = false;
}
This says that if there is a win, set the current player as the winner and stop the loop, as the game is over.
However, that's not all. Remember back when we said that playGame returns a String? That String is the name of who won (or if it's a tie). Change the null at the end of the method to winner.
String winner = "Tie";
This needs to be set to "Tie," as the default occurrence if no one wins is a tie. Now, we need to write a little if statement to handle a win. Paste this after the code to make a play:
if (hasWon) {
winner = currPlayer.getName();
keepPlaying = false;
}
This says that if there is a win, set the current player as the winner and stop the loop, as the game is over.
However, that's not all. Remember back when we said that playGame returns a String? That String is the name of who won (or if it's a tie). Change the null at the end of the method to winner.
Step 13: Deal With a Tie
Dealing with a tie is fairly simple. Paste this after the winning if statement:
if (turnCount == 9) {
keepPlaying = false;
}
If we are on the 9th turn, then all the cells have been filled, so just end the loop. Take note of the double equals sign (==). As you've seen, the single equals sign (=) sets values to variables. The double equals sign checks to see if two variables contain the same values.
That's it. If it's a tie, then winner still has "Tie" stored in it.
if (turnCount == 9) {
keepPlaying = false;
}
If we are on the 9th turn, then all the cells have been filled, so just end the loop. Take note of the double equals sign (==). As you've seen, the single equals sign (=) sets values to variables. The double equals sign checks to see if two variables contain the same values.
That's it. If it's a tie, then winner still has "Tie" stored in it.
Step 14: Add in Board Printing
There's just one last thing we have to do. To make the game user friendly, we want to print the board after every move. To do this, paste this right under the beginning of the loop:
printBoard(board);
Congratulations! You finished the playGame method.
printBoard(board);
Congratulations! You finished the playGame method.
Step 15: Print the Winner
Lastly, we need to print who won to the console. Scroll all the way down to the bottom and find the TODO tag. It is inside the printWinner method. Notice that the return type on this method is void. This means that the method doesn't return anything. Paste this inside the method:
if (winner.equals("Tie")) {
System.out.println("It's a tie!");
} else {
System.out.println(winner + " won!");
}
This says that if it's a tie, print "It's a tie!" If there is a winner, then print who won. Simple, right?
if (winner.equals("Tie")) {
System.out.println("It's a tie!");
} else {
System.out.println(winner + " won!");
}
This says that if it's a tie, print "It's a tie!" If there is a winner, then print who won. Simple, right?
Step 16: Run It
Congratulations, you made your first Java program! Now run by clicking the green circle with a play symbol in it (1) and enjoy your hard work.
If you wish to self-learn the code that I did not go over, I made sure to document heavily. Go take a look and good luck!
If you wish to self-learn the code that I did not go over, I made sure to document heavily. Go take a look and good luck!