Question

***Java Project***

Please upload the entire code and attach the screenshots of the code. The screenshots help me to write the code, so please attach that. Thank you so much. If you could use the comment to explain the code, it would be perfect! Thank you so much~

Design and code a Swing GUl for a two-player tic-tac-toe (noughts and crosses) game on a 3 x 3 game board. The JFrame should

1 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;

/**
* The GUI for 2-player Tic Tac Toe game. The frame is a BorderLayout with
* a Menu with 2 Menu items: New Game and Exit
* the game statistics in the upper panel
* the GridLayout at the center to arrange the 9 buttons
* JLabel at the bottom to describe the game status: New Game, Game in progress and turn for the player, Win/Loss/Tie
*/
public class TicTacToeGUI {
  
private final JFrame mainFrame;
private final JPanel scorePanel, buttonPanel, statusPanel;
private final JLabel statusLabel;
private final JButton[][] board;
private final JTextField player1ScoreField, player2ScoreField, drawsField;
private final JLabel player1Label, player2Label, drawsLabel;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem newGameMenuItem;
private JMenuItem exitMenuItem;
  
private String currentPlayer;
private boolean hasWinner;
private int player1Score, player2Score, drawsScore, buttonClicked;
  
public static void main(String[] args)
{
TicTacToeGUI ticTacToeGUI = new TicTacToeGUI();
}
  
public TicTacToeGUI()
{
mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
  
// panel to contain the player score statistics
scorePanel = new JPanel(new FlowLayout(0, 15, 5));
  
player1Label = new JLabel("Player 1: ");
player1ScoreField = new JTextField(10);
player1ScoreField.setHorizontalAlignment(SwingConstants.CENTER);
player1ScoreField.setEditable(false);
  
player2ScoreField = new JTextField(10);
player2ScoreField.setEditable(false);
player2ScoreField.setHorizontalAlignment(SwingConstants.CENTER);
player2Label = new JLabel("Player 2: ");
  
drawsField = new JTextField(10);
drawsField.setHorizontalAlignment(SwingConstants.CENTER);
drawsField.setEditable(false);
drawsLabel = new JLabel("Draws: ");
  
scorePanel.add(player1Label);
scorePanel.add(player1ScoreField);
scorePanel.add(player2Label);
scorePanel.add(player2ScoreField);
scorePanel.add(drawsLabel);
scorePanel.add(drawsField);
  
// panel to contain the buttons
buttonPanel = new JPanel(new GridLayout(3, 3));
  
statusPanel = new JPanel();
statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
  
// game status label
statusLabel = new JLabel("New Game");
statusLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 18));
statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
statusPanel.add(statusLabel);
  
board = new JButton[3][3];
currentPlayer = "X";
player1Score = 0;
player2Score = 0;
drawsScore = 0;
buttonClicked = 0;
hasWinner = false;
  
initGameBoard();
initMenuBar();
  
mainFrame.add(scorePanel, BorderLayout.NORTH);
mainFrame.add(buttonPanel, BorderLayout.CENTER);
mainFrame.add(statusPanel, BorderLayout.SOUTH);
  
mainFrame.setSize(600, 500);
mainFrame.setTitle("Tic Tac Toe");
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
  
private void initGameBoard()
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
JButton btn = new JButton();
btn.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 50));
board[i][j] = btn;
  
// set action listener for the buttons
btn.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
if(((JButton)e.getSource()).getText().equals("") && hasWinner == false)
{
btn.setText(currentPlayer);
buttonClicked++;
checkWinner();
togglePlayer();
}
}
});
  
buttonPanel.add(btn);
}
}
}
  
private void initMenuBar()
{
menuBar = new JMenuBar();
menu = new JMenu("Game");
newGameMenuItem = new JMenuItem("New Game");
newGameMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetGameBoard();
statusLabel.setText("New Game");
player1Score = player2Score = drawsScore = 0;
player1ScoreField.setText("");
player2ScoreField.setText("");
drawsField.setText("");
}
});
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(newGameMenuItem);
menu.add(exitMenuItem);
menuBar.add(menu);
mainFrame.setJMenuBar(menuBar);
}
  
private void resetGameBoard()
{
togglePlayer();
buttonClicked = 0;
hasWinner = false;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
board[i][j].setText("");
}
}
}
  
private void togglePlayer()
{
if(currentPlayer.equals("X"))
{
currentPlayer = "O";
statusLabel.setText("Game in progress: Player " + currentPlayer + "'s turn...");
}
else
{
currentPlayer = "X";
statusLabel.setText("Game in progress: Player " + currentPlayer + "'s turn...");
}
}
  
private void checkWinner()
{
// 1st column
if(board[0][0].getText().equals(currentPlayer) && board[1][0].getText().equals(currentPlayer) && board[2][0].getText().equals(currentPlayer))
{
JOptionPane.showMessageDialog(null, "Player " + currentPlayer + " is the Winner!");
if(currentPlayer.equals("X"))
player1ScoreField.setText(++player1Score + "");
else
player2ScoreField.setText(++player2Score + "");
statusLabel.setText("Game over! Player " + currentPlayer + " wins!");
hasWinner = true;
resetGameBoard();
}
// 2nd column
else if(board[0][1].getText().equals(currentPlayer) && board[1][1].getText().equals(currentPlayer) && board[2][1].getText().equals(currentPlayer))
{
JOptionPane.showMessageDialog(null, "Player " + currentPlayer + " is the Winner!");
if(currentPlayer.equals("X"))
player1ScoreField.setText(++player1Score + "");
else
player2ScoreField.setText(++player2Score + "");
  
statusLabel.setText("Game over! Player " + currentPlayer + " wins!");
hasWinner = true;
resetGameBoard();
}
// 3rd column
else if(board[0][2].getText().equals(currentPlayer) && board[1][2].getText().equals(currentPlayer) && board[2][2].getText().equals(currentPlayer))
{
JOptionPane.showMessageDialog(null, "Player " + currentPlayer + " is the Winner!");
if(currentPlayer.equals("X"))
player1ScoreField.setText(++player1Score + "");
else
player2ScoreField.setText(++player2Score + "");
  
statusLabel.setText("Game over! Player " + currentPlayer + " wins!");
hasWinner = true;
resetGameBoard();
}
  
// 1st row
else if(board[0][0].getText().equals(currentPlayer) && board[0][1].getText().equals(currentPlayer) && board[0][2].getText().equals(currentPlayer))
{
JOptionPane.showMessageDialog(null, "Player " + currentPlayer + " is the Winner!");
if(currentPlayer.equals("X"))
player1ScoreField.setText(++player1Score + "");
else
player2ScoreField.setText(++player2Score + "");
  
statusLabel.setText("Game over! Player " + currentPlayer + " wins!");
hasWinner = true;
resetGameBoard();
}
  
// 2nd row
else if(board[1][0].getText().equals(currentPlayer) && board[1][1].getText().equals(currentPlayer) && board[1][2].getText().equals(currentPlayer))
{
JOptionPane.showMessageDialog(null, "Player " + currentPlayer + " is the Winner!");
if(currentPlayer.equals("X"))
player1ScoreField.setText(++player1Score + "");
else
player2ScoreField.setText(++player2Score + "");
  
statusLabel.setText("Game over! Player " + currentPlayer + " wins!");
hasWinner = true;
resetGameBoard();
}
  
// 3rd row
else if(board[2][0].getText().equals(currentPlayer) && board[2][1].getText().equals(currentPlayer) && board[2][2].getText().equals(currentPlayer))
{
JOptionPane.showMessageDialog(null, "Player " + currentPlayer + " is the Winner!");
if(currentPlayer.equals("X"))
player1ScoreField.setText(++player1Score + "");
else
player2ScoreField.setText(++player2Score + "");
  
statusLabel.setText("Game over! Player " + currentPlayer + " wins!");
hasWinner = true;
resetGameBoard();
}
  
// left to right diagonal
else if(board[0][0].getText().equals(currentPlayer) && board[1][1].getText().equals(currentPlayer) && board[2][2].getText().equals(currentPlayer))
{
JOptionPane.showMessageDialog(null, "Player " + currentPlayer + " is the Winner!");
if(currentPlayer.equals("X"))
player1ScoreField.setText(++player1Score + "");
else
player2ScoreField.setText(++player2Score + "");
  
statusLabel.setText("Game over! Player " + currentPlayer + " wins!");
hasWinner = true;
resetGameBoard();
}
  
// right to left diagonal
else if(board[0][2].getText().equals(currentPlayer) && board[1][1].getText().equals(currentPlayer) && board[2][0].getText().equals(currentPlayer))
{
JOptionPane.showMessageDialog(null, "Player " + currentPlayer + " is the Winner!");
if(currentPlayer.equals("X"))
player1ScoreField.setText(++player1Score + "");
else
player2ScoreField.setText(++player2Score + "");
  
statusLabel.setText("Game over! Player " + currentPlayer + " wins!");
hasWinner = true;
resetGameBoard();
}
else
{
// the game is a draw
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(!board[i][j].getText().equals("") && buttonClicked == 9)
{
JOptionPane.showMessageDialog(null, "The match is a draw!");
statusLabel.setText("Game over! The game is a draw.");
drawsField.setText(++drawsScore + "");
hasWinner = false;
resetGameBoard();
}
}
}
}
}
}

****************************************************************** SCREENSHOT *********************************************************

| Tic Tac Toe Game Player 1: Player 2: Draws: New Game

| Tic Tac Toe Game Player 1: Player 2: Draws: Game in progress: Player Xs turn...

Tic Tac Toe Game Player 1: Player 2: Draws: (C Message Player X is the Winner! OK Game in progress: Player Xs turn...

Add a comment
Know the answer?
Add Answer to:
***Java Project*** Please upload the entire code and attach the screenshots of the code. The screenshots help me to write the code, so please attach that. Thank you so much. If you could use the comme...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need screenshots for this solution done in Flowgorithm. Thank you. Tic-Tac-Toe Game Design a program...

    I need screenshots for this solution done in Flowgorithm. Thank you. Tic-Tac-Toe Game Design a program that allows two players to play a game of tic-tac-toe. Use a two- dimensional String array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: a. Displays the contents of the board array. b. Allows player 1 to select a location...

  • Please help me write a Pseudocode (please do NOT answer in JAVA or Python - I...

    Please help me write a Pseudocode (please do NOT answer in JAVA or Python - I will not be able to use those). Please ALSO create a flowchart using Flowgarithm program. Thank you so much, if answer is provided in Pseudocode and Flowchart, I will provide good feedback and thumbs up to the resonder. Thank you! Tic-Tac-Toe Game Write a program that allows two players to play a game of tic-tac-toe. Use a two- dimensional char array with three rows...

  • JAVA TIC TAC TOE - please help me correct my code Write a program that will...

    JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below |    1       |   2        |   3 |    4       |   5        |   6                 |    7      |   8        |   9 The program will assign X to Player 1, and O to Player    The program will ask Player 1, to...

  • JAVAFX PROGRAM Write a program that will allow two users to play a game of tic-tac-toe....

    JAVAFX PROGRAM Write a program that will allow two users to play a game of tic-tac-toe. The game area should consist of nine buttons for the play area, a reset button, and a label that will display the current player's turn. When the program starts, the game area buttons should have no values in them (i.e. they should be blank) When player one clicks on a game area button, the button should get the value X. When player two clicks...

  • Use Java language to create this program Write a program that allows two players to play...

    Use Java language to create this program Write a program that allows two players to play a game of tic-tac-toe. Using a two-dimensional array with three rows and three columns as the game board. Each element of the array should be initialized with a number from 1 - 9 (like below): 1 2 3 4 5 6 7 8 9 The program should run a loop that Displays the contents of the board array allows player 1 to select the...

  • 18. Tic-Tac-Toe Game rite a program that allows two players to play a game of tic-tac-toe. Use di...

    18. Tic-Tac-Toe Game rite a program that allows two players to play a game of tic-tac-toe. Use dimensional char array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: Write . Displays the contents of the board array. . Allows player 1 to select a location on the board for an X. The program should ask the...

  • Java project In a game of tic-tac-toe, two players take turns marking an available cell in...

    Java project In a game of tic-tac-toe, two players take turns marking an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A draw (no winner) occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Create...

  • (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe....

    (Tic-Tac-Toe) Create a class Tic-Tac-Toe that will enable you to write a program to play Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional array. Use an enumeration to represent the value in each cell of the array. The enumeration’s constants should be named X, O and EMPTY (for a position that does not contain an X or an O). The constructor should initialize the board elements to EMPTY. Allow two human players. Wherever the first player moves, place an X...

  • write a program for python 3 write the functions that could be used in an implementation...

    write a program for python 3 write the functions that could be used in an implementation of the game tic-tac-toe. Below are the definitions of the different functions. The code to test each function is currently in the main() of the lab10.py file. • A function to build the board. This method should create a list of the numbers 1 – 9 and return that list. build_board () -> list • A void function to display the board. (see the...

  • Use WebGL to write a program that plays tic-tac-toe. The program should begin by drawing the...

    Use WebGL to write a program that plays tic-tac-toe. The program should begin by drawing the game board (two vertical lines and two horizontal lines). When a player left-clicks on an open space, the program should draw an “X” in that square. When a player right-clicks on an open space, the program should draw an “O” in that square. The Xs must be different colors from the Os. Both of those colors must be different from the lines making the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT