Question

Please I need your help I have the code below but I need to add one...

Please I need your help

I have the code below but I need to add one thing, after player choose "No" to not play the game again, Add a HELP button or page that displays your name, the rules of the game and the month/day/year when you finished the implementation.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.Random;

public class TicTacToe extends JFrame implements ChangeListener, ActionListener {
  private JSlider slider;
  private JButton oButton, xButton;
  private Board board;
  private int lineThickness=4;
  private Color oColor=Color.BLUE, xColor=Color.RED;
  static final char BLANK=' ', O='O', X='X';
  private char position[]={  // Board position (BLANK, O, or X)
    BLANK, BLANK, BLANK,
    BLANK, BLANK, BLANK,
    BLANK, BLANK, BLANK};
  private int wins=0, losses=0, draws=0;  // game count by user

  // Start the game
  public static void main(String args[]) {
    new TicTacToe();
  }

  // Initialize
  public TicTacToe() {
    super("Tic Tac Toe demo");
    JPanel topPanel=new JPanel();
    topPanel.setLayout(new FlowLayout());
    topPanel.add(new JLabel("Line Thickness:"));
    topPanel.add(slider=new JSlider(SwingConstants.HORIZONTAL, 1, 20, 4));
    slider.setMajorTickSpacing(1);
    slider.setPaintTicks(true);
    slider.addChangeListener(this);
    topPanel.add(oButton=new JButton("O Color"));
    topPanel.add(xButton=new JButton("X Color"));
    oButton.addActionListener(this);
    xButton.addActionListener(this);
    add(topPanel, BorderLayout.NORTH);
    add(board=new Board(), BorderLayout.CENTER);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500, 500);
    setVisible(true);
  }

  // Change line thickness
  public void stateChanged(ChangeEvent e) {
    lineThickness = slider.getValue();
    board.repaint();
  }

  // Change color of O or X
  public void actionPerformed(ActionEvent e) {
    if (e.getSource()==oButton) {
      Color newColor = JColorChooser.showDialog(this, "Choose a new color for O", oColor);
      if (newColor!=null)
        oColor=newColor;
    }
    else if (e.getSource()==xButton) {
      Color newColor = JColorChooser.showDialog(this, "Choose a new color for X", xColor);
      if (newColor!=null)
        xColor=newColor;
    }
    board.repaint();
  }

  // Board is what actually plays and displays the game
  private class Board extends JPanel implements MouseListener {
    private Random random=new Random();
    private int rows[][]={{0,2},{3,5},{6,8},{0,6},{1,7},{2,8},{0,8},{2,6}};
      // Endpoints of the 8 rows in position[] (across, down, diagonally)

    public Board() {
      addMouseListener(this);
    }

    // Redraw the board
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      int w=getWidth();
      int h=getHeight();
      Graphics2D g2d = (Graphics2D) g;

      // Draw the grid
      g2d.setPaint(Color.WHITE);
      g2d.fill(new Rectangle2D.Double(0, 0, w, h));
      g2d.setPaint(Color.BLACK);
      g2d.setStroke(new BasicStroke(lineThickness));
      g2d.draw(new Line2D.Double(0, h/3, w, h/3));
      g2d.draw(new Line2D.Double(0, h*2/3, w, h*2/3));
      g2d.draw(new Line2D.Double(w/3, 0, w/3, h));
      g2d.draw(new Line2D.Double(w*2/3, 0, w*2/3, h));

      // Draw the Os and Xs
      for (int i=0; i<9; ++i) {
        double xpos=(i%3+0.5)*w/3.0;
        double ypos=(i/3+0.5)*h/3.0;
        double xr=w/8.0;
        double yr=h/8.0;
        if (position[i]==O) {
          g2d.setPaint(oColor);
          g2d.draw(new Ellipse2D.Double(xpos-xr, ypos-yr, xr*2, yr*2));
        }
        else if (position[i]==X) {
          g2d.setPaint(xColor);
          g2d.draw(new Line2D.Double(xpos-xr, ypos-yr, xpos+xr, ypos+yr));
          g2d.draw(new Line2D.Double(xpos-xr, ypos+yr, xpos+xr, ypos-yr));
        }
      }
    }

    // Draw an O where the mouse is clicked
    public void mouseClicked(MouseEvent e) {
      int xpos=e.getX()*3/getWidth();
      int ypos=e.getY()*3/getHeight();
      int pos=xpos+3*ypos;
      if (pos>=0 && pos<9 && position[pos]==BLANK) {
        position[pos]=O;
        repaint();
        putX();  // computer plays
        repaint();
      }
    }

    // Ignore other mouse events
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}

    // Computer plays X
    void putX() {
      
      // Check if game is over
      if (won(O))
        newGame(O);
      else if (isDraw())
        newGame(BLANK);

      // Play X, possibly ending the game
      else {
        nextMove();
        if (won(X))
          newGame(X);
        else if (isDraw())
          newGame(BLANK);
      }
    }

    // Return true if player has won
    boolean won(char player) {
      for (int i=0; i<8; ++i)
        if (testRow(player, rows[i][0], rows[i][1]))
          return true;
      return false;
    }

    // Has player won in the row from position[a] to position[b]?
    boolean testRow(char player, int a, int b) {
      return position[a]==player && position[b]==player 
          && position[(a+b)/2]==player;
    }

    // Play X in the best spot
    void nextMove() {
      int r=findRow(X);  // complete a row of X and win if possible
      if (r<0)
        r=findRow(O);  // or try to block O from winning
      if (r<0) {  // otherwise move randomly
        do
          r=random.nextInt(9);
        while (position[r]!=BLANK);
      }
      position[r]=X;
    }

    // Return 0-8 for the position of a blank spot in a row if the
    // other 2 spots are occupied by player, or -1 if no spot exists
    int findRow(char player) {
      for (int i=0; i<8; ++i) {
        int result=find1Row(player, rows[i][0], rows[i][1]);
        if (result>=0)
          return result;
      }
      return -1;
    }

    // If 2 of 3 spots in the row from position[a] to position[b]
    // are occupied by player and the third is blank, then return the
    // index of the blank spot, else return -1.
    int find1Row(char player, int a, int b) {
      int c=(a+b)/2;  // middle spot
      if (position[a]==player && position[b]==player && position[c]==BLANK)
        return c;
      if (position[a]==player && position[c]==player && position[b]==BLANK)
        return b;
      if (position[b]==player && position[c]==player && position[a]==BLANK)
        return a;
      return -1;
    }

    // Are all 9 spots filled?
    boolean isDraw() {
      for (int i=0; i<9; ++i)
        if (position[i]==BLANK)
          return false;
      return true;
    }

    // Start a new game
    void newGame(char winner) {
      repaint();

      // Announce result of last game.  Ask user to play again.
      String result;
      if (winner==O) {
        ++wins;
        result = "You Win!";
      }
      else if (winner==X) {
        ++losses;
        result = "I Win!";
      }
      else {
        result = "Tie";
        ++draws;
      }
      if (JOptionPane.showConfirmDialog(null, 
          "You have "+wins+ " wins, "+losses+" losses, "+draws+" draws\n"
          +"Play again?", result, JOptionPane.YES_NO_OPTION)
          !=JOptionPane.YES_OPTION) {
        System.exit(0);
      }

      // Clear the board to start a new game
      for (int j=0; j<9; ++j)
        position[j]=BLANK;

      // Computer starts first every other game
      if ((wins+losses+draws)%2 == 1)
        nextMove();
    }
  } // end inner class Board
} // end class TicTacToe
0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have added the following code in line numebr 249.

JOptionPane.showMessageDialog(null, "Program developed by YOUR NAME\n" +
               "Rules for TIC TAC TOE\n" +
               " 1. The game is played on a grid that's 3 squares by 3 squares.\n" +
               " 2. You are X, your friend (or the computer in this case) is O." +
               " Players take turns putting their marks in empty squares.\n" +
               " 3. The first player to get 3 of her marks in a row " +
               " (up, down, across, or diagonally) is the winner.\n" +
               " 4. When all 9 squares are full, the game is over." +
               " If no player has 3 marks in a row, the game ends in a tie.\n" +
               "Program completed on 10/13/2020");
       System.exit(0);

Following is the modified complete program.

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TicTacToe extends JFrame implements ChangeListener, ActionListener {
private JSlider slider;
private JButton oButton, xButton;
private Board board;
private int lineThickness=4;
private Color oColor=Color.BLUE, xColor=Color.RED;
static final char BLANK=' ', O='O', X='X';
private char position[]={ // Board position (BLANK, O, or X)
BLANK, BLANK, BLANK,
BLANK, BLANK, BLANK,
BLANK, BLANK, BLANK};
private int wins=0, losses=0, draws=0; // game count by user

// Start the game
public static void main(String args[]) {
new TicTacToe();
}
  
// Initialize
public TicTacToe() {
super("Tic Tac Toe demo");
JPanel topPanel=new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(new JLabel("Line Thickness:"));
topPanel.add(slider=new JSlider(SwingConstants.HORIZONTAL, 1, 20, 4));
slider.setMajorTickSpacing(1);
slider.setPaintTicks(true);
slider.addChangeListener(this);
topPanel.add(oButton=new JButton("O Color"));
topPanel.add(xButton=new JButton("X Color"));
oButton.addActionListener(this);
xButton.addActionListener(this);
add(topPanel, BorderLayout.NORTH);
add(board=new Board(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}

// Change line thickness
public void stateChanged(ChangeEvent e) {
lineThickness = slider.getValue();
board.repaint();
}
// Change color of O or X
public void actionPerformed(ActionEvent e) {
if (e.getSource()==oButton) {
Color newColor = JColorChooser.showDialog(this, "Choose a new color for O", oColor);
if (newColor!=null)
oColor=newColor;
}
else if (e.getSource()==xButton) {
Color newColor = JColorChooser.showDialog(this, "Choose a new color for X", xColor);
if (newColor!=null)
xColor=newColor;
}
board.repaint();
}

// Board is what actually plays and displays the game
private class Board extends JPanel implements MouseListener {
private Random random=new Random();
private int rows[][]={{0,2},{3,5},{6,8},{0,6},{1,7},{2,8},{0,8},{2,6}};
// Endpoints of the 8 rows in position[] (across, down, diagonally)

public Board() {
addMouseListener(this);
}
// Redraw the board
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w=getWidth();
int h=getHeight();
Graphics2D g2d = (Graphics2D) g;

// Draw the grid
g2d.setPaint(Color.WHITE);
g2d.fill(new Rectangle2D.Double(0, 0, w, h));
g2d.setPaint(Color.BLACK);
g2d.setStroke(new BasicStroke(lineThickness));
g2d.draw(new Line2D.Double(0, h/3, w, h/3));
g2d.draw(new Line2D.Double(0, h*2/3, w, h*2/3));
g2d.draw(new Line2D.Double(w/3, 0, w/3, h));
g2d.draw(new Line2D.Double(w*2/3, 0, w*2/3, h));

// Draw the Os and Xs
for (int i=0; i<9; ++i) {
double xpos=(i%3+0.5)*w/3.0;
double ypos=(i/3+0.5)*h/3.0;
double xr=w/8.0;
double yr=h/8.0;
if (position[i]==O) {
g2d.setPaint(oColor);
g2d.draw(new Ellipse2D.Double(xpos-xr, ypos-yr, xr*2, yr*2));
}
else if (position[i]==X) {
g2d.setPaint(xColor);
g2d.draw(new Line2D.Double(xpos-xr, ypos-yr, xpos+xr, ypos+yr));
g2d.draw(new Line2D.Double(xpos-xr, ypos+yr, xpos+xr, ypos-yr));
}
}
}

// Draw an O where the mouse is clicked
public void mouseClicked(MouseEvent e) {
int xpos=e.getX()*3/getWidth();
int ypos=e.getY()*3/getHeight();
int pos=xpos+3*ypos;
if (pos>=0 && pos<9 && position[pos]==BLANK) {
position[pos]=O;
repaint();
putX(); // computer plays
repaint();
}
}

// Ignore other mouse events
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

// Computer plays X
void putX() {
  
// Check if game is over
if (won(O))
newGame(O);
else if (isDraw())
newGame(BLANK);

// Play X, possibly ending the game
else {
nextMove();
if (won(X))
newGame(X);
else if (isDraw())
newGame(BLANK);
}
}
// Return true if player has won
boolean won(char player) {
for (int i=0; i<8; ++i)
if (testRow(player, rows[i][0], rows[i][1]))
return true;
return false;
}

// Has player won in the row from position[a] to position[b]?
boolean testRow(char player, int a, int b) {
return position[a]==player && position[b]==player
&& position[(a+b)/2]==player;
}

// Play X in the best spot
void nextMove() {
int r=findRow(X); // complete a row of X and win if possible
if (r<0)
r=findRow(O); // or try to block O from winning
if (r<0) { // otherwise move randomly
do
r=random.nextInt(9);
while (position[r]!=BLANK);
}
position[r]=X;
}
// Return 0-8 for the position of a blank spot in a row if the
// other 2 spots are occupied by player, or -1 if no spot exists
int findRow(char player) {
for (int i=0; i<8; ++i) {
int result=find1Row(player, rows[i][0], rows[i][1]);
if (result>=0)
return result;
}
return -1;
}

// If 2 of 3 spots in the row from position[a] to position[b]
// are occupied by player and the third is blank, then return the
// index of the blank spot, else return -1.
int find1Row(char player, int a, int b) {
int c=(a+b)/2; // middle spot
if (position[a]==player && position[b]==player && position[c]==BLANK)
return c;
if (position[a]==player && position[c]==player && position[b]==BLANK)
return b;
if (position[b]==player && position[c]==player && position[a]==BLANK)
return a;
return -1;
}
// Are all 9 spots filled?
boolean isDraw() {
for (int i=0; i<9; ++i)
if (position[i]==BLANK)
return false;
return true;
}

// Start a new game
void newGame(char winner) {
repaint();

// Announce result of last game. Ask user to play again.
String result;
if (winner==O) {
++wins;
result = "You Win!";
}
else if (winner==X) {
++losses;
result = "I Win!";
}
else {
result = "Tie";
++draws;
}
if (JOptionPane.showConfirmDialog(null,
"You have "+wins+ " wins, "+losses+" losses, "+draws+" draws\n"
+"Play again?", result, JOptionPane.YES_NO_OPTION)
!=JOptionPane.YES_OPTION) {
       JOptionPane.showMessageDialog(null, "Program developed by YOUR NAME\n" +
               "Rules for TIC TAC TOE\n" +
               " 1. The game is played on a grid that's 3 squares by 3 squares.\n" +
               " 2. You are X, your friend (or the computer in this case) is O." +
               " Players take turns putting their marks in empty squares.\n" +
               " 3. The first player to get 3 of her marks in a row " +
               " (up, down, across, or diagonally) is the winner.\n" +
               " 4. When all 9 squares are full, the game is over." +
               " If no player has 3 marks in a row, the game ends in a tie.\n" +
               "Program completed on 10/13/2020");
       System.exit(0);
}
// Clear the board to start a new game
for (int j=0; j<9; ++j)
position[j]=BLANK;

// Computer starts first every other game
if ((wins+losses+draws)%2 == 1)
nextMove();
}
} // end inner class Board
} // end class TicTacToe
  
х Message i Program developed by YOUR NAME Rules for TIC TAC TOE 1. The game is played on a grid thats 3 squares by 3 square

Add a comment
Know the answer?
Add Answer to:
Please I need your help I have the code below but I need to add one...
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
  • JAVA Only Help on the sections that say Student provide code. The student Provide code has...

    JAVA Only Help on the sections that say Student provide code. The student Provide code has comments that i put to state what i need help with. import java.util.Scanner; public class TicTacToe {     private final int BOARDSIZE = 3; // size of the board     private enum Status { WIN, DRAW, CONTINUE }; // game states     private char[][] board; // board representation     private boolean firstPlayer; // whether it's player 1's move     private boolean gameOver; // whether...

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

  • This is my code for a TicTacToe game. However, I don't know how to write JUnit...

    This is my code for a TicTacToe game. However, I don't know how to write JUnit tests. Please help me with my JUnit Tests. I will post below what I have so far. package cs145TicTacToe; import java.util.Scanner; /** * A multiplayer Tic Tac Toe game */ public class TicTacToe {    private char currentPlayer;    private char[][] board;    private char winner;       /**    * Default constructor    * Initializes the board to be 3 by 3 and...

  • Please modify the following code to NOT have "TicTacToe extends Board" (I don't want any extending)....

    Please modify the following code to NOT have "TicTacToe extends Board" (I don't want any extending). Please ensure the resulting code completes EACH part of the following prompt: "Your task is to create a game of Tic-Tac-Toe using a 2-Dimensional String array as the game board. Start by creating a Board class that holds the array. The constructor should use a traditional for-loop to fill the array with "blank" Strings (eg. "-"). You may want to include other instance data......

  • This is my code for my game called Reversi, I need to you to make the...

    This is my code for my game called Reversi, I need to you to make the Tester program that will run and complete the game. Below is my code, please add comments and Javadoc. Thank you. public class Cell { // Displays 'B' for the black disk player. public static final char BLACK = 'B'; // Displays 'W' for the white disk player. public static final char WHITE = 'W'; // Displays '*' for the possible moves available. public static...

  • Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import...

    Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class Project3 extends JFrame implements ActionListener { private static int winxpos = 0, winypos = 0; // place window here private JButton exitButton, hitButton, stayButton, dealButton, newGameButton; private CardList theDeck = null; private JPanel northPanel; private MyPanel centerPanel; private static JFrame myFrame = null; private CardList playerHand = new CardList(0); private CardList dealerHand = new CardList(0);...

  • There is a problem with thecode. I get the error messages " 'board' was not declared...

    There is a problem with thecode. I get the error messages " 'board' was not declared in this scope", \src\TicTacToe.cpp|7|error: expected unqualified-id before ')' token| \src\TicTacToe.cpp|100|error: expected declaration before '}' token| Here is the code #ifndef TICTACTOE_H #define TICTACTOE_H #include class TicTacToe { private: char board [3][3]; public: TicTacToe () {} void printBoard(); void computerTurn(char ch); bool playerTurn (char ch); char winVerify(); }; ************************************ TicTacToe.cpp #endif // TICTACTOE_H #include "TicTacToe.h" #include #include using namespace std; TicTacToe() { for(int i =...

  • I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<i...

    I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<iostream> using namespace std; const int ROWS=3; const int COLS=3; void fillBoard(char [][3]); void showBoard(char [][3]); void getChoice(char [][3],bool); bool gameOver(char [][3]); int main() { char board[ROWS][COLS]; bool playerToggle=false; fillBoard(board); showBoard(board); while(!gameOver(board)) { getChoice(board,playerToggle); showBoard(board); playerToggle=!playerToggle; } return 1; } void fillBoard(char board[][3]) { for(int i=0;i<ROWS;i++) for(int j=0;j<COLS;j++) board[i][j]='*'; } void showBoard(char board[][3]) { cout<<" 1 2 3"<<endl; for(int i=0;i<ROWS;i++) { cout<<(i+1)<<"...

  • Java. i.Write a public instance method alignBody() that takes no arguments and returns no value. It...

    Java. i.Write a public instance method alignBody() that takes no arguments and returns no value. It should set the xPos and yPos of the body to the xPos and yPos of the StickFigure. ii.Write a public instance method alignLeg() that takes no argument and returns no value. It should set the xPos and yPos of the leg so it is centred immediately below the body of the StickFigure. public class StickFigure { /*Instance variables*/    private int xPos;//The horizontal position...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making 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 stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

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