Results 1 to 14 of 14
  1. #1
    efceddy is offline Member
    Join Date
    Apr 2013
    Posts
    11
    Rep Power
    0

    Default Help with java (action replay)

    I am currently creating a tic tac toe game and need help with the following
    1. How do i print the results from the text file (code needed and what needs to be in the text file)
    2. How do i preform a action replay of every move made in the game.

    Below is my code
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    
    @SuppressWarnings("serial") // Checks for warnings
    public class TTTGraphics2P extends JFrame { // Name of class so the game can be created
       
    
    	
       // Grid Layout
       public static final int ROWS = 4;  
       public static final int COLS = 4;
       
       
       // Constants for creating the board
       public static final int CELL_SIZE = 50; // cell width and height (square)
       public static final int CANVAS_WIDTH = CELL_SIZE * COLS;  // Allows the canvas to be drawn
       public static final int CANVAS_HEIGHT = CELL_SIZE * ROWS;
       public static final int GRID_WIDTH = 6;                  
       public static final int GRID_WIDHT_HALF = GRID_WIDTH / 1;
       // Grid line's width
       
       public static final int CELL_PADDING = CELL_SIZE / 6;
       public static final int SYMBOL_SIZE = CELL_SIZE - CELL_PADDING * 2; // width/height
       public static final int SYMBOL_STROKE_WIDTH = 3; // width of the O and X
     
      
       public enum GameState {
          PLAYING, DRAW, CROSS_WON, NOUGHT_WON
          // Represents the value of which player won / lost / drew
       }
       private GameState currentState;  // the current game state
     
       // Use an enumeration (inner class) to represent the seeds and cell contents
       public enum Seed {
          EMPTY, CROSS, NOUGHT
       }
       private Seed currentPlayer;  // the current player
     
       private Seed[][] board   ; // Game board of ROWS-by-COLS cells
       private DrawCanvas canvas; // Drawing canvas (JPanel) for the game board
       private JLabel statusBar;  // Status Bar
     
       /** Constructor to setup the game and the GUI components */
       public TTTGraphics2P() {
          canvas = new DrawCanvas();  // Construct a drawing canvas (a JPanel)
          canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
     
          // Code used to create a mouse click so they can place a O or X in the square
          canvas.addMouseListener(new MouseAdapter() {
             @Override
             public void mouseClicked(MouseEvent e) {  
                int mouseX = e.getX();
                int mouseY = e.getY();
                
                int rowSelected = mouseY / CELL_SIZE;
                int colSelected = mouseX / CELL_SIZE;
                // Code above shows the row / colum selected
                
                
                if (currentState == GameState.PLAYING) {
                   if (rowSelected >= 0 && rowSelected < ROWS && colSelected >= 0
                         && colSelected < COLS && board[rowSelected][colSelected] == Seed.EMPTY) {
                      board[rowSelected][colSelected] = currentPlayer; // Allows a move to be made
                      updateGame(currentPlayer, rowSelected, colSelected); // update state
                      
                      currentPlayer = (currentPlayer == Seed.CROSS) ? Seed.NOUGHT : Seed.CROSS; // Code allows the player to switch and have there go
                   }
                } else {       // game over
                   initGame(); // restarts the game
                }
                // Refresh the drawing canvas
                repaint();  // Call-back paintComponent().
             }
          });
     
          
          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); 
     
          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  // 4-in-the-row
                && board[rowSelected][1] == theSeed
                && board[rowSelected][2] == theSeed
           || board[0][colSelected] == theSeed      // 4-in-the-column
                && board[1][colSelected] == theSeed
                && board[2][colSelected] == theSeed
           || rowSelected == colSelected            // 4-in-the-diagonal
                && board[0][0] == theSeed
                && board[1][1] == theSeed
                && board[2][2] == theSeed
           || rowSelected + colSelected == 2  // -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);
                   }
                }
             }
            
    
             System.out.println(" 1 2 3");
             System.out.println("A" + board[0][0] + "|" + board[0][1] + "|" + board[0][2]);  
             System.out.println("-----");
             System.out.println("B" + board[1][0] + "|" + board[1][1] + "|" + board[1][2]);  
             System.out.println("-----");
             System.out.println("C" + board[2][0] + "|" + board[2][1] + "|" + board[2][2]);                        
             
             
             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.");
             // Prints the message of whos turn / won / 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
             }
          });
       }
    }
    Last edited by Tolls; 04-05-2013 at 04:38 PM. Reason: Add tags

  2. #2
    efceddy is offline Member
    Join Date
    Apr 2013
    Posts
    11
    Rep Power
    0

    Default Re: Help with java (action replay)

    anyone

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default Re: Help with java (action replay)

    First you need to wrap your code in [code] tags [/code] so it retains its formatting.
    Unformatted code is really hard to follow.

    Second, 10 minutes? Really?

    And on to your questions.
    1. What does this mean? What text file?
    2. In order to have a replay facility you will need to store the moves somewhere.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    efceddy is offline Member
    Join Date
    Apr 2013
    Posts
    11
    Rep Power
    0

    Default Re: Help with java (action replay)

    1. I have to show persistent scores a total of games won, drawn and lost for each player have no idea how
    2. Where do i stores the moves for the action replay

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default Re: Help with java (action replay)

    Please don't spam the forums.
    I've closed the other 2 threads.

    You haven't wrapped your code, so I can't see what you've done.

    For the persisting of results you'll need to come up with some form of format for the file.
    For the action replay you need to come up with some model for what a move consists of, and store those moves somewhere...that would usually be a class or classes that model a Tic Tac Toe game as Moves. You would probably be OK with a List<Move> where Move is a class representing the move made, and who by. You could even skip the who by, since it goes 'O' then 'X' usually.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    efceddy is offline Member
    Join Date
    Apr 2013
    Posts
    11
    Rep Power
    0

    Default Re: Help with java (action replay)

    You haven't wrapped your code, so I can't see what you've done - how do i wrap the code

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default Re: Help with java (action replay)

    To quote myself:
    "
    First you need to wrap your code in [code] tags [/code] so it retains its formatting.
    "
    Java Code:
    Look code
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    efceddy is offline Member
    Join Date
    Apr 2013
    Posts
    11
    Rep Power
    0

    Default Re: Help with java (action replay)

    wont let me wrap the code can you not copy and paste it in too see

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default Re: Help with java (action replay)

    OK.
    Added them in myself...probably timed out for editing.

    For persisting to a file, what does "each player" mean? Are we talking people, or simply NOUGHT and CROSS?
    If the latter then two rows should do it, each containing 3 numbers separated by commas...won, drawn, lost.
    The first row is NOUGHTs and the second is CROSSes.

    For replay of the last game, the simplest would be an array of moves.
    Strictly (for Java) this should be done with classes, but you don't seem to have done that so a 2D array:
    Java Code:
    int[][] moves = new int[<some big number>][2];
    The first part is the move number, so <some big number> would be 9 I suppose as that's the maximum number of moves you can have on a 3x3 board. The second is the coordinates, so moves[0][0] is the rowSelected and moves[0][1] is the columnSelected for the first move.
    Since cross always starts (from the code) you know the first entry in the array is the CROSS move.

    And from that you should at least be able to piece together a replay method, even if only in Pseudo code.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    efceddy is offline Member
    Join Date
    Apr 2013
    Posts
    11
    Rep Power
    0

    Default Re: Help with java (action replay)

    Yes people as in Player 1 and Player 2
    my grid also needs to be 4x4 and it is does that matter
    If i have not used classes will it still work

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default Re: Help with java (action replay)

    It'll work.
    You just need to write it.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  12. #12
    efceddy is offline Member
    Join Date
    Apr 2013
    Posts
    11
    Rep Power
    0

    Default Re: Help with java (action replay)

    Do you also no the reason for this when i have 3x3 it works fine then when i change the grid layout to 4x4 it messes up. You carnt place a 0 or X i get a error message do you no why here is the code.

    import java.awt.GridLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;

    public class TicTacToe extends JFrame {

    /**
    * Constructor.
    *
    * @param argTitle A String containing the title
    */
    public TicTacToe( String argTitle ) {

    super( argTitle );
    }

    /**
    * This method constructs the user interface.
    */
    public void start() {
    EventHandler eventHandler = null;

    eventHandler = new EventHandler();
    buttons = new JButton[ NUMBER_OF_BUTTONS ];
    for( int i = 0; i < NUMBER_OF_BUTTONS; i++ ) {

    buttons[ i ] = new JButton( BUTTON_LABEL );
    buttons[ i ].setName( Integer.toString( i, RADIX ) );
    buttons[ i ].addActionListener( eventHandler );
    add( buttons[ i ] );
    }
    setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
    setLayout( new GridLayout( NUMBER_OF_ROWS, NUMBER_OF_COLS ) );
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    setVisible( SHOW );
    }

    /**
    * Executable method.
    * Execution begins here.
    *
    * @param args A String array containing command-line arguments.
    */
    public static void main( String[] args ) {
    TicTacToe game = null;

    game = new TicTacToe( "Tic-Tac-Toe" );
    game.start();
    }

    public static final String BUTTON_LABEL = " ";

    public static final int NUMBER_OF_BUTTONS = 16,
    NUMBER_OF_ROWS = 4,
    NUMBER_OF_COLS = 4,
    SCREEN_WIDTH = 200,
    SCREEN_HEIGHT = 200,
    RADIX = 10;

    public static final boolean SHOW = true;
    // NOTE : The array of buttons is made instance variable as it will be accessed by the EventHandler
    private JButton[] buttons = null;

    /**
    * This is a private class that evaluates the Game state for every move made by the user.
    *
    * NOTE : Private methods assume only correct input is passed to them.
    */
    private class EventHandler implements ActionListener {

    /**
    * The button clicked event handler.
    *
    * @param argEventObject An object of type ActionEvent.
    */
    public void actionPerformed( ActionEvent argEventObject ) {
    JButton button = null;

    button = (JButton) argEventObject.getSource();
    button.setText( ( firstPerson ? SYMBOL_FIRST : SYMBOL_SECOND ) );
    // NOTE : After every move the following value is changed to indicate a different person
    firstPerson = !firstPerson;
    button.setEnabled( NOT_ENABLE );
    if( getGameState( SYMBOL_FIRST ) ) {

    if( this.showMessage ) {

    JOptionPane.showMessageDialog( null, SYMBOL_FIRST + MSG_WIN );
    disableRestOfButtons();
    return;
    }
    } else {

    if( getGameState( SYMBOL_SECOND ) ) {

    if( this.showMessage ) {

    JOptionPane.showMessageDialog( null, SYMBOL_SECOND + MSG_WIN );
    disableRestOfButtons();
    return;
    }
    } else {

    if( this.showMessage || isEndOfGame() ) {
    JOptionPane.showMessageDialog( null, MSG_TIE );
    disableRestOfButtons();
    return;
    }
    }
    }
    }

    /**
    * This method disables the buttons that are still enabled.
    */
    private void disableRestOfButtons() {

    for( JButton button : buttons ) {

    if( button.isEnabled() ) {

    button.setEnabled( NOT_ENABLE );
    }
    }
    }

    /**
    * This method checks if all buttons have been clicked.
    *
    * @return boolean true if all buttons have been clicked and false otherwise
    */
    private boolean isEndOfGame() {
    boolean endOfGame = true;

    for( JButton button : buttons ) {

    if( button.isEnabled() ) {

    endOfGame = false;
    break;
    }
    }

    return endOfGame;
    }

    /**
    * This method checks the following conditions,
    * - Whether a user has selected a full row
    * - Whether a user has selected a full column
    * - Whether a user hase selected a full left diagonal
    * - Whether a user hase selected a full right diagonal
    *
    * @param argSymbol A String X representing the first user, while O representing the second user
    *
    * @return boolean true if any of the above conditions are satisfied and false otherwise
    */
    private boolean getGameState( String argSymbol ) {
    boolean win = false;

    win = getRowwiseWin( argSymbol );
    if( !win ) {

    win = getColumnwiseWin( argSymbol );
    }
    if( !win ) {

    // Left diagonal check
    win = getWinStatus( argSymbol, LEFT_DIAGONAL_START_INDEX, LEFT_DIAGONAL_END_INDEX, LEFT_DIAGONAL_INCREMENT );
    }
    if( !win ) {

    // Right diagonal check
    win = getWinStatus( argSymbol, RIGHT_DIAGONAL_START_INDEX, RIGHT_DIAGONAL_END_INDEX, RIGHT_DIAGONAL_INCREMENT );
    }
    this.showMessage = win;

    return win;
    }

    /**
    * This method checks the following condition,
    * - Whether a user has selected a full row
    *
    * @param argSymbol A String X representing the first user, while O representing the second user
    *
    * @return boolean true if the above condition is satisfied and false otherwise
    */
    private boolean getRowwiseWin( String argSymbol ) {
    boolean win = false;

    // Row-wise check
    for( int i = 0; i < buttons.length; i += NEXT_ROW ) {

    if( getWinStatus( argSymbol, i, ( i + COL_COUNT ), NEXT_COL ) ) {

    win = true;
    break;
    }
    }

    return win;
    }

    /**
    * This method checks the following condition,
    * - Whether a user has selected a full column
    *
    * @param argSymbol A String X representing the first user, while O representing the second user
    *
    * @return boolean true if the above condition is satisfied and false otherwise
    */
    private boolean getColumnwiseWin( String argSymbol ) {
    boolean win = false;

    // Column-wise check
    for( int i = 0; i <= COL_COUNT; i++ ) {

    if( getWinStatus( argSymbol, i, ( ( NEXT_ROW * COL_COUNT ) + i ), NEXT_ROW ) ) {

    win = true;
    break;
    }
    }

    return win;
    }

    /**
    * This is the work-horse method checks the following conditions,
    * - Whether a user has selected a full row
    * - Whether a user has selected a full column
    * - Whether a user hase selected a full left diagonal
    * - Whether a user hase selected a full right diagonal
    *
    * @param argSymbol A String X representing the first user, while O representing the second user
    *
    * @param argStartIndex An int representing the starting index
    *
    * @param argEndIndex An int representing the ending index
    *
    * @param argIncrement An int representing the increment
    *
    * @return boolean true if the above conditions are satisfied and false otherwise
    */
    private boolean getWinStatus( String argSymbol, int argStartIndex, int argEndIndex, int argIncrement ) {
    boolean win = false;
    int count = 0;

    for( int i = argStartIndex; i <= argEndIndex; i += argIncrement ) {

    count += ( argSymbol.equals( buttons[ i ].getText() ) ? WIN : LOOSE );
    }
    win = ( count == WIN_SCORE );

    return win;
    }

    private boolean firstPerson = true,
    showMessage = false;

    private final boolean NOT_ENABLE = false;
    private final int WIN = 1,
    LOOSE = 0,
    NEXT_ROW = 3,
    COL_COUNT = 2,
    WIN_SCORE = 3,
    NEXT_COL = 1,
    LEFT_DIAGONAL_INCREMENT = 4,
    LEFT_DIAGONAL_START_INDEX = 0,
    LEFT_DIAGONAL_END_INDEX = 8,
    RIGHT_DIAGONAL_END_INDEX = 6,
    RIGHT_DIAGONAL_START_INDEX = 2,
    RIGHT_DIAGONAL_INCREMENT = 2;

    private final String SYMBOL_FIRST = " X ",
    SYMBOL_SECOND = " O ",
    MSG_WIN = " WINS...",
    MSG_TIE = "TIE...";
    }
    }

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default Re: Help with java (action replay)

    First [code] tags [/code] !
    Without them I will not bother looking at the code.

    Second, post the full error including stack trace and highlight the line of code where the error occurs.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  14. #14
    efceddy is offline Member
    Join Date
    Apr 2013
    Posts
    11
    Rep Power
    0

    Default Re: Help with java (action replay)

    looking at the code you put in code tags how come when i run the application if they get 3 in a row they still do not win
    Last edited by efceddy; 04-05-2013 at 05:42 PM.

Similar Threads

  1. Replay Java Trace Execution
    By gonny in forum New To Java
    Replies: 1
    Last Post: 06-24-2012, 04:48 AM
  2. Whois Server does't replay anything
    By rootnet47 in forum Networking
    Replies: 2
    Last Post: 08-09-2011, 05:09 AM
  3. Replies: 1
    Last Post: 06-30-2011, 10:49 AM
  4. statment replay!!!
    By moamen in forum New To Java
    Replies: 4
    Last Post: 09-25-2009, 01:49 PM
  5. Replay Solutions Job Fair - Java & C++ Jobs
    By jackchang in forum Jobs Offered
    Replies: 0
    Last Post: 08-19-2008, 07:17 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •