Results 1 to 14 of 14

Thread: chess game

  1. #1
    michail is offline Member
    Join Date
    Dec 2009
    Posts
    31
    Rep Power
    0

    Default chess game

    this has been del
    Last edited by michail; 01-28-2010 at 04:51 PM. Reason: solved

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    How do you represent your board? Do you have a 2 dimensional array that holds pieces? This is what needs to be created and then you would update the array when you move a piece. I also recommend that you get rid of all the statics and make your methods true OOP methods and your class a true OOP class. There are other changes that you'll want to make but these above may be good places to start.

    Best of luck.

  3. #3
    gcampton Guest

    Default

    Well I think one way to do this would be use an array, or arraylist.
    and set up all the pieces in their correct position, and then when using you methods. (d2, d3) you check the piece exists in it's current position if true, check if any piece is in the destination if true, you could add checks on this to make sure it is a valid move, however this will require more code.
    move the piece by swaping contents(piece to null), if something exists in destination then delete that piece (capture it), so piece to null again swapping the contents.
    I'm just speculating to give you some ideas how you can go about it.

    edit: fubarable beat me to it.

  4. #4
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Press enter with the cursor in either textField.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    
    public class ChessX extends JPanel {
        final int SIZE = 8;
        String rowIds = "12345678";
        String colIds = "abcdefgh";
        Point curLoc = new Point(-1,-1);  // current     : green
        Point dstLoc = new Point(-1,-1);  // destination : blue
    
        private void showMove(String current, String dest) {
            curLoc = getLoc(current);
            dstLoc = getLoc(dest);
            //System.out.printf("curLoc[%d, %d]  dstLoc[%d, %d]%n",
            //                   curLoc.x, curLoc.y, dstLoc.x, dstLoc.y);
            repaint();
        }
    
        private Point getLoc(String s) {
            int col = colIds.indexOf(s.charAt(0));
            int row = rowIds.indexOf(s.charAt(1));
            return new Point(col, row);
        }
    
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            double w = getWidth();
            double h = getHeight();
            double hInc = (w-1)/SIZE;
            double vInc = (h-1)/SIZE;
            for(int i = 0; i <= SIZE; i++) {
                double x = i*hInc;
                g2.draw(new Line2D.Double(x, 0, x, h));
            }
            for(int i = 0; i <= SIZE; i++) {
                double y = i*vInc;
                g2.draw(new Line2D.Double(0, y, w, y));
            }
            // Draw curLoc.
            double x = curLoc.x*hInc;
            double y = curLoc.y*vInc;
            g2.setPaint(Color.green.darker());
            g2.fill(new Rectangle2D.Double(x, y, hInc, vInc));
            // Draw dstLoc.
            x = dstLoc.x*hInc;
            y = dstLoc.y*vInc;
            g2.setPaint(Color.blue);
            g2.fill(new Rectangle2D.Double(x, y, hInc, vInc));
        }
    
        public Dimension getPreferredSize() {
            return new Dimension(400,400);
        }
    
        private JPanel getContent() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(getBoardComponent(), gbc);
            gbc.fill = GridBagConstraints.HORIZONTAL;
            panel.add(getInputPanel(), gbc);
            return panel;
        }
    
        private JPanel getBoardComponent() {
            JPanel topPanel = getTopPanel();
            int height = topPanel.getPreferredSize().height;
            JPanel leftPanel = getLeftPanel();
            int width = leftPanel.getPreferredSize().width;
            JPanel spacer = new JPanel();
            spacer.setPreferredSize(new Dimension(width, height));
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            panel.add(spacer, gbc);
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(topPanel, gbc);
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            panel.add(leftPanel, gbc);
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(this, gbc);
            return panel;
        }
    
        private JPanel getTopPanel() {
            String[] ids = colIds.split("(?<=[\\w])");
            JPanel panel = new JPanel(new GridLayout(1,0));
            for(int i = 0; i < SIZE; i++) {
                panel.add(new JLabel(ids[i], JLabel.CENTER));
            }
            return panel;
        }
    
        private JPanel getLeftPanel() {
            String[] ids = rowIds.split("(?<=[\\w])");
            JPanel panel = new JPanel(new GridLayout(0,1));
            for(int i = 0; i < SIZE; i++) {
                panel.add(new JLabel(ids[i]));
            }
            return panel;
        }
    
        private JPanel getInputPanel() {
            final JTextField curField = new JTextField("b3", 4);
            final JTextField dstField = new JTextField("e6", 4);
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    showMove(curField.getText(), dstField.getText());
                }
            };
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            addTo("current",     Color.green.darker(), curField, panel, gbc, al);
            addTo("destination", Color.blue,           dstField, panel, gbc, al);
            return panel;
        }
    
        private void addTo(String s, Color fg, JTextField tf, JPanel p,
                           GridBagConstraints gbc, ActionListener al) {
            JLabel label = new JLabel(s);
            label.setForeground(fg);
            gbc.anchor = GridBagConstraints.EAST;
            p.add(label, gbc);
            tf.setHorizontalAlignment(JTextField.CENTER);
            gbc.anchor = GridBagConstraints.WEST;
            tf.addActionListener(al);
            p.add(tf, gbc);
        }
    
        public static void main(String[] args) {
            ChessX chessX = new ChessX();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLayout(new GridBagLayout());
            f.add(chessX.getContent(), new GridBagConstraints());
            f.pack();
            f.setLocation(100,100);
            f.setVisible(true);
        }
    }

  5. #5
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,015
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by michail View Post
    Java Code:
     public static int squareToX(String square) 
              { 
                  int x = 0; 
                  char row;
                  
                  row = square.charAt(0); 
                  if (row == 'a') x = 0; 
                  else
                    if (row == 'b') x = 1; 
                  else
                    if (row == 'c') x = 2; 
                  else
                    if (row == 'd') x = 3; 
                  else
                    if (row == 'e') x = 4; 
                  else
                    if (row == 'f') x = 5; 
                  else
                    if (row == 'g') x = 6; 
                  else
                    if (row == 'h') x = 7; 
                    else System.out.println("Enter correct stuff");
                  
                  {
                      return x;
                      
                      }
                      
                }
                
       public static int squareToY(String square)            {
                    int y = 0;
                    char col;
                
                  col = square.charAt(1); 
                  if (col == '1') y = 0; 
                  else
                    if (col == '2') y = 1; 
                  else
                    if (col == '3') y = 2; 
                  else
                    if (col == '4') y = 3; 
                  else
                    if (col == '5') y = 4; 
                  else
                    if (col == '6') y = 5; 
                  else  
                    if (col == '7') y = 6; 
                  else
                    if (col == '8') y = 7; 
                    
                  else System.out.println("Enter correct stuff");
                  
                  {
                      return y;
                      }
                }
    Better change those verbose methods to this:

    Java Code:
    int coordinate(char pos, String pattern) {
       return pattern.indexOf(pos);
    }
    public static int squareToX(String square) 
       return coordinate(square.charAt(0), "abcdefgh");
    }
    public static int squareToY(String square) {
       return coordinate(square.charAt(1, "12345678");
    }
    kind regards,

    Jos
    Last edited by JosAH; 01-10-2010 at 01:41 PM. Reason: typos in the code ...

  6. #6
    michail is offline Member
    Join Date
    Dec 2009
    Posts
    31
    Rep Power
    0

    Default

    Tried Jos's and worked fine!
    I have a very simple 2D array and it is also text based [for now]!

    A question: Why are the statics not a good idea?
    The coords are sent back to the Move class, in the Move class can I make the actual moves, using desX, desY?
    [The array list is in the Chess class] [also have 5 separate classes for the pieces, maybe each class can specify the it's moves]
    Last edited by michail; 01-10-2010 at 01:15 PM. Reason: solved
    For a world of science and reason

  7. #7
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,015
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by michail View Post
    A question: Why are the statics not a good idea?
    Static methods aren't a bad thing by definition but in an object oriented world objects talk to (other) object by caling methods on them with optional parameters. There is (almost) no need to talk to an entire family (class) of objects.

    kind regards,

    Jos

  8. #8
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,015
    Blog Entries
    7
    Rep Power
    20

    Default

    Why don't you create a, say, Move class and use that; a Move class can be ever so simple:

    Java Code:
    public class Move {
       int xFrom, yFrom;
       int xTo   , yTo;
       public Move(int xFrom, int yFrom, int xTo, int yTo) {
          this.xFrom= xFrom;
          this.yFrom= yFrom;
          this.xTo= xTo;
          this.yTo= yTo;
       }
       ...
       public boolean doMove(Board board) {
          // check if the move is valid, if so return true
       }
    }
    kind regards,

    Jos

  9. #9
    michail is offline Member
    Join Date
    Dec 2009
    Posts
    31
    Rep Power
    0

    Default

    Well, I have sth like that but it.s full of random thoughts
    the problem is how to refresh the board after the user inputs the moves. (i could post the whole thing, however).
    For a world of science and reason

  10. #10
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,015
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by michail View Post
    Well, I have sth like that but it.s full of random thoughts
    the problem is how to refresh the board after the user inputs the moves. (i could post the whole thing, however).
    Well, in an object oriented world it's always something that makes something (else) do something. The first two 'somethings' are objects and the last 'something' is a method. Until you have figured out (by pencil and paper or in your head) all those 'somethings' don't code anything yet.

    kind regards,

    Jos

  11. #11
    michail is offline Member
    Join Date
    Dec 2009
    Posts
    31
    Rep Power
    0

    Thumbs up

    Did it! The pieces move. Now I have to write the move rules. At least i think that's the next step. Any advice on what to think of first?
    Good advice from Jos.
    For a world of science and reason

  12. #12
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,015
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by michail View Post
    A lot of redundant stuff here. Can someone please check? I am trying to validate the moves but I can't get the Mydisplay to be recognised in the isValid method.

    Java Code:
                if (Mydisplay == "Pawn 0,1")
    You don't compare Strings for equality like that; read the API documentation for the String class and especially read about the String.equals( ... ) method.

    kind regards,

    Jos

  13. #13
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,015
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by michail View Post
    I have another problem here, though. It doesn't recognise what that string is. It returns 0 when I test print it [line above].
    I checked the API and yeah that's not how you do it. Shouldn.t I be able to call the string Mydisplay in the isValid?
    Thanks for that
    Did you change your code as I suggested? i.e. use the String.equals( ... ) method for comparison for equality. If so, it doesn't hurt if you print out both Strings before you compare them so you can see what actually is compared.

    kind regards,

    Jos

  14. #14
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,015
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by michail View Post
    Yeah sorry, I tried it and it doesn.t recognise the this.Mydisplay you can compile it and see.

    It should recognise Mydisplay anywhere in the class
    It does see your variable Mydisplay anywhere in the class object because it is a member variable. Please be more exact w.r.t. the errors you are experiencing.

    kind regards,

    Jos

    ps. please leave out that COLOR stuff from your messages; as you can see it doesn't work as you intended. (previewing your own message would've shown that)

Similar Threads

  1. a good java chess program
    By rico16135 in forum New To Java
    Replies: 10
    Last Post: 11-06-2010, 12:25 PM
  2. Replies: 2
    Last Post: 08-05-2010, 04:49 AM
  3. Chess game
    By michail in forum New To Java
    Replies: 4
    Last Post: 12-23-2009, 06:51 PM
  4. I want play chess in Java
    By ganzorig in forum Advanced Java
    Replies: 6
    Last Post: 11-15-2009, 04:53 AM
  5. New Chess-Like game
    By jSarK0Y in forum Reviews / Advertising
    Replies: 3
    Last Post: 06-10-2009, 03:28 AM

Posting Permissions

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