Lab Assignment 17 - Working with Object Arrays In the old days we would do these
ID: 3778055 • Letter: L
Question
Lab Assignment 17 - Working with Object Arrays
In the old days we would do these projects as applets. Unfortunately, applets are not as secure as Sun / Oracle once thought they were. Now, it is almost impossible to run an applet over the web. If you want to see how the Tic-Tac-Toe game looks you will have to view this video
In this homework, you'll build your own version of TicTacToe using JLabels, GridLayout, and a couple arrays. Before you get started, however, why don't you take a minute to play a game?
Declare a two-dimensional array of primitive values
Declare a two-dimensional array of object references
Initialize each of the elements in a two-dimensional array of object references
Use a pair of nested for loops to process the elements in a two-dimensional array
Create a class called TicTacToe. Place it in a file called TicTacToe.java
Have your class extend from JFrame
Have your class implement ActionListener and MouseListener.
Create all of the methods needed for the ActionListener and MouseListener interfaces.
Make sure to import javax.swing.*, java.awt.* and java.awt.event.*
Before ddefining your attributes you need to create a container called content and initialize it by sending the getContentPane() message to this.
Define your application's attributes. The TicTacToe program has three different kinds of fields that you must define before you can compile the program successfully. Make sure you define your fields and check for errors before you attempt to go further.
Here are the three kinds of fields:
1. Program Arrays
The TicTacToe program has two "parallel", 3 x 3, two dimensional arrays. Start your programming by defining these two arrays:
The first of these is an array of JLabel objects. This array, named grid, is used to display the actual Xs and Os on your screen. Each JLabel will display an X, and O, or a blank.
The second array is an array of char primitives. This array, named game, is used to simplify keeping score as the game is played. Each element in game contains a space ' ' if the position has yet to be played, an 'X', if the position contains an X, and an 'O' if the position contains an O.
2. Graphical User-interface Fields
In addition to the JLabels that make up the array named grid, the TicTacToe application contains the following user-interface elements. Define these elements after you've finished defining your arrays:
A JButton object named restart. The user can restart the game by clicking this Button.
A JPanel named p. Use the default constructor to create p; it will hold the JLabels in grid
A JLabel named status. This will keep the user informed of the game's progress. You might want to initialize status to a helpful welcome message.
3. Primitive Fields
Your program will contain the following primitive fields which you'll use as you play the game:
An int named numClicks that will keep track of how many X's and O's are displayed.
A boolean named isDone which is used to determine when the game is finished. Initialize isDoneto false.
A boolean named isXTurn which is used to determine whose turn it is to click. Initialize isXTurn to true--we'll assume that X always goes first.
Once you've defined these fields, make sure your program contains no errors. If it does, then you've made a mistake defining the fields; go back and double-check your work until the errors have disappeared.
Write the constructor. There are four tasks to complete in this step. After you've finished writing the constructor, check one last time for errors before going on. When you finish this step, you should be able to run your application and see that its appearance is satisfactory.
1. Set the Layout
Your application will use BorderLayout for the application itself, even though the JPanel that contains the game's labels will use a GridLayout. Since the BorderLayout is the default layout for swing you will not have to set the layout on the content pane.
2. Add the Status Label
Add the JLabel named status to the top of your application. When you do so, also change the JLabel's appearance like this:
Swing components by default are transparent so they take on the background color of the container they are added to. Because of this, you must send your status JLabel the setOpaquemessage passing a parameter of true
Set the JLabel background to yellow, the foreground to blue
Set the JLabel font to a nice 12pt bold Helvetica
3. Initialize the main Panel
You want to display the JLabel objects in the grid array using a 3 x 3 grid on the screen. Fortunately, Java's GridLayout is just what you need. Before you add the JLabel objects to your JPanel, however, there are a few things you need to do to prepare your main JPanel.
Use the setLayout() method to change the JPanel object p so that it uses a GridLayout. Leave three pixels between cells in the grid.
Change the JPanel's background color to black. (This adds the lines between JLabels.)
Add the JPanel to the center of the content pane.
4. Initialize the grid
In Step 1, you created a 3 x 3 array of JLabel references named grid. Each of the elements in grid, however, is not yet a JLabel; instead grid is populated with 9 null JLabel references. To fix that, you need to use a pair of nested for loops to create 9 JLabel objects and place them into your array.
Here's what you do. Write a pair of nested for loops. Use row for the outer loop index and have it go from 0 to 2. Use col for the inner loop index and have it go from 0 to 2. Inside the inner loop, do the following:
Create a JLabel object using new, and place it in the corresponding element in the array. (grid[row][col]).
Attach a MouseListener to the JLabel object using addMouseListener(this). Note that this is different than using MouseMotionListener.
Send the JLabel the setOpaque message passing it a parameter of true
Set the background of the JLabel to white
Change the font used by the JLabel to a 32 point, bold Helvetica
Add the JLabel to the JPanel named p.
While you are still in the inner loop, place a space in the current element of the char array named game. Because both grid and game have the same number of dimensions, you can use the [row][col] indexes on game as well as grid.
At this point, your constructor is finished. Make sure you do not have any errors. You should at this point be able to run your application and see the basic outline of what the TicTacToe game is going to look like.
Handle the mouse clicks. The code to handle mouse clicks is placed in a method named mouseClicked(). You could have placed the code in the methods mousePressed() or mouseReleased()as well. Under Java 1.0 you could have used the mouseDown() or mouseUp() methods.
This is a fairly complex method and is somewhat difficult to explain clearly. For this reason the mouseClicked code is being given to you:
Create the gameOver method. In this method you are going to first check the horizontals then check the rows and columns using a for loop. When you are doing your checking think about the decision statements you are using. Should you have a bunch of if statements or should they be if else statements. Here are the steps to complete the method:
Create a local char variable called winner. Initialize it with a space character.
TTo check the first diagonal you will determine if the character at game[0][0] is equal to the character at game[1][1] and game[2][2]. If they are equal set winner equal to game[0][0].
Checking the second diagonal is very similar to the first. You simply need to go the other direction. That is, check to see if game[2][0] is equal to game[1][1] and game[0][2]. If they are then set winner equal to game[2][0].
If a winner hasn't been determined in the diagonal spaces you next need to check the rows. You will need a for loop that runs from 0 to 3. So that we are on the same page call your loop counter strong>row.
Within the for loop you are going to check both the rows and columns. To check the rows you should check that game[row][0] is not equal to an empty space and that game[row][0] is equal to game[row][1] and game[row][2]. If this is true set winner equal to game[row][0].
Checking the columns is similar to checking the rows. The difference is that you are going to put row as the second index. So, you need to check that game[0][row] is not equal to a space character and game[0][row] is equal to game[1][row] and game[2][row]. If this is true then set winner equal to game[0][row]
Once the loop exits you have determined the outcome. Now you simply need to report it. Set the field variable called isDone to true
Check for a tie. This is determined by checking to see if winner is equal to the space character and the field variable numClicks is equal to 9. If this is true set the text on the JLabel called status to a tie game.
If it is not a tie game then check for a winner. If winner is not equal to the space character then set the text of the JLabel called status to "Game Over:" + winner + " Won!!!"
If it is not a tie game or no winner then the game needs to continue. Set status to either "X's Turn" or "O's Turn" by determining the value of the variable isXTurn. Also you need to set isDone back to false.
Write the resetGame() method. This method is called to "clear out" all of the Labels whenever a game is finished, or when the user presses the "Reset" button. Here's all you need to write:
Write a nested for loop. Use row and col for your indexes.
For each element in the Label array named grid, set the text to a single blank space using the setText() method. [Make sure you don't set it to more than one space or to the empty Stringaccidentally.]
Inside the same nested loop, set each element in the char array named game to a single space as well. Here you'll have to use a char literal like this ' ', while in the previous step you need to use a space contained inside a String like this " ".
Set the field named numClicks to zero.
Set the field named isXTurn to true.
That's it. Test it out, and you're finished.
Lab Assignment 17 - Working with Object Arrays
Note About AppletsIn the old days we would do these projects as applets. Unfortunately, applets are not as secure as Sun / Oracle once thought they were. Now, it is almost impossible to run an applet over the web. If you want to see how the Tic-Tac-Toe game looks you will have to view this video
Purpose The Sun Java Development Kit (JDK) comes with a sample program that plays TicTacToe. The JDK program includes sounds and comes with cool graphics. It can be a little slow, however, and the code is not the easiest to understand.In this homework, you'll build your own version of TicTacToe using JLabels, GridLayout, and a couple arrays. Before you get started, however, why don't you take a minute to play a game?
To complete the homework you'll have to understand how to:Declare a two-dimensional array of primitive values
Declare a two-dimensional array of object references
Initialize each of the elements in a two-dimensional array of object references
Use a pair of nested for loops to process the elements in a two-dimensional array
Step-By-Step Instructions Step 1Create a class called TicTacToe. Place it in a file called TicTacToe.java
Have your class extend from JFrame
Have your class implement ActionListener and MouseListener.
Create all of the methods needed for the ActionListener and MouseListener interfaces.
Make sure to import javax.swing.*, java.awt.* and java.awt.event.*
Step 2Before ddefining your attributes you need to create a container called content and initialize it by sending the getContentPane() message to this.
Define your application's attributes. The TicTacToe program has three different kinds of fields that you must define before you can compile the program successfully. Make sure you define your fields and check for errors before you attempt to go further.
Here are the three kinds of fields:
1. Program Arrays
The TicTacToe program has two "parallel", 3 x 3, two dimensional arrays. Start your programming by defining these two arrays:
The first of these is an array of JLabel objects. This array, named grid, is used to display the actual Xs and Os on your screen. Each JLabel will display an X, and O, or a blank.
The second array is an array of char primitives. This array, named game, is used to simplify keeping score as the game is played. Each element in game contains a space ' ' if the position has yet to be played, an 'X', if the position contains an X, and an 'O' if the position contains an O.
2. Graphical User-interface Fields
In addition to the JLabels that make up the array named grid, the TicTacToe application contains the following user-interface elements. Define these elements after you've finished defining your arrays:
A JButton object named restart. The user can restart the game by clicking this Button.
A JPanel named p. Use the default constructor to create p; it will hold the JLabels in grid
A JLabel named status. This will keep the user informed of the game's progress. You might want to initialize status to a helpful welcome message.
3. Primitive Fields
Your program will contain the following primitive fields which you'll use as you play the game:
An int named numClicks that will keep track of how many X's and O's are displayed.
A boolean named isDone which is used to determine when the game is finished. Initialize isDoneto false.
A boolean named isXTurn which is used to determine whose turn it is to click. Initialize isXTurn to true--we'll assume that X always goes first.
Once you've defined these fields, make sure your program contains no errors. If it does, then you've made a mistake defining the fields; go back and double-check your work until the errors have disappeared.
Step 2Write the constructor. There are four tasks to complete in this step. After you've finished writing the constructor, check one last time for errors before going on. When you finish this step, you should be able to run your application and see that its appearance is satisfactory.
1. Set the Layout
Your application will use BorderLayout for the application itself, even though the JPanel that contains the game's labels will use a GridLayout. Since the BorderLayout is the default layout for swing you will not have to set the layout on the content pane.
2. Add the Status Label
Add the JLabel named status to the top of your application. When you do so, also change the JLabel's appearance like this:
Swing components by default are transparent so they take on the background color of the container they are added to. Because of this, you must send your status JLabel the setOpaquemessage passing a parameter of true
Set the JLabel background to yellow, the foreground to blue
Set the JLabel font to a nice 12pt bold Helvetica
3. Initialize the main Panel
You want to display the JLabel objects in the grid array using a 3 x 3 grid on the screen. Fortunately, Java's GridLayout is just what you need. Before you add the JLabel objects to your JPanel, however, there are a few things you need to do to prepare your main JPanel.
Use the setLayout() method to change the JPanel object p so that it uses a GridLayout. Leave three pixels between cells in the grid.
Change the JPanel's background color to black. (This adds the lines between JLabels.)
Add the JPanel to the center of the content pane.
4. Initialize the grid
In Step 1, you created a 3 x 3 array of JLabel references named grid. Each of the elements in grid, however, is not yet a JLabel; instead grid is populated with 9 null JLabel references. To fix that, you need to use a pair of nested for loops to create 9 JLabel objects and place them into your array.
Here's what you do. Write a pair of nested for loops. Use row for the outer loop index and have it go from 0 to 2. Use col for the inner loop index and have it go from 0 to 2. Inside the inner loop, do the following:
Create a JLabel object using new, and place it in the corresponding element in the array. (grid[row][col]).
Attach a MouseListener to the JLabel object using addMouseListener(this). Note that this is different than using MouseMotionListener.
Send the JLabel the setOpaque message passing it a parameter of true
Set the background of the JLabel to white
Change the font used by the JLabel to a 32 point, bold Helvetica
Add the JLabel to the JPanel named p.
While you are still in the inner loop, place a space in the current element of the char array named game. Because both grid and game have the same number of dimensions, you can use the [row][col] indexes on game as well as grid.
At this point, your constructor is finished. Make sure you do not have any errors. You should at this point be able to run your application and see the basic outline of what the TicTacToe game is going to look like.
Step 3Handle the mouse clicks. The code to handle mouse clicks is placed in a method named mouseClicked(). You could have placed the code in the methods mousePressed() or mouseReleased()as well. Under Java 1.0 you could have used the mouseDown() or mouseUp() methods.
This is a fairly complex method and is somewhat difficult to explain clearly. For this reason the mouseClicked code is being given to you:
Step 4
Create the gameOver method. In this method you are going to first check the horizontals then check the rows and columns using a for loop. When you are doing your checking think about the decision statements you are using. Should you have a bunch of if statements or should they be if else statements. Here are the steps to complete the method:
Create a local char variable called winner. Initialize it with a space character.
TTo check the first diagonal you will determine if the character at game[0][0] is equal to the character at game[1][1] and game[2][2]. If they are equal set winner equal to game[0][0].
Checking the second diagonal is very similar to the first. You simply need to go the other direction. That is, check to see if game[2][0] is equal to game[1][1] and game[0][2]. If they are then set winner equal to game[2][0].
If a winner hasn't been determined in the diagonal spaces you next need to check the rows. You will need a for loop that runs from 0 to 3. So that we are on the same page call your loop counter strong>row.
Within the for loop you are going to check both the rows and columns. To check the rows you should check that game[row][0] is not equal to an empty space and that game[row][0] is equal to game[row][1] and game[row][2]. If this is true set winner equal to game[row][0].
Checking the columns is similar to checking the rows. The difference is that you are going to put row as the second index. So, you need to check that game[0][row] is not equal to a space character and game[0][row] is equal to game[1][row] and game[2][row]. If this is true then set winner equal to game[0][row]
Once the loop exits you have determined the outcome. Now you simply need to report it. Set the field variable called isDone to true
Check for a tie. This is determined by checking to see if winner is equal to the space character and the field variable numClicks is equal to 9. If this is true set the text on the JLabel called status to a tie game.
If it is not a tie game then check for a winner. If winner is not equal to the space character then set the text of the JLabel called status to "Game Over:" + winner + " Won!!!"
If it is not a tie game or no winner then the game needs to continue. Set status to either "X's Turn" or "O's Turn" by determining the value of the variable isXTurn. Also you need to set isDone back to false.
Step 5Write the resetGame() method. This method is called to "clear out" all of the Labels whenever a game is finished, or when the user presses the "Reset" button. Here's all you need to write:
Write a nested for loop. Use row and col for your indexes.
For each element in the Label array named grid, set the text to a single blank space using the setText() method. [Make sure you don't set it to more than one space or to the empty Stringaccidentally.]
Inside the same nested loop, set each element in the char array named game to a single space as well. Here you'll have to use a char literal like this ' ', while in the previous step you need to use a space contained inside a String like this " ".
Set the field named numClicks to zero.
Set the field named isXTurn to true.
That's it. Test it out, and you're finished.
Explanation / Answer
Answer:
import java.util.*;
public class TicTacToeGame
{
private int counter;
private char location[]=new char[10];
private char player;
public static void main(String args[])
{
String ch;
TicTacToeGame Toe=new TicTacToeGame();
do{
Toe.beginBoard();
Toe.play_game();
System.out.println ("Press Y to play the game again ");
Scanner in =new Scanner(System.in);
ch=in.nextLine();
System.out.println("ch value is "+ch);
}while (ch.equals("Y"));
}
public void beginBoard()
{
char locationdef[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9'};
int i;
counter = 0;
player = 'X';
for (i=1; i<10; i++) location[i]=locationdef[i];
presentBoard();
}
public String presentBoard()
{
System.out.println( " " );
System.out.println( " " );
System.out.println( " " + location [1] + " | " +location [2]+ " | " +location [3]);
System.out.println( " | | " );
System.out.println( " ___|____|___ " );
System.out.println( " " +location [4]+ " | " +location [5]+ " | " +location [6]);
System.out.println( " | | " );
System.out.println( " ___|____|___ " );
System.out.println( " " +location [7]+ " | " +location [8]+ " | " +location [9]);
System.out.println( " | | " );
System.out.println( " | | " );
System.out.println( " " );
return "presentBoard";
}
public void play_game()
{
int spot;
char blank = ' ';
System.out.println( "Player " + getPlayer() +" will go first and be the letter 'X'" );
do {
presentBoard();
System.out.println( " Player " + getPlayer() +" choose a location." );
boolean posTaken = true;
while (posTaken) {
Scanner in =new Scanner (System.in);
spot=in.nextInt();
posTaken = checklocation(spot);
if(posTaken==false)
location[spot]=getPlayer();
}
System.out.println( "Nice move." );
presentBoard();
nextPlayer();
}while ( getWinner() == blank );
}
public char getWinner()
{
char Winner = ' ';
if (location[1] == 'X' && location[2] == 'X' && location[3] == 'X') Winner = 'X';
if (location[4] == 'X' && location[5] == 'X' && location[6] == 'X') Winner = 'X';
if (location[7] == 'X' && location[8] == 'X' && location[9] == 'X') Winner = 'X';
if (location[1] == 'X' && location[4] == 'X' && location[7] == 'X') Winner = 'X';
if (location[2] == 'X' && location[5] == 'X' && location[8] == 'X') Winner = 'X';
if (location[3] == 'X' && location[6] == 'X' && location[9] == 'X') Winner = 'X';
if (location[1] == 'X' && location[5] == 'X' && location[9] == 'X') Winner = 'X';
if (location[3] == 'X' && location[5] == 'X' && location[7] == 'X') Winner = 'X';
if (Winner == 'X' )
{System.out.println("Player1 wins the game." );
return Winner;
}
if (location[1] == 'O' && location[2] == 'O' && location[3] == 'O') Winner = 'O';
if (location[4] == 'O' && location[5] == 'O' && location[6] == 'O') Winner = 'O';
if (location[7] == 'O' && location[8] == 'O' && location[9] == 'O') Winner = 'O';
if (location[1] == 'O' && location[4] == 'O' && location[7] == 'O') Winner = 'O';
if (location[2] == 'O' && location[5] == 'O' && location[8] == 'O') Winner = 'O';
if (location[3] == 'O' && location[6] == 'O' && location[9] == 'O') Winner = 'O';
if (location[1] == 'O' && location[5] == 'O' && location[9] == 'O') Winner = 'O';
if (location[3] == 'O' && location[5] == 'O' && location[7] == 'O') Winner = 'O';
if (Winner == 'O' )
{
System.out.println( "Player2 wins the game." );
return Winner; }
for(int i=1;i<10;i++)
{
if(location[i]=='X' || location[i]=='O')
{
if(i==9)
{
char Draw='D';
System.out.println(" Game is stalemate ");
return Draw;
}
continue;
}
else
break;
}
return Winner;
}
public boolean checklocation(int spot)
{
if (location[spot] == 'X' || location[spot] == 'O')
{
System.out.println("That location is already taken, please choose another");
return true;
}
else {
return false;
}
}
public void nextPlayer()
{
if (player == 'X')
player = 'O';
else player = 'X';
}
public String getTitle()
{
return "Tic Tac Toe" ;
}
public char getPlayer()
{
return player;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.