Hwk10java package hwk10 import javaawtBorderLayout import ja

Hwk10.java

package hwk10;

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Component;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.IOException;

import javax.imageio.ImageIO;

import javax.swing.BoxLayout;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

@SuppressWarnings(\"serial\")

public class Hwk10 extends JFrame {

   Hwk10() {

       this.setTitle(\"Tic Tac Toe\");

       this.setBounds(0, 0, 600, 600);

       this.setDefaultCloseOperation(EXIT_ON_CLOSE);

   }

  

  

   public static void main(String[] args) throws IOException {

       JFrame frame = new Hwk10();

frame.setLayout(new BorderLayout());

  

// create a panel with box layer aligned with y axis

JPanel gamePanel = new JPanel();

gamePanel.setLayout(new BoxLayout(gamePanel, BoxLayout.Y_AXIS));

  

// create a new game button that is centered on x axis

JButton newGame = new JButton(\"New Game\");

newGame.setAlignmentX(Component.CENTER_ALIGNMENT);

// add the new game button to the game panel

gamePanel.add(newGame);

  

// create a box panel with 3 x 3 grid layout

JPanel box = new JPanel();

box.setLayout(new GridLayout(3, 3));

  

// create an array of 9 buttons and add them to the box panel

JButton[] buttons = new JButton[9];

for (int i = 0; i < 9; i++) {

buttons[i] = new JButton(\"\");

box.add(buttons[i]);

}

  

  

// instantiate a tic-tac-toe game object

final TicTacToe game = new TicTacToe(buttons);

  

// add an action listener to the new-game buttom so that it clears the game on click.

ActionListener WhenHitTheButton = new ActionListener() {

public void actionPerformed(ActionEvent e) {

game.clear();

}

};

newGame.addActionListener(WhenHitTheButton);

  

// add game panel (north) and box panel (center) to the frame and set it visible

frame.add(gamePanel, BorderLayout.NORTH);

frame.add(box, BorderLayout.CENTER);

      

       frame.setVisible(true);

   }

}

class TicTacToe {

   int[] data = new int[9];

   JButton[] buttons;

   boolean isX = true;

   // this variable keeps track of how many steps the game has played (it cannot be >= 9)

   int steps = 0;

   // use the flag to indicate whether the game has ended due to that X wins or O wins but not due to a draw

   boolean gameEnded = true;

  

   ImageIcon icon_x, icon_o;

  

   // save buttons, load icon images, and clear the game (by calling \"clear\" method)

   TicTacToe(JButton[] buttons) throws IOException {

       this.buttons = buttons;

       icon_x = new ImageIcon(ImageIO.read(getClass().getResource(\"x.png\")));

       icon_o = new ImageIcon(ImageIO.read(getClass().getResource(\"o.png\")));

       clear();

   }

  

   // add the same listener to all buttons

   void addListener() {

       // TODO

   }

   // create an action listener

   ActionListener buttonListener = new ActionListener() {

       // 1. Use the event source to find out which button is clicked

       // 2. Find out if anyone wins and if so, has it X or O player won

       // 3. In the console,

       // if X wins, print \"X wins\",

       // if O wins, print \"O wins\",

       // if it is a draw (max number of steps has reached), print \"Draw\"

       // if nobody wins, do nothing and continue the game

       // 4. Don\'t forget to increment the \"steps\" variable to find out whether max number of steps has reached.

       // 5. Switch player in this method as well if it is a legal move.

       @Override

       public void actionPerformed(ActionEvent e) {

           Object src = e.getSource();

           // TODO

       }

   };

  

   // reset \"steps\" to 0

   // for each button, set the background color to \"white\" and remove icons from buttons \"setIcon(null)\"

   // reset \"data\" array to 0

   // if game has ended (due to someone winnning), add listener back to buttons and reset the flag to false

   void clear() {

       // TODO

   }

  

   // remove listener from all buttons and set \"gameEnded\" flag to true

   void removeListener() {

       // TODO

   }

  

   // put X or O at i

   // if a button click is legal (i.e. the button was no clicked before), set icons to the button and update \"data\" array accordingly

   // return true if and only if the button click is legal

   boolean play(int i, boolean isX) {

       // TODO

   }

   // if X wins, return 1,

   // if O wins, return 2,

   // if draws or no result, return 0

   //

   // if someone wins, the remove listeners so that subsequent clicks won\'t change the remaining unclicked buttons

   int win() {

       // TODO

   }

   // check whether the ith row matches

   // if so, set the background for that row of buttons to blue color

   // and also return 1 if X wins, 2 if O wins, 0 if nobody wins

   int checkRow(int i) {

       // TODO

   }

   // check whether the ith column matches

   // if so, set the background for that column of buttons to blue color

   // and also return 1 if X wins, 2 if O wins, 0 if nobody wins

   int checkColumn(int i) {

       // TODO

   }

   // check whether a diagonal matches

   // if so, set the background for that diagonal of buttons to blue color

   // and also return 1 if X wins, 2 if O wins, 0 if nobody wins

   // note that there are two diagonals to check

   int checkDiagonal() {

       // TODO

   }

   // set buttons at the specified indices to blue

   void setBackground(int[] indices) {

       // TODO

   }

}

Homework 10 November 12, 2016 1 Overview In this assignment, you will continue homework 9 by adding some features to the Tic Tac Toe game. 2 Requirements You should check whether the player X or O wins or a draw has been reached each time a legal move has been made. You should print out the game result (X wins, O wins, or draw) in the console. If a player wins (not draw), you should disable the remaining unclicked buttons in the game grid so that they cannot be selected. You can accomplish this by removing listeners from all buttons. If a player wins, you should highlight the winning row, column, or diagonal by changing the background of the corresponding buttons to blue. When new game button is clicked, you should remove all icons from the buttons in the grid and change their background color to white again 3 GUI You should try t with this to emulate the behavior shown in the video I pos homework 4 Submission You should submit your source code by the name of Hwk10.java to the drop box

Solution

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

@Suppress Warnings(\"serial\")

public class TTTGraphics2p extends JFrame{

//Named-constants for the game board

public static final int ROWS = 3;

public static final int COLS = 3;

public static final int CELL_SIZE = 100;

public static final int CANVAS_WIDTH = CELL_SIZE * COLS;

public static final int CANVAS_HEIGHT =CELL_SIZE * ROWS;

public static final int GRID_WIDTH = 8;

public static final int GRID_WIDTH_HALF = GRID_WIDTH/2;

public static final int CELL_PADDING = CELL_SIZE - CELL_PADDING*2;

public static final int SYMBOL_STROKE_WIDTH = 8;

public enum GameState{

PLAYING,DRAW,CROSS_WON,NOUGHT_WON

}

private GameState currentState;

public enum Seed{

EMPTY CROSS NOUGHT

}

private Seed currentPlayer;

private Seed[][]board;

private DrawCanvas canvas;

private JLabel statusBar;

public TTTGraphics2p(){

canvas = new DrawCanvas();

canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));

canvas.addMouseListener(new MouseAdapter(){

@Override

public void mouseClicked(MouseEvent e){

int mouseX = e.getX();

int mouseY = e.getY();
// Get the row and column clicked
int rowSelected = mouseY / CELL_SIZE;
int colSelected = mouseX / CELL_SIZE;

if (currentState == GameState.PLAYING) {
if (rowSelected >= 0 && rowSelected < ROWS && colSelected >= 0
&& colSelected < COLS && board[rowSelected][colSelected] == Seed.EMPTY) {
board[rowSelected][colSelected] = currentPlayer; // Make a move
updateGame(currentPlayer, rowSelected, colSelected); // update state
// Switch player
currentPlayer = (currentPlayer == Seed.CROSS) ? Seed.NOUGHT : Seed.CROSS;
}
} else { // game over
initGame(); // restart the game
}
// Refresh the drawing canvas
repaint(); // Call-back paintComponent().
}
});

// Setup the status bar (JLabel) to display status message
statusBar = new JLabel(\" \");
statusBar.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 15));
statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5));

Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.CENTER);
cp.add(statusBar, BorderLayout.PAGE_END); // same as SOUTH

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack(); // pack all the components in this JFrame
setTitle(\"Tic Tac Toe\");
setVisible(true); // show this JFrame

board = new Seed[ROWS][COLS]; // allocate array
initGame(); // initialize the game board contents and game variables
}

/** Initialize the game-board contents and the status */
public void initGame() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
board[row][col] = Seed.EMPTY; // all cells empty
}
}
currentState = GameState.PLAYING; // ready to play
currentPlayer = Seed.CROSS; // cross plays first
}

/** Update the currentState after the player with \"theSeed\" has placed on
(rowSelected, colSelected). */
public void updateGame(Seed theSeed, int rowSelected, int colSelected) {
if (hasWon(theSeed, rowSelected, colSelected)) { // check for win
currentState = (theSeed == Seed.CROSS) ? GameState.CROSS_WON : GameState.NOUGHT_WON;
} else if (isDraw()) { // check for draw
currentState = GameState.DRAW;
}
// Otherwise, no change to current state (still GameState.PLAYING).
}

/** Return true if it is a draw (i.e., no more empty cell) */
public boolean isDraw() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
if (board[row][col] == Seed.EMPTY) {
return false; // an empty cell found, not draw, exit
}
}
}
return true; // no more empty cell, it\'s a draw
}

/** Return true if the player with \"theSeed\" has won after placing at
(rowSelected, colSelected) */
public boolean hasWon(Seed theSeed, int rowSelected, int colSelected) {
return (board[rowSelected][0] == theSeed // 3-in-the-row
&& board[rowSelected][1] == theSeed
&& board[rowSelected][2] == theSeed
|| board[0][colSelected] == theSeed // 3-in-the-column
&& board[1][colSelected] == theSeed
&& board[2][colSelected] == theSeed
|| rowSelected == colSelected // 3-in-the-diagonal
&& board[0][0] == theSeed
&& board[1][1] == theSeed
&& board[2][2] == theSeed
|| rowSelected + colSelected == 2 // 3-in-the-opposite-diagonal
&& board[0][2] == theSeed
&& board[1][1] == theSeed
&& board[2][0] == theSeed);
}

/**
* Inner class DrawCanvas (extends JPanel) used for custom graphics drawing.
*/
class DrawCanvas extends JPanel {
@Override
public void paintComponent(Graphics g) { // invoke via repaint()
super.paintComponent(g); // fill background
setBackground(Color.WHITE); // set its background color

// Draw the grid-lines
g.setColor(Color.LIGHT_GRAY);
for (int row = 1; row < ROWS; ++row) {
g.fillRoundRect(0, CELL_SIZE * row - GRID_WIDHT_HALF,
CANVAS_WIDTH-1, GRID_WIDTH, GRID_WIDTH, GRID_WIDTH);
}
for (int col = 1; col < COLS; ++col) {
g.fillRoundRect(CELL_SIZE * col - GRID_WIDHT_HALF, 0,
GRID_WIDTH, CANVAS_HEIGHT-1, GRID_WIDTH, GRID_WIDTH);
}

// Draw the Seeds of all the cells if they are not empty
// Use Graphics2D which allows us to set the pen\'s stroke
Graphics2D g2d = (Graphics2D)g;
g2d.setStroke(new BasicStroke(SYMBOL_STROKE_WIDTH, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND)); // Graphics2D only
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
int x1 = col * CELL_SIZE + CELL_PADDING;
int y1 = row * CELL_SIZE + CELL_PADDING;
if (board[row][col] == Seed.CROSS) {
g2d.setColor(Color.RED);
int x2 = (col + 1) * CELL_SIZE - CELL_PADDING;
int y2 = (row + 1) * CELL_SIZE - CELL_PADDING;
g2d.drawLine(x1, y1, x2, y2);
g2d.drawLine(x2, y1, x1, y2);
} else if (board[row][col] == Seed.NOUGHT) {
g2d.setColor(Color.BLUE);
g2d.drawOval(x1, y1, SYMBOL_SIZE, SYMBOL_SIZE);
}
}
}

// Print status-bar message
if (currentState == GameState.PLAYING) {
statusBar.setForeground(Color.BLACK);
if (currentPlayer == Seed.CROSS) {
statusBar.setText(\"X\'s Turn\");
} else {
statusBar.setText(\"O\'s Turn\");
}
} else if (currentState == GameState.DRAW) {
statusBar.setForeground(Color.RED);
statusBar.setText(\"It\'s a Draw! Click to play again.\");
} else if (currentState == GameState.CROSS_WON) {
statusBar.setForeground(Color.RED);
statusBar.setText(\"\'X\' Won! Click to play again.\");
} else if (currentState == GameState.NOUGHT_WON) {
statusBar.setForeground(Color.RED);
statusBar.setText(\"\'O\' Won! Click to play again.\");
}
}
}

/** The entry main() method */
public static void main(String[] args) {
// Run GUI codes in the Event-Dispatching thread for thread safety
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TTTGraphics2P(); // Let the constructor do the job
}
});
}
}

Hwk10.java package hwk10; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.Acti
Hwk10.java package hwk10; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.Acti
Hwk10.java package hwk10; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.Acti
Hwk10.java package hwk10; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.Acti
Hwk10.java package hwk10; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.Acti
Hwk10.java package hwk10; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.Acti
Hwk10.java package hwk10; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.Acti
Hwk10.java package hwk10; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.Acti
Hwk10.java package hwk10; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.Acti

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site