Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 22 of 22

Thread: isValidMove Method

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default isValidMove Method

    I need help with the isValidMove Method for my pawn piece. How do I code pawns first move of 2 squares then 1 sqaure after that .
    /**
     * A player of a chess game.
     *
     * @author Zachary Kurmas
     */
    public enum Player {
       BLACK, WHITE;
     
       /**
        * Return the {@code Player} whose turn is next.
        *
        * @return the {@code Player} whose turn is next
        */
       public Player next() {
          return this == BLACK ? WHITE : BLACK;
       }
    }
    public class Move {
     
       public int fromRow, fromColumn, toRow, toColumn;
     
       public Move(int fromRow, int fromColumn, int toRow, int toColumn) {
          this.fromRow = fromRow;
          this.fromColumn = fromColumn;
          this.toRow = toRow;
          this.toColumn = toColumn;
       }
    }
    public class Pawn extends ChessPiece {
     
    	protected Pawn(Player player) {
    		super(player);
     
    	}
    	public String type(){
    		return "Pawn";
    	}
    	public boolean isValidMove(Move move, IChessPiece[][] board){
    		if(super.isValidMove(move, board) == false){
    			return false;
    		}
    		if (move.toRow != move.fromRow+1){
    			return false;
     
    		}
     
     
     
    	}
     
    }
     
     
     
     
     
    public abstract  class  ChessPiece implements IChessPiece {
    	/**  */
    	private Player owner;
     
     
    	 /**
    	    * Return the player that owns this piece.
    	    *
    	    * @return the player that owns this piece.
    	    */
    	protected ChessPiece(Player player) {
    		this.owner = player;
     
    	}
     
    //	public abstract String type()
     
    	/* (non-Javadoc)
    	 * @see chess.IChessPiece#player()
    	 */
    	@Override
    	public Player player() {
    		if (owner == Player.BLACK) {
    			return owner;
    		}
    		if (owner == Player.WHITE) {
    			return owner;
    		} else
    			return null;
     
    	}
     
     
    	/*
    	 * (non-Javadoc)
    	 * 
    	 * @see chess.IChessPiece#isValidMove(chess.Move, chess.IChessPiece[][])
    	 */
    	@Override
    	public boolean isValidMove(Move move, IChessPiece[][] board) {
    		if (move.toRow == move.fromRow && move.fromColumn == move.toColumn) {
    			return false;
    		}
     
    		IChessPiece firstPiece = board[move.toRow][move.toColumn];
    		IChessPiece secondPiece = board[move.fromRow][move.fromColumn];
    		 if( firstPiece != null && firstPiece == secondPiece ){
    			 return false;
    		 }
    		 else
    			return board[move.fromRow][move.fromColumn].equals(this.owner);
     
    	}
     
     
     
     
    	public abstract String type();
    }
    public interface IChessPiece {
     
       /**
        * Return the player that owns this piece.
        *
        * @return the player that owns this piece.
        */
       Player player();
     
       /**
        * Return the type of this piece ("King", "Queen", "Rook", etc.).  Note:  In this case "type" refers to the game
        * of chess, not the type of the Java class.
        *
        * @return the type of this piece
        */
       String type();
     
       /**
        * Returns whether the piece at location {@code [move.fromRow, move.fromColumn]} is allowed to move to location
        * {@code [move.fromRow, move.fromColumn]}.
        *
        * Note:  Pieces don't store their own location (because doing so would be redundant).  Therefore,
        * the {@code [move.fromRow, move.fromColumn]} component of {@code move} is necessary.
        * {@code this} object must be the piece at location {@code [move.fromRow, move.fromColumn]}.
        * (This method makes no sense otherwise.)
        *
        * @param move  a {@link Move} object describing the move to be made.
        * @param board the {@link ChessBoard} in which this piece resides.
        * @return {@code true} if the proposed move is valid, {@code false} otherwise.
        * @throws IndexOutOfBoundsException if either {@code [move.fromRow, move.fromColumn]} or {@code [move.toRow,
        *                                   move.toColumn]} don't represent valid locations on the board.
        * @throws IllegalArgumentException  if {@code this} object isn't the piece at location {@code [move.fromRow, move.fromColumn]}.
        */
       boolean isValidMove(Move move, IChessPiece[][] board);
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    Can you determine if its the first move and allow 2 squares if so?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    Quote Originally Posted by Norm View Post
    Can you determine if its the first move and allow 2 squares if so?
    Yes that is what I am asking.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    Have a variable like a boolean that says if this is the first move or not.
    Initialize it as true and set it false when the first move is made.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    Quote Originally Posted by Norm View Post
    Have a variable like a boolean that says if this is the first move or not.
    Initialize it as true and set it false when the first move is made.
    How do I actually code the move using this method public boolean isValidMove(Move move, IChessPiece[][] board){
    }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    Can you explain where you are having a problem with the code? Ask a specific question about it.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    I need to make sure a movement with the pawn is valid. So if I do something like if(move.toRow == move.fromRow){
    return false;
    }
    So how do I only allow the pawn to move 1 spot forward and not allow it to move backwards.
    For example this is from the parent class ChessPiece which all piece have to follow this rule.
    if (move.toRow == move.fromRow && move.fromColumn == move.toColumn) {
    return false;
    }

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    how do I only allow the pawn to move 1 spot forward
    Define which way is forward and then test if the move is in that direction. The near pieces move away from you, the far pieces move towards you.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    This is what i have done so far. Going to have to make some more changes.

    public boolean isValidMove(Move move, IChessPiece[][] board) {
    		if (super.isValidMove(move, board) == false) {
    			return false;
    		}
     
     
    		if (firstmove = true) {
    			if (player == Player.BLACK) {
    				if (move.toRow == move.fromRow - 1
    						&& move.fromColumn != move.toColumn) {
    					return false;
    				}
    				if (move.toRow > move.fromRow + 2
    						&& move.fromColumn != move.toColumn) {
    					return false;
    				}
     
    				if (player == Player.WHITE) {
    					if (move.toRow == move.fromRow + 1
    							&& move.fromColumn != move.toColumn) {
    						return false;
    					}
    					if (move.toRow < move.fromRow - 2
    							&& move.fromColumn != move.toColumn) {
    						return false;
    					}
    				}
    			}
     
    			if (firstmove = false) {
    				if (player == Player.BLACK) {
    					if (move.toRow == move.fromRow - 1
    							&& move.fromColumn != move.toColumn) {
    						return false;
    					}
    				}
    				if (player == Player.WHITE) {
    					if (move.toRow == move.fromRow + 1
    							&& move.fromColumn != move.toColumn) {
    						return false;
    					}
    				}
    			}
    		}
     
    			return true;
     
     
    	}

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    Do you have a question?

    One problem I see is the use of an assignment operator (=) instead of an equality test operator(==)
    Testing a boolean variable for equal to true is redundant. Its value is true or false and can be used directly:
       if(firstMove) {


    There is a lot of repeated code there. The use of a signed value for the move direction would reduce the amount of code.
      int moveDir =  //  set to 1 or -1 depending on direction of move
     
       ..  row + moveDir  //  either adds 1 or subtracts one depending on sign of moveDir
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    ok I have no questions for now, but i might later. Thanks for the help.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    I added some comments after first post.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    Did I use it right?
    public class Pawn extends ChessPiece {
    	private Player player;
    	private boolean firstmove;
     
    	protected Pawn(Player player) {
    		super(player);
    		boolean firstmove = true;
     
    	}
     
    	@Override
    	public String type() {
    		// TODO Auto-generated method stub
    		return "Pawn";
    	}
     
    	public boolean isValidMove(Move move, IChessPiece[][] board) {
    		if (super.isValidMove(move, board) == false) {
    			return false;
    		}
     
     
    		int dy = player ==  Player.WHITE ? -1 : 1;
     
     
    		if (firstmove) {
     
    				if (move.toRow == move.fromRow - dy
    						&& move.fromColumn != move.toColumn) {
    					return false;
    				}
    				if (move.toRow > move.fromRow - dy -dy
    						&& move.fromColumn != move.toColumn) {
    					return false;
    				}
    		}
    		else{
    			    if (move.toRow == move.fromRow - dy
    							&& move.fromColumn != move.toColumn) {
    						return false;
    					}
    		}
     
     
     
     
     
     
    			return true;
     
     
    	}
    }

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    Does it work when compiled and executed? Does it return the right results?


    It looks better.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    Can some one help me find a way so that when i click on a button is marks that as clicked so i can click on another button and move the piece.
    public class ButtonListener implements ActionListener {
     
    		public void actionPerformed(ActionEvent event) {
    			for (int row = 0; row < 8; row++) {
    				for (int col = 0; col < 8; col++) {
    					if (board[row][col] == event.getSource()) {         
     
    				}
    			}
    			displayBoard();
    		}
     
    	}
    package chess;
     
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.LayoutManager;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
     
    public class ChessPanel extends JPanel {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	private JButton[][] board;
     
    	private ChessModel model;
    	private JButton quitButton;
    	private IChessPiece p;
    	private ButtonListener buttonListener = new ButtonListener();
    	private Player player;
    	private ImageIcon emptyIcon;
     
    	private JPanel middlePanel;
    	private ImageIcon bpawn;
    	private ImageIcon wpawn;
    	private ImageIcon bking;
    	private ImageIcon wking;
    	private ImageIcon bqueen;
    	private ImageIcon wqueen;
    	private ImageIcon bknight;
    	private ImageIcon wknight;
    	private ImageIcon brook;
    	private ImageIcon wrook;
    	private ImageIcon bbishop;
    	private ImageIcon wbishop;
     
    	public ChessPanel(Player player) {
    		model = new ChessModel(player);
    		player = Player.BLACK;
     
    		setLayout(new BorderLayout());
    		emptyIcon = new ImageIcon("empty.jpg");
    		bpawn = new ImageIcon("blackpawn.jpg");
    		wpawn = new ImageIcon("whitepawn.jpg");
    		bking = new ImageIcon("blackking.jpg");
    		wking = new ImageIcon("whiteking.jpg");
    		bqueen = new ImageIcon("blackqueen.jpg");
    		wqueen = new ImageIcon("whitequeen.jpg");
    		bknight = new ImageIcon("blackknight.jpg");
    		wknight = new ImageIcon("whiteknight.jpg");
    		brook = new ImageIcon("blackrook.jpg");
    		wrook = new ImageIcon("whiterook.jpg");
    		bbishop = new ImageIcon("blackbishop.jpg");
    		wbishop = new ImageIcon("whitebishop.jpg");
    		middlePanel = BoardPanel();
    		add(middlePanel);
    		setBackground(Color.cyan);
     
    	}
     
    	private JPanel BoardPanel() {
    		JPanel panel = new JPanel();
    		panel.setLayout(new GridLayout(8, 8));
     
    		ButtonListener listener = new ButtonListener();
     
    		board = new JButton[8][8];
     
    		for (int row = 0; row < 8; row++) {
    			for (int col = 0; col < 8; col++) {
    				board[2][col] = new JButton("", emptyIcon);
    				board[3][col] = new JButton("", emptyIcon);
    				board[4][col] = new JButton("", emptyIcon);
    				board[5][col] = new JButton("", emptyIcon);
    				board[6][col] = new JButton("", emptyIcon);
     
    				board[6][col] = new JButton("", bpawn);
    				board[7][0] = new JButton("", brook);
    				board[7][1] = new JButton("", bknight);
    				board[7][2] = new JButton("", bbishop);
    				board[7][3] = new JButton("", bking);
    				board[7][4] = new JButton("", bqueen);
    				board[7][5] = new JButton("", bbishop);
    				board[7][6] = new JButton("", bknight);
    				board[7][7] = new JButton("", brook);
     
    				board[1][col] = new JButton("", wpawn);
    				board[0][0] = new JButton("", wrook);
    				board[0][1] = new JButton("", wknight);
    				board[0][2] = new JButton("", wbishop);
    				board[0][3] = new JButton("", wking);
    				board[0][4] = new JButton("", wqueen);
    				board[0][5] = new JButton("", wbishop);
    				board[0][6] = new JButton("", wknight);
    				board[0][7] = new JButton("", wrook);
     
    				board[row][col].addActionListener(listener);
    				panel.add(board[row][col]);
    			}
    		}
     
    		// for (int i = 1; i <= 2; i++) {
    		// row = p.player() == Player.BLACK ? 0 : 8;
    		//
    		// for (col = 1; col <= 8; col++) {
    		//
    		// switch (col) {
    		// case 1: case 8:
    		// Square[row][col]= new JLabel("Rook", JLabel.CENTER);
    		// break;
    		// case 2: case 7:
    		// Square[row][col]= new JLabel("Kinght", JLabel.CENTER);
    		// break;
    		// case 3: case 6:
    		// Square[row][col]= new JLabel("Bishop", JLabel.CENTER);;
    		// break;
    		// case 4:
    		// Square[row][col]= new JLabel("Queen", JLabel.CENTER);
    		// break;
    		// case 5:
    		// Square[row][col]= new JLabel("King", JLabel.CENTER);
    		// break;
    		// }
    		// }
    		// }
     
    		return panel;
    	}
     
    	private void displayBoard() {
     
    		for (int row = 0; row < 8; row++) {
    			for (int col = 0; col < 8; col++) {
     
    				if (player == null) {
    					board[row][col].setIcon(emptyIcon);
    				}
    				if (player == Player.BLACK) {
    					if (model.pieceAt(row, col) instanceof Pawn) {
    						board[row][col].setIcon(bpawn);
    					}
     
     
    					if (model.pieceAt(row, col) instanceof Knight) {
    						board[row][col].setIcon(bknight);
    					}
     
     
    					if (model.pieceAt(row, col) instanceof King) {
    						board[row][col].setIcon(bking);
    					}
     
     
    					if (model.pieceAt(row, col) instanceof Queen) {
    						board[row][col].setIcon(bqueen);
    					}
    					if (model.pieceAt(row, col) instanceof Rook) {
    						board[row][col].setIcon(brook);
    					}
     
     
    					if (model.pieceAt(row, col) instanceof Bishop) {
    						board[row][col].setIcon(bbishop);
    					}
    				}
    				if (player == Player.WHITE) {
    					if (model.pieceAt(row, col) instanceof Pawn) {
    						board[row][col].setIcon(wpawn);
     
    					}
    					if (model.pieceAt(row, col) instanceof Knight) {
    						board[row][col].setIcon(wknight);
    					}
     
     
    					if (model.pieceAt(row, col) instanceof King) {
    						board[row][col].setIcon(wking);
    					}
     
     
    					if (model.pieceAt(row, col) instanceof Queen) {
    						board[row][col].setIcon(wqueen);
    					}
    					if (model.pieceAt(row, col) instanceof Rook) {
    						board[row][col].setIcon(wrook);
    					}
     
     
    					if (model.pieceAt(row, col) instanceof Bishop) {
    						board[row][col].setIcon(wbishop);
    					}
    				}
    			}
    		}
    	}
     
    	public class ButtonListener implements ActionListener {
     
    		public void actionPerformed(ActionEvent event) {
    			for (int row = 0; row < 8; row++) {
    				for (int col = 0; col < 8; col++) {
    					if (board[row][col] == event.getSource()) {         
     
    				}
    			}
    			displayBoard();
    		}
     
    	}
    }

    package chess;
     
     
     
    public class ChessModel implements IChessModel {
     
    	private IChessPiece[][] board;
    	private Player player;
     
    	public ChessModel(Player owner) {
    		board = new IChessPiece[8][8];
    		player = owner;
    	}
     
    	@Override
    	public boolean isComplete() {
    		// TODO Auto-generated method stub
    		return false;
    	}
     
     
    	@Override
    	public boolean isValidMove(Move move) {
    		IChessPiece piece = pieceAt(move.fromRow, move.fromColumn);
    		return piece != null && piece.isValidMove(move, board);
    	}
     
    	@Override
    	public void move(Move move) {
    		move(move);
    		player = currentPlayer().next();
    	}
     
    	@Override
    	public boolean inCheck() {
    		// TODO Auto-generated method stub
    		return false;
    	}
     
    	@Override
    	public Player currentPlayer() {
     
    		return player;
    	}
     
     
    	@Override
    	public IChessPiece pieceAt(int row, int column) {
     
    		return board[row][column];
     
    	}
     
    }

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    button is marks that as clicked
    Do you want to disable the button that was clicked on so it can't send any more events?
    If you cast the object returned by getSource() to a button, you can call the button's methods.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    I need to be able to click a first button then a second to move the chess piece. I need to call the isvaildmove and move method from my Model. I don't it will be necessary to disable the button since if fromRow and fromColumn = toRow and toColumn the isValid Method will return false.
    This is my Move class
     
    public class Move {
     
       public int fromRow, fromColumn, toRow, toColumn;
     
       public Move(int fromRow, int fromColumn, int toRow, int toColumn) {
          this.fromRow = fromRow;
          this.fromColumn = fromColumn;
          this.toRow = toRow;
          this.toColumn = toColumn;
       }
    }

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    find a way so that when i click on a button is marks that as clicked
    Can you explain what you want to do with the button that is clicked?
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    I just need the values of row and col at board[row][col] so move.fromRow = row and move.fromColumn= col. Then I need to be able to click a second button so at board[row][col] move.toRow = row and move.toColumn.

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    I just need the values of row and col
    Do you want to have the button contain the row and col values?
    A couple of ways to do that.
    1)Extent the JButton class with your class that can contain the row and col values that you can get from the object by using the value returned by getSource().
    2)Use the JComponent class's client property methods to store and retrieve the row and col values.
    3)Search the array for a reference that matches what is returned by getSource()
    If you don't understand my answer, don't ignore it, ask a question.

  21. #21
    Junior Member
    Join Date
    Feb 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: isValidMove Method

    How do I now make it so that I can click on a second button and store its values without storing the values of the first button again.

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,912
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: isValidMove Method

    click on a second button and store its values
    In the action listener for the button, the getSource() method will return a reference to the button that was clicked so you can get its values.

    without storing the values of the first button again.
    I don't understand this part. There is only one button reference returned by the getSource() method. The code won't get a reference to the previous button.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 1
    Last Post: January 23rd, 2013, 07:29 AM
  2. [SOLVED] How to create a Java generic method, similar to a C++ template method?
    By Sharmeen in forum Object Oriented Programming
    Replies: 3
    Last Post: October 18th, 2012, 03:33 AM
  3. Replies: 3
    Last Post: October 31st, 2011, 01:42 AM
  4. Help with toString method and an addObject method?
    By Camisado in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 12th, 2011, 07:00 AM
  5. Can i call init() method in destroy method.?
    By muralidhar in forum Java Servlet
    Replies: 1
    Last Post: October 22nd, 2010, 12:18 PM