Results 1 to 5 of 5
  1. #1
    danborgir is offline Member
    Join Date
    Jan 2011
    Posts
    26
    Rep Power
    0

    Default Chess rules method

    Hi guys,



    Recently I've posted quite a few threads about a chess game I am producing for a project at Uni. I am now onto what seems the hardest part of the game - the piece rules.

    The game knows what each piece is - where it starts and if moved where the pieces location is after moving. Now I need to feed through a method whether the move is valid (move) else if not (return to original position).

    So far my code for the game layout and movement methods are:

    Java Code:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
     
    public class ChessGame extends JFrame implements MouseListener, MouseMotionListener {
        JLayeredPane layeredPane;
        JPanel chessBoard;
        JLabel chessPiece;
        int xAdjustment;
        int yAdjustment;
    	int posFrom;
    	Pieces boardPieces = new Pieces();
    	
    	
    
    	
     
        public ChessGame(){
    	
    		
            Dimension boardSize = new Dimension(600, 600);
     
            //  Use a Layered Pane for this this application
     
            layeredPane = new JLayeredPane();
            getContentPane().add(layeredPane);
            layeredPane.setPreferredSize(boardSize);
            layeredPane.addMouseListener(this);
            layeredPane.addMouseMotionListener(this);
    
    		
    		
    		
            //Add a chess board to the Layered Pane 
     
             chessBoard = new JPanel();
            layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
            chessBoard.setLayout( new GridLayout(8, 8) );
            chessBoard.setPreferredSize( boardSize );
            chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
    		
    		Color Green = new Color(119,170,119);
    		Color Cream = new Color(250,235,215);
     
            for (int i = 0; i < 64; i++) {
                JPanel square = new JPanel( new BorderLayout() );
                chessBoard.add( square );
     
                int row = (i / 8) % 2;
                if (row == 0)
                    square.setBackground( i % 2 == 0 ? Green : Cream );
                else
                    square.setBackground( i % 2 == 0 ? Cream : Green );
            }
    		
    		
    		/** Pieces for the board */
    		
    		//  Image String array - TOP ROWS
    
    	   String[] ImageArray_TOP = new String[16];
    
    	   ImageArray_TOP[0] = "pieces/top/1brook.gif";
    	   ImageArray_TOP[1] = "pieces/top/1bknight.gif";
    	   ImageArray_TOP[2] = "pieces/top/1bbishop.gif";
    	   ImageArray_TOP[3] = "pieces/top/1bqueen.gif";
    	   ImageArray_TOP[4] = "pieces/top/1bking.gif";
    	   ImageArray_TOP[5] = "pieces/top/1bbishop.gif";
    	   ImageArray_TOP[6] = "pieces/top/1bknight.gif";
    	   ImageArray_TOP[7] = "pieces/top/1brook.gif";
    	   
    	   ImageArray_TOP[8] = "pieces/top/1bpawn.gif";
    	   ImageArray_TOP[9] = "pieces/top/1bpawn.gif";
    	   ImageArray_TOP[10] = "pieces/top/1bpawn.gif";
    	   ImageArray_TOP[11] = "pieces/top/1bpawn.gif";
    	   ImageArray_TOP[12] = "pieces/top/1bpawn.gif";
    	   ImageArray_TOP[13] = "pieces/top/1bpawn.gif";
    	   ImageArray_TOP[14] = "pieces/top/1bpawn.gif";
    	   ImageArray_TOP[15] = "pieces/top/1bpawn.gif";
    	   
    	   // Image String Array - BOTTOM ROWS
    	 
    	   	String[] ImageArray_BOTTOM = new String[16];
    		
    	   ImageArray_BOTTOM[0] = "pieces/bottom/rpawn.gif";	
    	   ImageArray_BOTTOM[1] = "pieces/bottom/rpawn.gif";
    	   ImageArray_BOTTOM[2] = "pieces/bottom/rpawn.gif";
    	   ImageArray_BOTTOM[3] = "pieces/bottom/rpawn.gif";
    	   ImageArray_BOTTOM[4] = "pieces/bottom/rpawn.gif";
    	   ImageArray_BOTTOM[5] = "pieces/bottom/rpawn.gif";
    	   ImageArray_BOTTOM[6] = "pieces/bottom/rpawn.gif";
    	   ImageArray_BOTTOM[7] = "pieces/bottom/rpawn.gif";
    
    	   ImageArray_BOTTOM[8] = "pieces/bottom/rrook.gif";
    	   ImageArray_BOTTOM[9] = "pieces/bottom/rknight.gif";
    	   ImageArray_BOTTOM[10] = "pieces/bottom/rbishop.gif";
    	   ImageArray_BOTTOM[11] = "pieces/bottom/rqueen.gif";
    	   ImageArray_BOTTOM[12] = "pieces/bottom/rking.gif";
    	   ImageArray_BOTTOM[13] = "pieces/bottom/rbishop.gif";
    	   ImageArray_BOTTOM[14] = "pieces/bottom/rknight.gif";
    	   ImageArray_BOTTOM[15] = "pieces/bottom/rrook.gif";	
    		
            // Add pieces to the board (TOP)
    		
    		for( int i = 0; i < 16; i++) { 
    		
            JLabel piece = new JLabel( new ImageIcon(ImageArray_TOP[i]) );
            JPanel panel = (JPanel)chessBoard.getComponent(i);
            panel.add(piece);
            
    		}
    		
    		// Add pieces to the board (BOTTOM)
    		int inc = 48;
    		for( int j = 0; j < 16; j++, inc++) { 
    		
            JLabel piece = new JLabel( new ImageIcon(ImageArray_BOTTOM[j]) );
            JPanel panel = (JPanel)chessBoard.getComponent(inc);
            panel.add(piece);
            
    		}
    		
        }
    	
    	
     // ************** changed by ioannis **************************
        public void mousePressed(MouseEvent e){
    	
    		
            chessPiece = null;
            Component c =  chessBoard.findComponentAt(e.getX(), e.getY());
    		
    		int X = e.getX();
    		int Y = e.getY();
    		
    		int column = X;
    		int row = Y;
    		
    		// ************** changed by ioannis **************************
    		posFrom = boardPieces.workoutloc(X, Y,'p');
    		
    		System.out.println("the piece location is: "+posFrom);
    		// ************** changed by ioannis **************************
            if (c instanceof JPanel) 
    			return;
    		
    		
            Point parentLocation = c.getParent().getLocation();
            xAdjustment = parentLocation.x - e.getX();
            yAdjustment = parentLocation.y - e.getY();
            chessPiece = (JLabel)c;
            chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
            chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
            layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
    		
       }
        //Move the chess piece around
       
        public void mouseDragged(MouseEvent me) {
            if (chessPiece == null) return;
    		
    		
            chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment); 
    		 
        }
      
      //Drop the chess piece back onto the chess board
     
     // ************** changed by ioannis **************************
        public void mouseReleased(MouseEvent e) {
    	
    		
    		
            if(chessPiece == null) return;
    		
            chessPiece.setVisible(false);
    		Component c =  chessBoard.findComponentAt(e.getX(), e.getY());
    		
            if (c instanceof JLabel){
    		
                Container parent = c.getParent();
                parent.remove(0);
                parent.add( chessPiece );
            } 
            else {
                Container parent = (Container)c;
                parent.add( chessPiece );
            }
     
            chessPiece.setVisible(true); 
    		
    		// ************** changed by ioannis **************************
    		// to track the movement of the piece and actually change its position on the pseudoboard too
    		int X = e.getX();
    		int Y = e.getY();
    		int pos=boardPieces.workoutloc(X, Y,'r');
    		boardPieces.trackMove(posFrom,pos);
    		System.out.println("the drop piece location is: "+pos);
    		// ************** changed by ioannis **************************
        }
     
        public void mouseClicked(MouseEvent e) {
    	
        }
        public void mouseMoved(MouseEvent e) {
       }
        public void mouseEntered(MouseEvent e){
    	
        }
        public void mouseExited(MouseEvent e) {
    	
        }
     
        public static void main(String[] args) {
            JFrame frame = new ChessGame();
    		
    	
    		JMenuBar MenuBar = new JMenuBar();
    		JMenu File = new JMenu("File" );	
    		JMenu Help = new JMenu( "Help" );
    		MenuBar.add( File );
    		MenuBar.add( Help );
    
    		JMenuItem newGame = new JMenuItem( "New Game" );
    		JMenuItem exit = new JMenuItem( "Exit" );
    		File.add( newGame );
    		File.add( exit );
    		
    		JMenuItem HelpInfo = new JMenuItem( "How to play chess" );
    		JMenuItem About = new JMenuItem( "About" );
    		JMenuItem MoveHistory = new JMenuItem( "Move History" );
    		JMenuItem multiplayerClick = new JMenuItem( "Network Play" );
    
    		
    		Help.add( HelpInfo );
    		Help.add( MoveHistory );
    		Help.add( About );
    		Help.add( multiplayerClick );
    		
    		
    		// ActionListeners for items
    		
    		// EXIT PROGRAM
    		
    		ActionListener ExitGame = new ActionListener() {
    			public void actionPerformed( ActionEvent actionEvent ) {
    				System.exit(0);
    			}	
    		};
    		
    		// NEW GAME
    		
    		ActionListener newGameAction = new ActionListener() {
    			public void actionPerformed( ActionEvent actionEvent ) {
    				
    				// SOMETHING
    				
    			}
    		};	
    		
    		// HOW TO PLAY
    		
    		ActionListener HowToPlay = new ActionListener() {
    			public void actionPerformed( ActionEvent actionEvent ) {
    				String url = "http://www.chess.com/learn-how-to-play-chess.html"; 
    		try	{
    			java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
    				} catch (IOException ex) { 
    					System.err.println(); }
    			
    			}
    		};	
    		
    		// MOVE HISTORY
    		
    		ActionListener moveHistory = new ActionListener() {
    			public void actionPerformed( ActionEvent actionEvent ) {
    			
    			
    			MoveHistoryText textBox = new MoveHistoryText();
    		//	HistoryOfMoves test = new HistoryOfMoves();
    			
    			}
    		};	
    		
    		// MULTIPLAYER
    		
    		ActionListener multiPlayerAction = new ActionListener() {
    			public void actionPerformed( ActionEvent actionEvent ) {
    				
    				
    				Object[] possibleValues = { "Client", "Server" };
    				Object selectedValue = JOptionPane.showInputDialog(null, "Are you connecting as Client or Server?", "Network Play", JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]);
    				
    				if(selectedValue == "Client") {
    				new networkConnect();
    				} else {
    				Thread thread = new SimpleServer();
    				thread.start();
    				}
    				
    			}
    		};	
    		
    		
    		// ADD LISTENERS
    		
    		exit.addActionListener( ExitGame );
    		newGame.addActionListener( newGameAction );
    		HelpInfo.addActionListener( HowToPlay );
    		MoveHistory.addActionListener( moveHistory );
    		multiplayerClick.addActionListener( multiPlayerAction );
    		
    		
    		frame.setJMenuBar( MenuBar );
    		frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE );
    		frame.setTitle("ECE90315 Chess");
    		frame.setResizable(false);
    		frame.setLocationRelativeTo( null );
    		frame.setVisible(true);
    		frame.setSize(600, 645);
    		frame.setIconImage(new ImageIcon("pieces/icon.png").getImage());
    		frame.pack();
         }
    }
    This is the code for the pieces and working out the location of each piece:

    Java Code:
    import java.io.*;
    import java.util.*;
    
    public class Pieces  {  
    
    int start = 0;
    int start2 = 0;
    static int i = 0;
    
    // ************** changed by ioannis **************************	
    int[][] pseudoboard = new int[8][8];
    
    
    static Vector<Object> pieces1History = new Vector<Object>();
    static Vector<Object> pieces2History = new Vector<Object>();
    static Vector<Object> player1moveStart = new Vector<Object>();
    static Vector<Object> player2moveFinish = new Vector<Object>();
    
    //static List<String> moveHistory = new ArrayList<String>();
    	
    int indexNumber=0;
    String[] piecePlaces = new String[64];
    // ************** changed by ioannis **************************
    
    public Pieces()
    {
    // ************** changed by ioannis **************************
     // moved these here for you, better this way .. ioannis 
    	piecePlaces[0] = "WR1";
    	piecePlaces[1] = "WH1";
    	piecePlaces[2] = "WB1";
    	piecePlaces[3] = "WK";
    	piecePlaces[4] = "WQ";
    	piecePlaces[5] = "WB2";
    	piecePlaces[6] = "WH2";
    	piecePlaces[7] = "WR2";
    	piecePlaces[8] = "WPAWN1";
    	piecePlaces[9] = "WPAWN2";
    	piecePlaces[10] = "WPAWN3";
    	piecePlaces[11] = "WPAWN4";
    	piecePlaces[12] = "WPAWN5";
    	piecePlaces[13] = "WPAWN6";
    	piecePlaces[14] = "WPAWN7";
    	piecePlaces[15] = "WPAWN8";
    	
    	piecePlaces[16] = null;
    	piecePlaces[17] = null;
    	piecePlaces[18] = null;
    	piecePlaces[19] = null;
    	piecePlaces[20] = null;
    	piecePlaces[21] = null;
    	piecePlaces[22] = null;
    	piecePlaces[23] = null;
    	piecePlaces[24] = null;
    	piecePlaces[25] = null;
    	piecePlaces[26] = null;
    	piecePlaces[27] = null;
    	piecePlaces[28] = null;
    	piecePlaces[29] = null;
    	piecePlaces[30] = null;
    	piecePlaces[31] = null;
    	piecePlaces[32] = null;
    	piecePlaces[33] = null;
    	piecePlaces[34] = null;
    	piecePlaces[35] = null;
    	piecePlaces[36] = null;
    	piecePlaces[37] = null;
    	piecePlaces[38] = null;
    	piecePlaces[39] = null;
    	piecePlaces[40] = null;
    	piecePlaces[41] = null;
    	piecePlaces[42] = null;
    	piecePlaces[43] = null;
    	piecePlaces[44] = null;
    	piecePlaces[45] = null;
    	piecePlaces[46] = null;
    	piecePlaces[47] = null;
    	
    	piecePlaces[48] = "BPAWN1";
    	piecePlaces[49] = "BPAWN2";
    	piecePlaces[50] = "BPAWN3";
    	piecePlaces[51] = "BPAWN4";
    	piecePlaces[52] = "BPAWN5";
    	piecePlaces[53] = "BPAWN6";
    	piecePlaces[54] = "BPAWN7";
    	piecePlaces[55] = "BPAWN8";
    	piecePlaces[56] = "BR1";
    	piecePlaces[57] = "BH1";
    	piecePlaces[58] = "BB1";
    	piecePlaces[59] = "BK";
    	piecePlaces[60] = "BQ";
    	piecePlaces[61] = "BB2";
    	piecePlaces[62] = "BH2";
    	piecePlaces[63] = "BR2";
    // ************** changed by ioannis **************************	
    //	int start = 0;
    //	int start2 = 0;
    	
    	//int[][] pseudoboard = new int[8][8];
    	//String[][] pseudoboard = new String[8][8];
    	
    	//int indexNumber=0;
    // ************** changed by ioannis **************************
    
    	
    	// allocating the pseudoboard positions to match the piecePlaces locations
    	
    	for (int i=0;i<=7;i++)
    		{
    			
    			for(int k=0;k<=7;k++)
    			{
    			pseudoboard[k][i]=indexNumber;
    			indexNumber++;
    			}
    		
    		}
    		// ************** changed by ioannis **************************
    	}
    	
    	
    // ************** changed by ioannis **************************
    public  int workoutloc(int X, int Y,char c) {
    		int column = X;
    		int row = Y;
    
    		for (int rows = 0; rows < 8; rows++)
    			{
    				for(int cols = 0; cols < 8; cols++)
    					{	
    						start++;
    					}	
    						start2++;
    			}		
    		
    	if(X >= 0 && X <= 600) {
    		column = X / 75;
    		System.out.print("X is "+column);
    	}else{
    			//mouse not on game board
    	}
    
    	if(Y >= 0 && Y <= 600) {
    		row = Y / 75;
    		System.out.println(" & Y is "+row);
    	}else{
    		    //mouse not on game board
    	}	
    	
    // ************** changed by ioannis **************************	
    	if (c=='p') // case mouse button is pressed
    	{
    	System.out.println("You clicked on "+piecePlaces[pseudoboard[column][row]]+" in square "+ pseudoboard[column][row]);
    	
    	if(piecePlaces[pseudoboard[column][row]] == null) { return 0; } else {
    	pieces1History.add(piecePlaces[pseudoboard[column][row]]);
    	player1moveStart.add(pseudoboard[column][row]);
    	//moveHistory.add(piecePlaces[pseudoboard[column][row]]);
    	} }
    	if(c=='r')// case mouse button is released
    	{
    	System.out.println("You moved to "+piecePlaces[pseudoboard[column][row]]+" in square "+pseudoboard[column][row]);
    	player2moveFinish.add(pseudoboard[column][row]);
    	i++;
    	
    	}
    	
    	
    	
    	return pseudoboard[column][row];
    	} 
    	
    public void trackMove(int BoardPositionFrom,int BoardPositionTo)
    {
    		String tempVar;
    		String tempVar2;
    
    		if(BoardPositionFrom!=BoardPositionTo)
    		{
    		tempVar=piecePlaces[BoardPositionTo];
    		piecePlaces[BoardPositionTo]=piecePlaces[BoardPositionFrom];
    		piecePlaces[BoardPositionFrom]=null;
    		}
    }	
    	
    }
    I believe I need to create a method within:

    Java Code:
    public void mouseReleased(MouseEvent e) {
    	
    		
    		
            if(chessPiece == null) return;
    		
            chessPiece.setVisible(false);
    		Component c =  chessBoard.findComponentAt(e.getX(), e.getY());
    		
            if (c instanceof JLabel){
    		
                Container parent = c.getParent();
                parent.remove(0);
                parent.add( chessPiece );
            } 
            else {
                Container parent = (Container)c;
                parent.add( chessPiece );
            }
     
            chessPiece.setVisible(true);
    I think I would want the method to check what piece it is and check against a generic rules for that piece. However making that a reality confuses me!

    Any help would be awesome right now - so close yet so far! :D

    Cheers,

    Dan.
    Last edited by danborgir; 04-27-2011 at 11:37 AM.

  2. #2
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    Location
    London, UK
    Posts
    797
    Blog Entries
    2
    Rep Power
    4

    Default

    each Piece object should contain a list of relative board coordinates it may be placed on from where it is.

    Say the board has columns 1-8, rows A-H and a horse starts from the square A2. The valid moves should be determined by the Horses list of coordinates
    (+2,+1) [up2, right1, OFF],
    (+2,-1) [up2, left1, OFF],
    (+1,+2) [OFF],
    (+1,-2) [OFF],
    (-1,+2) [B4] [occupied],
    (-1,-2) [OFF],
    (-2,+1) [C3] [valid],
    (-2,-1) [C1] [valid]

    all the 8 possible moves a horse can make, and then use a separate method to take into the board range factor (so the horse can't be moved off the board) and another method to check if something is already placed on the destination square
    Last edited by ozzyman; 04-27-2011 at 12:50 PM.

  3. #3
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    I would suggest a moveGenerator method for each piece type that will return a list of valid move squares for that piece. The knight could use an algorithm based on ozzyman's idea above, but you'll probably find that, for example, a queen, would need a different algorithm (move horizontally or diagonally in any direction until a piece is encountered). If you have a ChessPiece abstract class or interface, with King, Queen, Bishop, etc., subclasses, each subclass can implement the method appropriately.

    Btw, don't forget about special cases where an otherwise valid move isn't possible, such as where a piece is pinned to the king. You can either handle this kind of thing in the piece itself, e.g. a king pin flag that you can check when generating the move list, or just have the piece generate the basic list and check externally. But if it can be done by the piece itself, life is generally much simpler. Weird stuff like castling, promoting, and taking en-passant will need special handling (and some careful thought).

    When generating the moves, it might be advantageous to also generate a list of pieces being attacked, so the piece knows where it can move and what pieces it is attacking. Again, the algorithm will vary according to piece type.

    Polymorphism means that once you've implemented the method for each piece type, you can treat each the same in most situations, but it does mean that each piece needs access to the board.
    Last edited by dlorde; 04-27-2011 at 07:33 PM.

  4. #4
    Dastagir is offline Member
    Join Date
    Dec 2011
    Posts
    5
    Rep Power
    0

    Default Re: Chess rules method

    where i have to store/keep image to get this implemented?
    ImageArray_TOP[0] = "pieces/top/1brook.gif";

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,883
    Rep Power
    25

    Default Re: Chess rules method

    Please start your own thread for your questions.

Similar Threads

  1. Help with Chess GUI
    By Lord Voldemort in forum AWT / Swing
    Replies: 9
    Last Post: 01-24-2011, 06:38 PM
  2. Chess program
    By Chro in forum New To Java
    Replies: 1
    Last Post: 10-26-2010, 10:20 AM
  3. Chess game
    By michail in forum New To Java
    Replies: 4
    Last Post: 12-23-2009, 07:51 PM
  4. New Chess-Like game
    By jSarK0Y in forum Reviews / Advertising
    Replies: 3
    Last Post: 06-10-2009, 04:28 AM
  5. Replies: 1
    Last Post: 07-05-2008, 04:08 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
  •