Question

GUI Implementation Implement a tic-tac-toe game via GUI. Your game must have to panels, one display the game board for the user to play and the other is a control panel showing the user with options to pay a new game or quit. At any moment, only one panel is shown taking the entire window/frame. Initially, the game boar shown first, and the control panel is shown only when the user completes a game.

CSII Java plz

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

Hi please find the answer

If you have any query please let me know first by comment i will give solutions

============================

TicTacToe.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class TicTacToe extends JFrame implements ActionListener

{

// setting up ALL the variables

JFrame window = new JFrame("Tic Tac Toe Game");

  

JMenuBar mnuMain = new JMenuBar();

JMenuItem mnuNewGame = new JMenuItem(" New Game"),

mnuGameTitle = new JMenuItem("|Tic Tac Toe| "),

mnuStartingPlayer = new JMenuItem(" Starting Player"),

mnuExit = new JMenuItem(" Quit");

JButton btnEmpty[] = new JButton[10];

  

JPanel pnlNewGame = new JPanel(),

pnlNorth = new JPanel(),

pnlSouth = new JPanel(),

pnlTop = new JPanel(),

pnlBottom = new JPanel(),

pnlPlayingField = new JPanel();

JPanel radioPanel = new JPanel();

  

private JRadioButton SelectX = new JRadioButton("User Plays X", false);

private JRadioButton SelectO = new JRadioButton("User Plays O", false);

private ButtonGroup radioGroup;

private String startingPlayer= "";

final int X = 800, Y = 480, color = 190; // size of the game window

private boolean inGame = false;

private boolean win = false;

private boolean btnEmptyClicked = false;

private boolean setTableEnabled = false;

private String message;

private Font font = new Font("Rufscript", Font.BOLD, 100);

private int remainingMoves = 1;

private int wonNumber1 = 1, wonNumber2 = 1, wonNumber3 = 1;

  

final int winCombo[][] = new int[][] {

{1, 2, 3}, {1, 4, 7}, {1, 5, 9},

{4, 5, 6}, {2, 5, 8}, {3, 5, 7},

{7, 8, 9}, {3, 6, 9}

/*Horizontal Wins*/ /*Vertical Wins*/ /*Diagonal Wins*/

}; //end array

//=============================== GUI ========================================//

public TicTacToe() //This is the constructor

{

//Setting window properties:

window.setSize(X, Y);

window.setLocation(300, 180);

window.setResizable(true);

window.setLayout(new BorderLayout());

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

  

//------------ Sets up Panels and text fields ------------------------//

// setting Panel layouts and properties

pnlNorth.setLayout(new FlowLayout(FlowLayout.CENTER));

pnlSouth.setLayout(new FlowLayout(FlowLayout.CENTER));

  

pnlNorth.setBackground(new Color(70, 70, 70));

pnlSouth.setBackground(new Color(color, color, color));

  

pnlTop.setBackground(new Color(color, color, color));

pnlBottom.setBackground(new Color(color, color, color));

  

pnlTop.setLayout(new FlowLayout(FlowLayout.CENTER));

pnlBottom.setLayout(new FlowLayout(FlowLayout.CENTER));

radioPanel.setBackground(new Color(color, color, color));

pnlBottom.setBackground(new Color(color, color, color));

radioPanel.setBorder(BorderFactory.createTitledBorder(

BorderFactory.createEtchedBorder(), "Who Goes First?"));

  

// adding menu items to menu bar

mnuMain.add(mnuGameTitle);

mnuGameTitle.setEnabled(false);

mnuGameTitle.setFont(new Font("Purisa",Font.BOLD,18));

mnuMain.add(mnuNewGame);

mnuNewGame.setFont(new Font("Purisa",Font.BOLD,18));

mnuMain.add(mnuStartingPlayer);

mnuStartingPlayer.setFont(new Font("Purisa",Font.BOLD,18));

mnuMain.add(mnuExit);

mnuExit.setFont(new Font("Purisa",Font.BOLD,18));//---->Menu Bar Complete

  

// adding X & O options to menu

SelectX.setFont(new Font("Purisa",Font.BOLD,18));

SelectO.setFont(new Font("Purisa",Font.BOLD,18));

radioGroup = new ButtonGroup(); // create ButtonGroup

radioGroup.add(SelectX); // add plain to group

radioGroup.add(SelectO);

radioPanel.add(SelectX);

radioPanel.add(SelectO);

  

// adding Action Listener to all the Buttons and Menu Items

mnuNewGame.addActionListener(this);

mnuExit.addActionListener(this);

mnuStartingPlayer.addActionListener(this);

  

// setting up the playing field

pnlPlayingField.setLayout(new GridLayout(3, 3, 2, 2));

pnlPlayingField.setBackground(Color.black);

for(int x=1; x <= 9; ++x)

{

btnEmpty[x] = new JButton();

btnEmpty[x].setBackground(new Color(220, 220, 220));

btnEmpty[x].addActionListener(this);

pnlPlayingField.add(btnEmpty[x]);

btnEmpty[x].setEnabled(setTableEnabled);

}

// adding everything needed to pnlNorth and pnlSouth

pnlNorth.add(mnuMain);

BusinessLogic.ShowGame(pnlSouth,pnlPlayingField);

  

// adding to window and Showing window

window.add(pnlNorth, BorderLayout.NORTH);

window.add(pnlSouth, BorderLayout.CENTER);

window.setVisible(true);

}// End GUI

// =========== Start Action Performed ===============//

public void actionPerformed(ActionEvent click)  

{

// get the mouse click from the user

Object source = click.getSource();

  

// check if a button was clicked on the gameboard

for(int currentMove=1; currentMove <= 9; ++currentMove)

{

if(source == btnEmpty[currentMove] && remainingMoves < 10)  

{

btnEmptyClicked = true;

BusinessLogic.GetMove(currentMove, remainingMoves, font,

btnEmpty, startingPlayer);   

btnEmpty[currentMove].setEnabled(false);

pnlPlayingField.requestFocus();

++remainingMoves;

}

}

  

// if a button was clicked on the gameboard, check for a winner

if(btnEmptyClicked)

{

inGame = true;

CheckWin();

btnEmptyClicked = false;

}

  

// check if the user clicks on a menu item

if(source == mnuNewGame)   

{

System.out.println(startingPlayer);

BusinessLogic.ClearPanelSouth(pnlSouth,pnlTop,pnlNewGame,

pnlPlayingField,pnlBottom,radioPanel);

if(startingPlayer.equals(""))

{

JOptionPane.showMessageDialog(null, "Please Select a Starting Player",

"Oops..", JOptionPane.ERROR_MESSAGE);

BusinessLogic.ShowGame(pnlSouth,pnlPlayingField);

}

else

{

if(inGame)  

{

int option = JOptionPane.showConfirmDialog(null, "If you start a new game," +

" your current game will be lost..." + "n" +"Are you sure you want to continue?"

, "New Game?" ,JOptionPane.YES_NO_OPTION);

if(option == JOptionPane.YES_OPTION)   

{

inGame = false;

startingPlayer = "";

setTableEnabled = false;

}

else

{

BusinessLogic.ShowGame(pnlSouth,pnlPlayingField);

}

}

// redraw the gameboard to its initial state

if(!inGame)

{

RedrawGameBoard();

}

}

}

// exit button

else if(source == mnuExit)  

{

int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?",

"Quit" ,JOptionPane.YES_NO_OPTION);

if(option == JOptionPane.YES_OPTION)

{

System.exit(0);

}

}

// select X or O player

else if(source == mnuStartingPlayer)  

{

if(inGame)  

{

JOptionPane.showMessageDialog(null, "Cannot select a new Starting "+

"Player at this time.nFinish the current game, or select a New Game "+

"to continue", "Game In Session..", JOptionPane.INFORMATION_MESSAGE);

BusinessLogic.ShowGame(pnlSouth,pnlPlayingField);

}

else

{

setTableEnabled = true;

BusinessLogic.ClearPanelSouth(pnlSouth,pnlTop,pnlNewGame,

pnlPlayingField,pnlBottom,radioPanel);

  

SelectX.addActionListener(new RadioListener());

SelectO.addActionListener(new RadioListener());

radioPanel.setLayout(new GridLayout(2,1));

  

radioPanel.add(SelectX);

radioPanel.add(SelectO);

pnlSouth.setLayout(new GridLayout(2, 1, 2, 1));

pnlSouth.add(radioPanel);

pnlSouth.add(pnlBottom);

}

}

pnlSouth.setVisible(false);

pnlSouth.setVisible(true);  

}// End Action Performed

  

// =========== Start RadioListener ===============//  

private class RadioListener implements ActionListener

{

public void actionPerformed(ActionEvent event)

{

JRadioButton theButton = (JRadioButton)event.getSource();

if(theButton.getText().equals("User Plays X"))

{

startingPlayer = "X";

mnuMain.hide();

}

if(theButton.getText().equals("User Plays O"))

{

startingPlayer = "O";

mnuMain.hide();

}

  

// redisplay the gameboard to the screen

pnlSouth.setVisible(false);

pnlSouth.setVisible(true);   

RedrawGameBoard();

}

}// End RadioListener

/*

----------------------------------

Start of all the other methods. |

----------------------------------

*/

private void RedrawGameBoard()  

{

BusinessLogic.ClearPanelSouth(pnlSouth,pnlTop,pnlNewGame,

pnlPlayingField,pnlBottom,radioPanel);

BusinessLogic.ShowGame(pnlSouth,pnlPlayingField);

  

btnEmpty[wonNumber1].setBackground(new Color(220, 220, 220));

btnEmpty[wonNumber2].setBackground(new Color(220, 220, 220));

btnEmpty[wonNumber3].setBackground(new Color(220, 220, 220));

remainingMoves = 1;

  

for(int x=1; x <= 9; ++x)

{

btnEmpty[x].setText("");

btnEmpty[x].setEnabled(setTableEnabled);

}

  

win = false;   

}

  

private void CheckWin()

{

for(int x=0; x < 8; ++x)   

{

if(!btnEmpty[winCombo[x][0]].getText().equals("") &&

btnEmpty[winCombo[x][0]].getText().equals(btnEmpty[winCombo[x][1]].getText()) &&

btnEmpty[winCombo[x][1]].getText().equals(btnEmpty[winCombo[x][2]].getText())

/*

The way this checks the if someone won is:

First: it checks if the btnEmpty[x] is not equal to an empty string- x being the array number

inside the multi-dementional array winCombo[checks inside each of the 7 sets][the first number]

Secong: it checks if btnEmpty[x] is equal to btnEmpty[y]- x being winCombo[each set][the first number]

y being winCombo[each set the same as x][the second number] (So basically checks if the first and

second number in each set is equal to each other)

Third: it checks if btnEmtpy[y] is eual to btnEmpty[z]- y being the same y as last time and z being

winCombo[each set as y][the third number]

Conclusion: So basically it checks if it is equal to the btnEmpty is equal to each set of numbers

*/

)

{

win = true;

wonNumber1 = winCombo[x][0];

wonNumber2 = winCombo[x][1];

wonNumber3 = winCombo[x][2];

btnEmpty[wonNumber1].setBackground(Color.white);

btnEmpty[wonNumber2].setBackground(Color.white);

btnEmpty[wonNumber3].setBackground(Color.white);

break;

}

}

if(win || (!win && remainingMoves > 9))

{

if(win)

{

if(startingPlayer.equals("X"))

{

if(remainingMoves % 2 == 0)

message = " X has won!";

  

else

message = " O has won!";

  

mnuMain.show();

}

else

{

if(remainingMoves % 2 == 0)

message = " O has won!";

else   

message = " X has won!";

mnuMain.show();

}

JOptionPane.showMessageDialog(null, message, "Congrats!",

JOptionPane.INFORMATION_MESSAGE);

  

}

else if(!win && remainingMoves > 9)

{

message = "Both players have tied!";

JOptionPane.showMessageDialog(null, message, "Tie Game!",

JOptionPane.WARNING_MESSAGE);

  

mnuMain.show();

}

for(int x=1; x <= 9; ++x)

{

btnEmpty[x].setEnabled(false);

}

win = false;

inGame = false;

startingPlayer = "";   

}

}// End of CheckWin

public static void main(String[] args)

{

// start game

new TicTacToe();

}// End of main

}

===============================================

BusinessLogic.java

import javax.swing.*;

import java.awt.*;

public class BusinessLogic

{

public static void GetMove(int currentMove, int remainingMoves, Font font, JButton btnEmpty[],

String startingPlayer)

{// gets the current move "X" or "O" for the user & displays to screen

btnEmpty[currentMove].setFont(font);

if(startingPlayer.equals("X"))

{

if(remainingMoves % 2 != 0)

{

btnEmpty[currentMove].setText("X");

}

else

{

btnEmpty[currentMove].setText("O");

}

}

else

{

if(remainingMoves % 2 != 0)

{

btnEmpty[currentMove].setText("O");

}

else

{

btnEmpty[currentMove].setText("X");

}

}

}// End of GetMove

public static void ShowGame(JPanel pnlSouth, JPanel pnlPlayingField)

{// shows the Playing Field

pnlSouth.setLayout(new BorderLayout());

pnlSouth.add(pnlPlayingField, BorderLayout.CENTER);

pnlPlayingField.requestFocus();

}// End of ShowGame

public static void ClearPanelSouth(JPanel pnlSouth, JPanel pnlTop,

JPanel pnlNewGame, JPanel pnlPlayingField, JPanel pnlBottom, JPanel radioPanel)

{// clears any posible panals on screen

pnlSouth.remove(pnlTop);

pnlSouth.remove(pnlBottom);

pnlSouth.remove(pnlPlayingField);

pnlTop.remove(pnlNewGame);

pnlSouth.remove(radioPanel);

}// End of ClearPanelSouth

}

===========================================

When program start display this screen

=================================

After selecting player the upper menu panel hide

=================================

After game finish both panel display

=================================================

If you have any query please let me know first by comment i will give solutions

Add a comment
Know the answer?
Add Answer to:
CSII Java plz GUI Implementation Implement a tic-tac-toe game via GUI. Your game must have to...
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
  • So I have to make a tic tac toe game in C++. and the problem is...

    So I have to make a tic tac toe game in C++. and the problem is asking me to design, implement and test classea to reperesnt the game board(3x3 sqaure), and the x and o markers. the problem is also asking me to provide suitable observor and mutator methods for modifying the game board and displaying game status. I have to use clases to create a game that prompts for player x and player O to place markers at specified...

  • tic-tac-toe game. Add functionality to the program so when the button is clicked for the AI...

    tic-tac-toe game. Add functionality to the program so when the button is clicked for the AI to take a turn, a heuristic is applied for each of the possible moves, a possible move is selected and the game state and GUI are properly updated. Once complete, the program should be able to play a single game of tic-tac-toe with the user. C#

  • (Game: play a tic-tac-toe game) In a game of tic-tac-toe, two players take turns marking an...

    (Game: play a tic-tac-toe game) In a game of tic-tac-toe, two players take turns marking an available cell in a 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 in the grid have been filled with tokens and neither player has achieved a win. Create...

  • Implement a tic-tac-toe game. At the bottom of these specifications you will see a template you...

    Implement a tic-tac-toe game. At the bottom of these specifications you will see a template you must copy and paste to cloud9. Do not change the provided complete functions, or the function stub headers / return values. Currently, if the variables provided in main are commented out, the program will compile. Complete the specifications for each function. As you develop the program, implement one function at a time, and test that function. The provided comments provide hints as to what...

  • 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...

  • Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game....

    Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game. The objective of this project is to demonstrate your understanding of various programming concepts including Object Oriented Programming (OOP) and design. Tic Tac Toe is a two player game. In your implementation one opponent will be a human player and the other a computer player. ? The game is played on a 3 x 3 game board. ? The first player is known as...

  • Please make this into one class. JAVA Please: Tic Tac Toe class - Write a fifth...

    Please make this into one class. JAVA Please: Tic Tac Toe class - Write a fifth game program that can play Tic Tac Toe. This game displays the lines of the Tic Tac Toe game and prompts the player to choose a move. The move is recorded on the screen and the computer picks his move from those that are left. The player then picks his next move. The program should allow only legal moves. The program should indicate when...

  • Write a program to Simulate a game of tic tac toe in c#

    Write a program to Simulate a game of tic tac toe. A game of tic tac toe has two players. A Player class is required to store /represent information about each player. The UML diagram is given below.Player-name: string-symbol :charPlayer (name:string,symbol:char)getName():stringgetSymbol():chargetInfo():string The tic tac toe board will be represented by a two dimensional array of size 3 by 3 characters. At the start of the game each cell is empty (must be set to the underscore character ‘_’). Program flow:1)    ...

  • use python to do it implement the tic-tac-toe game. What to submit: 1. Your source code...

    use python to do it implement the tic-tac-toe game. What to submit: 1. Your source code 2. Two runs, one user wins and one user loses.

  • Hey guys, I need help writing a Tic-Tac-Toe game programmed in Java. The game has to...

    Hey guys, I need help writing a Tic-Tac-Toe game programmed in Java. The game has to be a 1D (One-Dimension) array board NOT 2D. It has to be a human plays against the computer type of Tic-Tac-Toe. Here is the requirements for the program. PLEASE NO COPY AND PASTE ANSWER. Thank you in advance! You will develop a program in which a human plays against the computer. 1. Validate user input at every opportunity. a. Do not allow number entries...

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