Can't undo last move

I am trying to add an undo function to this program. Here is what I have so far. I can't get the undo function to work for some reason. Any help is appreciated.
// Five.java - main program for Five-In-A-Row Program
import javax.swing.JFrame;
////////////////////////////////////////////////////// class Five
/** Five.java - Winner is able to put 5 pieces in a row.
   The Five program consists of three files:
   Five.java      - this file with main to create window.
   FiveGUI.java   - implements the GUI interface.
   FiveLogic.java - the logical functioning.
   @author Fred Swartz
   @version 2004-05-02
class Five {
    //================================================ method main
    public static void main(String[] args) {
        JFrame window = new JFrame("Five In A Row");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setContentPane(new FiveGUI());
        window.pack();  // finalize layout
        window.setResizable(false);
        window.show();  // make window visible
    }//end main
}//endclass Five
//===========================================
// FiveGUI.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/////////////////////////////////////////////////// class FiveGUI
/** A Graphical User Interface for a Five-In-A-Row game.
    This implements the user interface (view and controller),
    but the logic (model) is implemented in a separate class that
    knows nothing about the user interface.
    <p>This subclasses JPanel and puts the some buttons in the north,
    a graphical display of the board in the center, and
    a status field in the south.
    </p>
    <p>Exercise: This game probably originated on a Go board where
       the pieces are placed on the intersections, not in the
       empty spaces.  Change the program to put all pieces on the
       intersections.
    </p>
    <p>Exercise: The Undo button doesn't do anything.  Fix it here
       in the GUI and in the logic.
    </p>
    <p>Exercise: Create a machine player.</p>
    @author Fred Swartz
    @version 2004-05-02 Rodenbach
class FiveGUI extends JPanel {
    //=============================================== instance variables
    private GraphicsPanel boardDisplay_;
    private JTextField    statusField_ = new JTextField();
    private FiveLogic     gameLogic_ = new FiveLogic(9, 9);
    private boolean       gameOver_ = false;
    private static final Color[]  PLAYER_COLOR = {null, Color.black, Color.white};
    private static final String[] PLAYER_NAME  = {null, "BLACK", "WHITE"};
    //====================================================== constructor
    public FiveGUI() {
        //--- Create some buttons
        JButton newGameButton = new JButton("New Game");
        JButton undoButton = new JButton("Undo");
        //--- Create control panel
        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());
        controlPanel.add(newGameButton);
        controlPanel.add(undoButton);
        //--- Create graphics panel
        boardDisplay_ = new GraphicsPanel();
        //--- Set the layout and add the components
        this.setLayout(new BorderLayout());
        this.add(controlPanel , BorderLayout.NORTH);
        this.add(boardDisplay_, BorderLayout.CENTER);
        this.add(statusField_ , BorderLayout.SOUTH);
        //-- Add action listeners
        newGameButton.addActionListener(new NewGameAction());
            undoButton.addActionListener(new UndoAction());
    }//end constructor
    //////////////////////////////////////////////// class GraphicsPanel
    // This is defined inside the outer class so that
    // it can use the game logic variable.
    class GraphicsPanel extends JPanel implements MouseListener {
        private static final int ROWS = 9;
        private static final int COLS = 9;
        private static final int CELL_SIZE = 30; // Pixels
        private static final int WIDTH  = COLS * CELL_SIZE;
        private static final int HEIGHT = ROWS * CELL_SIZE;
        //================================================== constructor
        public GraphicsPanel() {
            this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
            this.setBackground(Color.gray);
            this.addMouseListener(this);  // Listen own mouse events.
        }//end constructor
        //============================================== paintComponent
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            //-- Paint grid (could be done once and saved).
            for (int r=1; r<ROWS; r++) {  // Horizontal lines
                g.drawLine(0, r*CELL_SIZE, WIDTH, r*CELL_SIZE);
            for (int c=1; c<COLS; c++) {
                g.drawLine(c*CELL_SIZE, 0, c*CELL_SIZE, HEIGHT);
            //-- Draw players pieces.
            for (int r=0; r<ROWS; r++) {
                for (int c=0; c<COLS; c++) {
                    int x = c * CELL_SIZE;
                    int y = r * CELL_SIZE;
                    int who = gameLogic_.getPlayerAt(r, c);
                    if (who != gameLogic_.EMPTY) {
                        g.setColor(PLAYER_COLOR[who]);
                        g.fillOval(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
        }//end paintComponent
        //======================================== listener mousePressed
        public void mousePressed(MouseEvent e) {
            //--- map x,y coordinates into a row and col.
            int col = e.getX()/CELL_SIZE;
            int row = e.getY()/CELL_SIZE;
            int currentOccupant = gameLogic_.getPlayerAt(row, col);
            if (!gameOver_ && currentOccupant == gameLogic_.EMPTY) {
                gameLogic_.move(row, col);
                switch (gameLogic_.getGameStatus()) {
                    case 1: // Player one wins.  Game over.
                            gameOver_ = true;
                            statusField_.setText("BLACK WINS");
                            break;
                    case 2: // Player two wins.  Game over.
                            gameOver_ = true;
                            statusField_.setText("WHITE WINS");
                            break;
                    case FiveLogic.TIE:  // Tie game.  Game over.
                            gameOver_ = true;
                            statusField_.setText("TIE GAME");
                            break;
                    default: showNextPlayer();
            } else {  // Not legal
                Toolkit.getDefaultToolkit().beep();
            this.repaint();  // Show any updates to game.
        }//end mousePressed
        //========================================== ignore these events
        public void mouseClicked (MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered (MouseEvent e) {}
        public void mouseExited  (MouseEvent e) {}
    }//end inner class GraphicsPanel
    //======================================= untility method showNextPlayer
    private void showNextPlayer() {
       statusField_.setText(PLAYER_NAME[gameLogic_.getNextPlayer()] + " to play");
    }//end showNextPlayer
    ///////////////////////////////////////// inner class NewGameAction
    private class NewGameAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            gameLogic_.reset();
            gameOver_ = false;
            showNextPlayer();
            boardDisplay_.repaint();
    }//end inner class NewGameAction
     ///////////////////////////////////////// inner class NewGameAction
    private class UndoAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            gameLogic_.undo();
            gameOver_ = false;
            showNextPlayer();
            boardDisplay_.repaint();
    }//end inner class NewGameAction
}//end class FiveGUI
//================================================
// FiveLogic.java - Game to get 5 pieces in a row.
///////////////////////////////////////////////// class FiveLogic
/** This class implements the logic (model) for the game of
    Five-In-A-Row.
    <br/>Exercise: The undo function doesn't do anything.  Fix it.
    @author Fred Swartz
    @version 2004-05-02
class FiveLogic {
    /** Number of board rows. */
    private int maxRows_;
    /** Number of board columns. */
    private int maxCols_;
    /** The board. */
    private int[][] board_;
      /**The undo array. */
      private int[][] undoArray_;
    /** The player who moves next. */
    private int     nextPlayer_;
    /** Number of moves in the game. */
    private int     moves_ = 0;
    //-- Constants
    public  static final int EMPTY   = 0;  // The cell is empty.
    private static final int PLAYER1 = 1;
    public  static final int TIE     = -1; // Game is a tie (draw).
    //================================================== constructor
    public FiveLogic(int rows, int cols) {
        maxRows_ = rows;
        maxCols_ = cols;
        board_ = new int[maxRows_][maxCols_];
            undoArray_ = new int[maxRows_][maxCols_];
        reset();
    }//end constructor
    //================================================= getNextPlayer
    /** Returns the next player. */
    public int getNextPlayer() {
        return nextPlayer_;
    }//end getFace
    //=================================================== getPlayerAt
    /** Returns player who has played at particular row and column. */
    public int getPlayerAt(int r, int c) {
        return board_[r][c];
    }//end getPlayerAt
    //========================================================== reset
    /** Clears board to initial state. Makes first move in center. */
    public void reset() {
        for (int r=0; r<maxRows_; r++) {
            for (int c=0; c<maxCols_; c++) {
                board_[r][c] = EMPTY;
        moves_ = 0;  // No moves so far.
        nextPlayer_ = PLAYER1; 
        //-- Make first move in center.
        move(maxCols_/2, maxRows_/2);  // First player moves to center
    }//end reset
    //=========================================================== move
    /** Play a marker on the board, record it, flip players. */
    public void move(int r, int c) {
        //assert board_[r][c] == EMPTY;
            undoArray_[r][c] = board_[r][c];
        board_[r][c] = nextPlayer_;  // Record this move.
        nextPlayer_ = 3-nextPlayer_; // Flip players
        moves_++;                    // Increment number of moves.
    }//end move
    //=========================================================== undo
    /** Undo the last move made.  Don't go beyond beginning. */
    public void undo() {
                board_ = undoArray_;
               moves_--;      
    }//end undo
    //========================================== utility method count5_
    /** The count5_ utility function returns true if there are five in
        a row starting at the specified r,c position and
        continuing in the dr direcection (+1, -1) and
        similarly for the column c.
    private boolean count5_(int r, int dr, int c, int dc) {
        int player = board_[r][c];  // remember the player.
        for (int i=1; i<5; i++) {
            if (board_[r+dr*i][c+dc*i] != player) return false;
        return true;  // There were 5 in a row!
    } // count5_
    //=================================================== getGameStatus
    /** -1 = game is tie, 0 = more to play,
         1 = player1 wins, 2 = player2 wins */
    public int getGameStatus() {
        int row;
        int col;
        int n_up, n_right, n_up_right, n_up_left;
        boolean at_least_one_move;   // true if game isn't a tie
        for (row = 0; row < maxRows_; row++) {
            for (col = 0; col < maxCols_; col++) {
                int p = board_[row][col];
                if (p != EMPTY) {
                    // look at 4 kinds of rows of 5
                    //  1. a column going up
                    //  2. a row going to the right
                    //  3. a diagonal up and to the right
                    //  4. a diagonal up and to the left
                    if (row < maxRows_-4) // Look up
                        if (count5_(row, 1, col, 0)) return p;
                    if (col < maxCols_-4) { // row to right
                        if (count5_(row, 0, col, 1))  return p;
                        if (row < maxRows_-4) { // diagonal up to right
                            if (count5_(row, 1, col, 1)) return p;
                    if (col > 3 && row < maxRows_-4) { // diagonal up left
                        if (count5_(row, 1, col, -1)) return p;
                }//endif position wasn't empty
            }//endfor row
        }//endfor col
        // Neither player has won, it's tie if there are empty positions.
        // Game is finished if total moves equals number of positions.
        if (moves_ == maxRows_*maxCols_) {
            return TIE; // Game tied.  No more possible moves.
        } else {
            return 0;  // More to play.
    }//end getGameStatus
}//end class FiveLogic

Oh, oh, oh. I know why it clears the whole board. You are only saving the previous state of each square as a player moves to it. A player can only move to a square if it's empty. So you are only storing empty squares.
Change the move method to do this:
public void move(int r, int c) {
    //assert board_[r][c] == EMPTY;
    undoArray_ = (int[][]) board_.clone();
    board_[r][c] = nextPlayer_; // Record this move.
    nextPlayer_ = 3-nextPlayer_; // Flip players
    moves_++;  // Increment number of moves.
}

Similar Messages

  • HT1451 I've accidentally moved some music into trash, and I can't 'undo' the move out of trash. How do I retrieve my music? please...

    Please add the image directly by clicking Insert Image (camera icon). We cannot accept linked or embedded images. What??

    Davs, 
    When you say "presentation," are you by any chance talking about Power Point?  If so, the music must be in one of the formats that is compatible with Power Point, which includes MP3.
    The files sold in the iTunes Store are in AAC format, which is not compatible with Power Point.  You can convert AAC to MP3 by following this guide:
    http://support.apple.com/kb/PH12367

  • Transform no longer saves last move

    transforms for rotate, reflect and scale no longer read off of the hand transformed objects -- ever since the expansion and focus of the rounded rectangles. transform dialog boxes only interact with itself inside the dialog box, and kick back to fixed amounts. this really sucks, it means I cant refer to what my last transform was in order to record or reapply it except through transform d. what my rotation or scaling was! does not show up in the transform dialog box. this mean I am now dealing in guesswork! illustrator no longer can record your last move except through control d and you'd have to sit down and do the math. am I missing something, this is seriously seriously cutting down my capability for technical control. MOST MOST MOST CONSIDERABLY -- this is a big problem. as a technical drawing program, I need those numbers. 

    Also discovered that it's not possible to turn Cycle mode on or off during recording. Cycle mode can only be turned off in record mode by clicking on the Cycle icon on the transport... but you can't turn it on using this method. (Clicking on the Cycle Range during recording has no effect).
    Very annoying....

  • I had two files named graphics and I replaced one graphics file with another which was the wrong one.  Can I undo my replacement?  I move the wrong one, which was on my desktop into another one and that is when it as me if I wanted to replace the file.

    I accidently replaced a file with another.  Can I undo my action? 
    I had two files named graphics.  One was on my desktop and another was within another file called solitarie.  I move the one on my desktop (wrong file) into the solitarie file and was asked if I wanted to replace the graphics file in the solitarie folder (the correct one).  I said yes accidently and then remembered that I had made a mistake.  If I use undo, it only move the wrong file back to the desktop.  Is there an undo of replace?

    Sorry, but's that's why you get the warning. "Replace" means just that - the new file over-writes the old one. There is no undo.

  • HT1657 I rented a movie on Itunes last night and I watched half of it before falling asleep. Today I tried to open the movie and watch the last half but I cannot find it. It has been less than 24 hours since I rented it. Where can I find the movie?

    I rented a movie on Itunes last night and I watched half of it before falling asleep. Today I tried to open the movie and watch the last half but I cannot find it. It has been less than 24 hours since I rented it. Where can I find the movie?

    I found my answer in another Thread and it worked... so for anyone who needs it, here it is:
    https://discussions.apple.com/message/19134562#19134562
    Had the same problem and spoke with Apple Support. They had me reset the System Management Controller:
    Shut down the computer. With the computer off, on the left hand side of the keyboard press shift+control+option along with the power button simultaneously and release. Wait 5-10 seconds and restart the computer.
    This solved my problem and I was immediately able to purchase, download, and play an HD movie from iTunes w/o any error message.

  • How can I include in my VI actions like "Undo last action/redo last action"?

    I built a Vi and I want to include functions like Undo (last action) and Redo (last action).
    Any suggestion wellcome.
    Thank you

    Hi
    If you have the Menu Bar visible when your VI runs - this Forms your Default VI run-time Menu. You will discover a built in Undo and Redo Functions under "Edit" Menu. This fuction can be added to your custom Menus or .rtm files.
    However, this undo fuctionality is limited to data change only, which means it will erase the last control change. This Undo will not reverse any data propagated as a result of your last control change. Here is an example.
    Say you are taking a continuously polled value of a String control and building a Path using this, and you have a Button that says "Process Path" which ends the polling and brings you out of the While Loop. In this example if you change the value of String Control and Say Undo you will be reverted to Previo
    us Value. However If after changing the Value you Clicked the "Process Path" Button, you will be Out of your While Loop with the Path being built with the Last value of String Control before "ProcessPath" was clicked. Now Clicking Undo tries to Reverse the Last Control Which was "Process Path" This has no effect on Path Value. The Undo Function will not reverse the Data which has Propagated and take you backwards in the diagram. It will simply reverse the Data Changed on the last Control.
    Therefore if you want a robust "Undo" and "Redo" you will have to program this functionality, Basically you will have to trap values of all controls and on data change remember these values. On Undo you can then Change the values of Controls back to Previous Value and Also take your Diagram back to Where the Last action had impacted any data propagation.
    All this - mind you - is for a single level undo. It will get complex to do Multiple Level Undo.
    Good Luck! Dont you wish, you could Just
    Undo the Computer Age?!!
    Mache
    Good Luck!
    Mache

  • I don't have back up since last august but I accidentally delete the message recently. How can I undo that mess back ?

    I don't have back up since last august but I accidentally delete the message recently.  How can I undo that message back ?

    If you haven't backed up to either your computer or iCloud, you can't get the message back. Let this be a lesson to either back your phone up to your computer or to iCloud (or both) regularly.

  • What tool can I insert in tool box to undo last stroke and return to where I previously left off, e.g., when I am writing an e=mail and part of the message is deleted--so I don't have to re-write the whole message again?

    what tool can I insert in tool box to undo last stroke and return to where I previously left off, e.g., when I am writing an e=mail and part of the message is deleted--so I don't have to re-write the whole message again?

    Firefox doesn't do email, it's a web browser.
    If you are using Firefox to access web mail, you need to seek support from your service provider or a forum for that service.
    If your problem is with Thunderbird, see this forum for support.
    [http://www.mozillamessaging.com/en-US/support/]
    or this one
    [http://forums.mozillazine.org/viewforum.php?f=39]

  • HT204370 where can I find the movies I rented and downloaded last night

    i downloaded 2 movies to watch on flight, downloaded to computer.  Now have iPad with me.  I don't see the movies in library/anywhere in iTunes/cloud so tried to re-download, received message that I had already rented.  where can I find the movies?

    If you rented and downloaded them on your computer's iTunes then did you then connect the iPad to your computer and move them over to it ? If you did then they should be in the Videos app.
    Rentals are a one-time only download so they won't appear in the cloud for re-downloading.

  • I recently brought a new HP laptop and I downloaded the newly updated iTunes on it; however I have an old Aver laptop with iTunes version 10.7 on it or the one before iTunes 11 came out. How can I transfer my movies from the old version to the new one?

    I recently brought a new HP laptop and downloaded iTunes 11 on it. My old laptop which is a Acer has iTunes version 10.7, I believe. I wanted to know, How can I transfer 18 movies from the old iTunes onto my new Itunes? It only shows the most recent two movies when I look at the purchases in my account. I had a lot of moves downloaded last year from the old version and would like some assistance on how to get all those movies into my iTunes 11 library. Thank you.

    you should starting with copying the iTunes folder from your old laptop to the new one.
    the iTunes folder is in your user profile Music folder.
    it should go to the same location on the new laptop.
    Provided that you have your media, music and movies in the default location, and you sign in to your apple ID and authorize your new computer (all in iTunes)
    you should have all intact.
    Post if any problems.

  • How can I undo an add-on settings sync?

    I use Firefox Sync. As far as I can tell, bookmarks synced well. Tabs didn’t but that’s probably due to having opened to many on my main machine. Also add-ons synced i. e. the Firefox on a Ubuntu laptop now has all the add-ons that my home computer Firefox has. Unfortunately, the sync reset all of the settings in some add-ons. So, for example, in LeechBlock the list of websites that I’d like to block, the schedule and all the rules are gone. How can I undo the last sync? Or is there a way to make my main computer the master in all syncs?

    The prefs that are set by an extension are usually not included in the Sync, so you get the default setting if you sync an extension from one computer to another.
    Only prefs that have a corresponding services.sync.prefs.sync.* pref that is set to true will be synced to other devices.
    If you want to sync additional prefs then you can create a corresponding Boolean sync pref yourself and set the value to true.
    * services.sync.prefs.sync. (with the pref name appended no space after the last dot)
    *http://kb.mozillazine.org/about:config

  • My iphone 4s is literally frozen when I try to do anything to it, since the ios 8 download yesterday.  Can I undo the download and go back?

    I downloaded the ios8 last night and ever since, everything from making a call to checking facebook or text is freezing up my phone!  The time even stops on it!! Can I undo this update and go back because this is making my phone useless?

    i am sorry to say but there is no way to undo a software update to go back you have to go threw your phone provider and have then do a replacement on the phone and just not do the update. when they receive the phone they will send it off for testing and to have the bugs fixed 

  • How to calculate the days between last movement of material till today date

    Hello Experts,
    Could someone help me please?
    I have a key figure in the InfoCube 0IC_C03 witch contain the last date of movement of material.
    (it is a key figure created in format date and contain the max value).
    How can I to calculate the number of days between this date (last movement),  till today date (system date).
    I need to show:
    material........last movement.....days without movements.
    xxxxxxxxxxx.....dd/mm/yyyy..........9999
    Im trying to do this calculation in bex using variable formula but it doesn't work becouse current date (customer exit) brings sy-datum in format yyyymmdd and the kf-last-mov is in format number (I dont know what kind of number)
    Thanks in advance,
    Points are assured.
    Regards,
    Silvio Meurer.
    Message was edited by:
            Silvio Meurer

    Hi Parth,
    Here we are using the version 7.0 and SP 10, I'm afraid I could not understand you. I Can't find the function DATE_DIFF (Where is it?)
    I'm using the formula and it doesn't work. Coud you see the result is:
    last movement date     Today date        result
    02.04.2007                  20.070.625       19.337.856
    18.05.2007                  20.070.625       19.337.810
    the "today date" is from customer exit and the result is a strange number to me.
    Could you help me?

  • Hello..Does anyone in this community know what the following error code indicates   0x8002006E   I was trying to burn a DVD from files in a burn folder. They were pictures from my Nikon camera. I can play videos and movies from the same dvd player.

    I was trying to burn a DVD from files in a burn folder. They were pictures from my Nikon camera. I can play videos and movies from the same dvd player.    Thanks for any help you can offer,

    Thanks for your reply:
    I did find an error log related to the error code and tried all suggestions on the list of recommendations, still no luck            
    I definitely am running OS X10.5.8 (hopefully will be updating later on this month)
    I tried several brand new discs from the same box, still no luck.
    My last option is to go out and try a different brand, guess I'll go with Verbatim this time but I think I'll poke around some more before buying 20 more new discs.

  • Trouble with curves + trackpad, can't undo

    When I try to adjust the curves of a layer with a vector mask using my trackpad (clicking with my thumb, and moving the cursor with my pointer finger) something other than the curves changes. I know it is not curves because 1) it is applied whether I click apply or cancel in the curves window and 2) whatever this thing is, I can't undo it with command-Z or the history pane. It's not the blneding mode, opacity or fill that has changed. I'm assuming it has to do with some sort of gesture I don't mean to be doing. I have been able to adjust other layers with regular raster mask just fine. It seems to happen when I move the curve point up and then back down on the same click. The layers I've had this happen on are also using a lower layer as a clipping mask. This is a real problem because the only way to fix it is to revert to a saved version before this happened.

    Your IT Administrator must turn on ActiveSync on your corporate server before the account can be added.  Talk to them about this.

Maybe you are looking for

  • Forcing the disk cache to be written to disk

    Hi all. We are looking for a way to insure the content of the icommon in the ufs on disk as we need to read it. However, calling sync is async and does not seem to provide what we're looking for. When a file is updated, created all the information is

  • How to save a favourite radio station in Apple TV?

    How do I save a radio station to my favourites in Apple TV?

  • To switch or not to switch.

    Hi all ... I've been using Word (Mac) for a long time. I like a lot of the features and templates in Pages. My question is: "If I create my work in Pages, will my clients (many who are oriented to Word) be able to see, work with, and edit my pages do

  • Combo box with a little twist?

    Hi everyone, Umm, i want to make a some drop boxes or combo boxes where if the user choose some option, than in the next combo boxes that option will not appear. Can I do that? How? Thanks for the help, sorry if this question had been asked, and espe

  • How to use OfficeControl

    Hello All, I followed the tutorial about how to use OfficeControl. Very simple Example. <a href="http://help.sap.com/saphelp_nw2004s/helpdata/en/ef/3483789514b748b6fe1f145e9685ab/frameset.htm">Using OfficeControl</a> But on runtime I just see white s