Question

In: Computer Science

            It is not uncommon to develop the logic of a program as a console application...


            It is not uncommon to develop the logic of a program as a console application (NO GUI) and then graft a GUI on to it later. There are also many reasons for separating the GUI of the program from the rest of the code logic. (This is part of a common design pattern called Model View Controller (MVC) where the GUI represents the View aspect.) For instance, you might have a Web-based or mobile device GUI in addition to a Desktop Application one…

            So for this lab, I want you to recode the 2-player Tic Tac Toe game (as we did in CP I) previous lab to use a Java Swing GUI. You can use the same internal data representation (board) and much of the code from the previous version. If you were not with me for CP I, you can get a copy of the Tic Tac Toe console program code from Bb.

The computer does not play the game but facilitates two human players enforcing the rules for the game and determining ties and wins. It should prompt the user to play again when a game ends.

           

  1. Create a java Swing GUI application in a new Netbeans project called TicTacToeGUI. Your project will have a TicTacToeFrame.java class and a java main class: TicTacToeRunner.java.
  2. The game is the same in every respect to the previous lab from CP I (where we refactored Tic Tac Toe console code from the text) except that there is now a GUI to handle the display of the game state and the input from the user. Starting with X each player alternates making a move by clicking on a square. The game blocks until a legal move is entered and then switches to receive input from the other player. The game should check for wins after each move starting with the 5th and should check for a tie (7th move).
  3. Use JOptionPane to msg the user as needed for illegal moves and when the game is won or tied, or the user quits. Do not use any console (System.out.print…) output as this is a GUI program.
  4. Use grid layout to create a 3 X 3 matrix of JButton objects for the Tic Tac Toe board.   Provide a quit button as well. Hint: use an Array of JButton objects for the squares. IF you do this in a clever way as a 2D array, it will interface nicely with your previous code for the game. I suggest that you sub-class the JButton to create a TicTacToeButton class that holds the state of the button.
  5. You also want to create a single listener instance for all the Buttons on the board. It should determine the row col position of the Button and interface with the code for the game logic.
  6. Provide many screen shots that establish that your game works correctly:
  • Win dialog
  • Tie dialogs (Full board tie and the not full board tie)
  • Looping until user enters a valid move
  • Prompt to play another game.
      
  1. Package your entire Netbeans folder into an archive called LastnameFirstname _Ass01.zip (using your actual name instead of LastnameFirstname) and submit your file using the Bb assignments mechanism.

Solutions

Expert Solution

Working code implemented in Java and appropriate comments provided for better understanding.

Here I am attaching code for all files:

  • TicTacToeRunner.java
  • TicTacToeFrame.java

TicTacToeRunner.java:


public class TicTacToeRunner {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
  
TicTacToeFrame frame = new TicTacToeFrame();
  
  
}
  
}

TicTacToeFrame.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;

public class TicTacToeFrame implements ActionListener {
  
private JFrame game = new JFrame("Tic Tac Toe");
  
private JPanel board;
private JPanel buttonPnl;

private JButton button1 = new JButton("");
private JButton button2 = new JButton("");
private JButton button3 = new JButton("");
private JButton button4 = new JButton("");
private JButton button5 = new JButton("");
private JButton button6 = new JButton("");
private JButton button7 = new JButton("");
private JButton button8 = new JButton("");
private JButton button9 = new JButton("");
private JButton quitBtn = new JButton("Quit");
private JButton resetBtn = new JButton("Reset");
private JButton scoreBtn = new JButton("Score");
private String letter = "";
private int count = 0;
private int XWins, OWins = 0;
private boolean win = false;

public TicTacToeFrame()
{
//create panel for the board(the buttons)
board = new JPanel();
board.setLayout(new GridLayout(3, 3));
  
//Buttons
board.add(button1);
board.add(button2);
board.add(button3);
board.add(button4);
board.add(button5);
board.add(button6);
board.add(button7);
board.add(button8);
board.add(button9);

button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
button7.addActionListener(this);
button8.addActionListener(this);
button9.addActionListener(this);

//create game the frame the jpanels to it
createButtonPnl();
game.setLayout(new BorderLayout());
game.add(board, BorderLayout.CENTER);
game.add(buttonPnl, BorderLayout.SOUTH);
game.setSize(400, 400);
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setLocation(500, 300);
game.setVisible(true);
}
  
@Override
public void actionPerformed(ActionEvent z)
{
count++;
if (count == 1 || count == 3 || count == 5 || count == 7 || count == 9)
{
letter = "X";
}
else if (count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "O";
}
//Displaying an X or O on the buttons
if (z.getSource() == button1)
{
button1.setText(letter);
button1.setEnabled(false);
CheckForWin();
}
else if (z.getSource() == button2)
{
button2.setText(letter);
button2.setEnabled(false);
CheckForWin();
}
else if (z.getSource() == button3)
{
button3.setText(letter);
button3.setEnabled(false);
CheckForWin();
}
else if (z.getSource() == button4)
{
button4.setText(letter);
button4.setEnabled(false);
CheckForWin();
}
else if (z.getSource() == button5)
{
button5.setText(letter);
button5.setEnabled(false);
CheckForWin();
}
else if (z.getSource() == button6)
{
button6.setText(letter);
button6.setEnabled(false);
CheckForWin();
}
else if (z.getSource() == button7)
{
button7.setText(letter);
button7.setEnabled(false);
CheckForWin();
}
else if (z.getSource() == button8)
{
button8.setText(letter);
button8.setEnabled(false);
CheckForWin();
}
else if (z.getSource() == button9)
{
button9.setText(letter);
button9.setEnabled(false);
CheckForWin();
}
  
}

public void CheckForWin()
{      
   //looking who wins horizontally
   if (button1.getText() == button2.getText() && button2.getText() == button3.getText() && button1.getText() != "")
   {
   win = true;
   Win();
   }
   else if (button4.getText() == button5.getText() && button5.getText() == button6.getText() && button4.getText() != "")
   {
   win = true;
   Win();
   }
   else if (button7.getText() == button8.getText() && button8.getText() == button9.getText() && button7.getText() != "")
   {
   win = true;
   Win();
   }
   //looking for who wins vertically
   else if (button1.getText() == button4.getText() && button4.getText() == button7.getText() && button1.getText() != "")
   {
   win = true;
   Win();
   }
   else if (button2.getText() == button5.getText() && button5.getText() == button8.getText() && button2.getText() != "")
   {
   win = true;
   Win();
   }
   else if (button3.getText() == button6.getText() && button6.getText() == button9.getText() && button3.getText() != "")
   {
   win = true;
   Win();
   }
   //looking for who wins diagonally
   else if (button1.getText() == button5.getText() && button5.getText() == button9.getText() && button1.getText() != "")
   {
   win = true;
   Win();
   }
   else if (button3.getText() == button5.getText() && button5.getText() == button7.getText() && button3.getText() != "")
   {
   win = true;
   Win();
   }
   else
   {
   win = false;
   Win();
   }
}

public void Win()
{
if (win == true)
{
JOptionPane.showMessageDialog(null, "Player " + letter + " Won!");
if(letter.equalsIgnoreCase("X"))
{
   XWins++;
}
else
{
   OWins++;
}   
}
else if (count == 9 && win == false)
{
JOptionPane.showMessageDialog(null, "It's a Tie!");
}
}
  
public void reset()
{
button1.setText("");
button1.setEnabled(true);
button2.setText("");
button2.setEnabled(true);
button3.setText("");
button3.setEnabled(true);
button4.setText("");
button4.setEnabled(true);
button5.setText("");
button5.setEnabled(true);
button6.setText("");
button6.setEnabled(true);
button7.setText("");
button7.setEnabled(true);
button8.setText("");
button8.setEnabled(true);
button9.setText("");
button9.setEnabled(true);
win = false;
count = 0;
}

public void createButtonPnl()
{
buttonPnl = new JPanel();
buttonPnl.setLayout(new GridLayout(1,3));
  
buttonPnl.add(resetBtn);
resetBtn.addActionListener((ActionEvent ae) -> {
int reply = JOptionPane.showConfirmDialog(null, "Reset game?", "Confirm", JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION)
{
reset();
count = 0;
}
});

buttonPnl.add(scoreBtn);
scoreBtn.addActionListener((ActionEvent ae) -> {
JOptionPane.showMessageDialog(null, "Player X's number of Wins" + " " + XWins + " \nPlayer O's number of Wins" + " " + OWins);
});

buttonPnl.add(quitBtn);
quitBtn.addActionListener((ActionEvent ae) -> {
int reply = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Exiting Tic Tac Toe", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
System.exit(0);
}
});
  
}

}

Sample Output Screenshots:


Related Solutions

In this program you will develop an application that will display an amortization schedule.
Using Anaconda Python, program the following:OverviewIn this program you will develop an application that will display an amortization schedule. The word "amortize" means to "To write off gradually and systematically a given amount of money within a specific number of time periods." It will show, for each month of the loan, how much of your monthly loan payment is being applied towards interest costs, and how much is actually being applied to reduce the outstanding balance (principal) of your loan.The...
Language: C# Create a new Console Application. Your Application should ask the user to enter their...
Language: C# Create a new Console Application. Your Application should ask the user to enter their name and their salary. Your application should calculate how much they have to pay in taxes each year and output each amount as well as their net salary (the amount they bring home after taxes are paid!). The only taxes that we will consider for this Application are Federal and FICA. Your Application needs to validate all numeric input that is entered to make...
What factors should you consider when choosing between a console application and a GUI application?
What factors should you consider when choosing between a console application and a GUI application?
Write a console application called PlayingCards that has 4 classes: PlayingCards, Deck, Cards, Card. This application...
Write a console application called PlayingCards that has 4 classes: PlayingCards, Deck, Cards, Card. This application will be able to create a deck of cards, shuffle it, sort it and print it. Use the following class diagrams to code your application. Use the following code for the PlayingCards class public class PlayingCards{ public static void main(String[] args){                 System.out.println("Playings Cards");                 Deck deck = new Deck();                 deck.create();                 System.out.println("Sorted cards");                 deck.sort();                 deck.showCards();                 System.out.println("Shuffled cards");                 deck.shuffle();...
Write a Java console application that reads a string for a date in the U.S. format...
Write a Java console application that reads a string for a date in the U.S. format MM/DD/YYYY and displays it in the European format DD.MM.YYYY  For example, if the input is 02/08/2017, your program should output 08.02.2017
Write a console application to total a set of numbers indicated and provided by a user,...
Write a console application to total a set of numbers indicated and provided by a user, using a while loop or a do…while loop according to the user’s menu choice as follows: C++programming Menu 1. To total numbers using a while loop 2. To total numbers using a do...while loop Enter your menu choice: 1 How many numbers do you want to add: 2 Enter a value for number 1: 4 Enter a value for number 2: 5 The total...
C# Create a console application that prompts the user to enter a regular expression, and then...
C# Create a console application that prompts the user to enter a regular expression, and then prompts the user to enter some input and compare the two for a match until the user presses Esc: The default regular expression checks for at least one digit. Enter a regular expression (or press ENTER to use the default): ^[a- z]+$ Enter some input: apples apples matches ^[a-z]+$? True Press ESC to end or any key to try again. Enter a regular expression...
with C# create a console application project that outputs the number of bytes in memory that...
with C# create a console application project that outputs the number of bytes in memory that each of the following number types use, and the minimum and maximum values they can have: sbyte, byte, short, ushort, int, uint, long, ulong, float, double, and decimal. Try formatting the values into a nice-looking table! More Information: You can always read the documentation, available at https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting for Composite Formatting to learn how to align text in a console application. Your output should look...
1. Design and develop a fuzzy logic system for DC motor speed control a) Develop the...
1. Design and develop a fuzzy logic system for DC motor speed control a) Develop the input membership function based on error and change in error as inputs b) Formulate the rules for the fuzzy based DC motor speed control. c) Develop and test the fuzzy system using both Mamdani and Sugeno Methods.
Create the logic for an application that instantiates an object of the ATM class. Prompt the...
Create the logic for an application that instantiates an object of the ATM class. Prompt the user for the ATM object data to display the user’s bank balance PROGRAMMING LOGIC AND DESIGN QUESTION JAVA LANGUAGE
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT