Chess board

hello
i need help with this animation i need to make
i have a chess board and a simple form, lets say a circle, my
problem is that i need to change the color of the part of the cell
while the circle pass, so when the cicrle is in a black cell part
of the cell becomes white and the next white cell should be change
to white
thanks alot for you help

quote:
Originally posted by:
chrisf671
ok i know what you need to do is make collistion detection on
the cells i found you a tutorial on it. here
http://www.spoono.com/flash/tutorials/tutorial.php?id=18
if you need futher help just ask.
tyvm for your answer chris
the collinding is really usefull and im sure ill use it, my
only problem is that i need one of the boxes to gradually change
color as it is getting into the other box
lets say that the green box is half in and half outside the
gray box, meaning that the outside part will rest green and the
half within the gray box will change to red
ill make some experiment with it and keep you updated, pls if
u have any other idea i will really apreciated it
thxs again

Similar Messages

  • Problem in designing chess board

    I designed chess board before by making for loop for rows and anthor one for columns. But here i did inner for loop : one for row ant the other for column but only column appear and row not appear ...
    My try:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    public class MovePawnTest extends JFrame {
        private BoardGame board;
        public MovePawnTest() {
            board = new BoardGame();
            getContentPane().add(board, BorderLayout.CENTER);
        public static void main(String[] args) {
            MovePawnTest movePawnTest = new MovePawnTest();
            movePawnTest.setDefaultCloseOperation(MovePawnTest.EXIT_ON_CLOSE);
            movePawnTest.setSize(new Dimension(600, 300));
            movePawnTest.setLocationRelativeTo(null);
            movePawnTest.setVisible(true);
            movePawnTest.setExtendedState(MAXIMIZED_BOTH);
    import java.awt.Graphics;
    import javax.swing.JPanel;
    public class BoardGame extends JPanel {
        private final int ROW = 8, COL = 8, x = 100, y = 60;
        private int[][] board;
        public BoardGame() {
            board = new int[ROW][COL];
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            drawBoard(g);
        private void drawBoard(Graphics g) {
            for (int i = 0; i < ROW; ++i) {
                for (int j = 0; j < COL; ++j) {
                    g.drawLine((x * j) + 100, (y * i) + 60, (x * j) + 100, (y * i) + 60);
    }please say me the
    thanks in advance

    ah fark
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class ChessBoard extends JPanel{
      private static final int ROWS = 8;
      private static final int COLS = 8;
      private static final int WIDTH = 600;
      private static final Dimension SIZE = new Dimension(WIDTH, WIDTH);
      private static final Color COLOR1 = Color.white;
      private static final Color COLOR2 = Color.gray;
      public ChessBoard() {
        setPreferredSize(SIZE);
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int panelWidth = getWidth();
        int panelHeight = getHeight();
        for (int row = 0; row < ROWS; row++) {
          double h = (double)panelHeight / ROWS;
          int y = (int)(h * row);
          for (int col = 0; col < COLS; col++) {
            double w = (double)panelWidth / COLS;
            int x = (int)(w * col);
            Color c = ((row % 2 == 0) ^ (col % 2 == 0)) ? COLOR1 : COLOR2;
            g.setColor(c);
            g.fillRect(x, y, (int)w, (int)h);       
      private static void createAndShowUI() {
        JFrame frame = new JFrame("ChessBoard");
        frame.getContentPane().add(new ChessBoard());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
    }

  • How can i make infinite chess board

    Hello.
    for example i want to create an infinite chess board for iphone.
    i want to scale it as i want and to ho throw it up, down, left and right.
    in what way can i make it? what class to use?
    i think UIScrollView, but how? i do not have an image, because it must be infinite
    and then i want to add figures to this chess board. for example if user tap on a cell a figure appears.

    Hi Mywa, and welcome to the Dev Forums!
    I'll try to outline a solution, but I doubt anyone is going to code it for you in a forum, so you'll need some iPhone development experience. As a minimum, make sure you know exactly how the [PageControl|http://developer.apple.com/library/ios/#samplecode/PageControl/Int roduction/Intro.html] sample app works, and have a good understanding of the Tiling example in the [ScrollViewSuite|http://developer.apple.com/library/ios/#samplecode/ScrollViewS uite/Introduction/Intro.html%23//apple_ref/doc/uid/DTS40008904]. It would also help if you're familiar with most of the content in the Scroll View Programming Guide for iOS.
    I would start the project by obtaining a 320 x 320 image of your chess board (e.g. a slice of the board containing 8 x 8 squares, each 40 x 40 pixels). For now, you can just package the image as a single UIImageView object in a xib file (later on we might replace this with a custom subclass of UIView which draws either blank or populated squares, but let's do the basics first).
    In your board controller's viewDidLoad method, create 9 of these objects, setting the frames to make 3 rows of 3 squares each, and add the 9 objects to a 320 x 320 scrollview so that only the central object is visible. Then set the scroll view's [contentSize|http://developer.apple.com/library/ios/documentation/UIKit/Referen ce/UIScrollViewClass/Reference/UIScrollView.html#//appleref/doc/uid/TP40006922-CH3-SW20] property to 960 x 960 and make sure you can scroll horizontally and vertically to the edges of the grid.
    Once you get that part working, you're ready to expand the contentSize and write the code which removes and adds the 320 x 320 image view objects as needed. This is where you'll need to understand the sample apps I recommended. Basically, after each scrolling movement your controller logic needs to decide which image view objects can be released (or recycled), and which grid positions need a new (or reused) image view. The game is to always have an image view ready before any part of an empty grid position becomes visible.
    For best performance, the image view objects should be placed in a "reuse" queue when they're removed from the superview, then pulled off the queue as needed, just as cells are managed by UITableView. But the reuse queue is only an optimization, so I would save it for later. For now, I would just release and create. The important thing is to make sure you never need to have very many more than 9 image view objects in memory at any time.
    Once you have your "infinite" board operating correctly, you're ready to decide how to store the position of each piece, and how to draw the pieces on the visible squares. If the number of pieces is likely to exceed 1000, you might find the data storage to be more challenging than the drawing, because you'll need to locate pieces fast enough to keep up with scrolling. If the number of 8 x 8 board segments is to be considered infinite, you might not want to store the data for all 64 squares of every segment that's ever been visible. In that case you'll need a "sparse array" that only includes info on populated squares, i.e. one element for each piece instead of one element for each location. I think William gave you some good advice on what data structures to use for this. At some point you might also consider a database to implement your sparse array.
    That's probably the best I can do to get you started. I would advise against trying to design all the details ahead of time. E.g., I don't expect you to reply with "Ok, but how do I actually draw the pieces?" until you've got the board working. And I don't expect you to ask how to draw the board until you've become good friends with the recommended sample apps. But once you're seriously into the sample code, we might be able to help with questions like: "I'm trying to calculate which view objects are visible as shown in the layoutSubviews method of [3Tiling/Classes/TiledScrollView.m|http://developer.apple.com/library/ios/sampleco de/ScrollViewSuite/Listings/3_Tiling_Classes_TiledScrollView_m.html#//apple_ref/ doc/uid/DTS40008904-3_Tiling_Classes_TiledScrollView_m-DontLinkElementID26], but ... ". Ok?
    \- Ray

  • ChessBoard , my attempt and learning to develope chess board

    this is my attempt to learn how to create simple chessboard in java.. ill post my code as i progress, any suggestions is greate.
    i use netbeans :) and jdk1.6rc. peace
    * ChessBoard.java
    * Created on November 26, 2006, 10:06 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author Bilal El Uneis
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ChessBoard extends JFrame implements MouseListener
    JPanel [][] squares;
    /** Creates a new instance of ChessBoard */
    public ChessBoard()
    Container c = getContentPane();
    c.setLayout(new GridLayout(8,8, 1 , 1));
    squares = new JPanel[8][8];
    for(int i=0; i<8; i++)
    for(int j=0; j<8; j++)
    squares[i][j] = new JPanel();
    if((i+j)%2 == 0)
    squares[i][j].setBackground(Color.white);
    else
    squares[i][j].setBackground(Color.black);
    squares[i][j].addMouseListener(this);
    c.add(squares[i][j]);
    public void mouseClicked(MouseEvent e){ }
    public void mouseEntered(MouseEvent e){ }
    public void mouseExited(MouseEvent e) { }
    public void mousePressed(MouseEvent e) { }
    public void mouseReleased(MouseEvent e) { }
    public static void main(String args[])
    ChessBoard test = new ChessBoard();
    test.setSize(300,300);
    test.setResizable(false);
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    test.setVisible(true);
    }

    ok .. still trying to find time to play with my gui thing.. i got my board to basically give me info when my mouse is on piece or square.. also created a class called movablePiece that listen to mouse events too.
    changes made to board and board2 disapears ..
    here is the code ..
    * BoardSquare.java
    * Created on December 8, 2006, 11:08 PM
    * @author Bilal El Uneis
    * [email protected]
    import java.awt.event.*;
    import javax.swing.*;
    public class BoardSquare extends JPanel implements MouseListener
        public BoardSquare()
            super();
            addMouseListener(this);
        public BoardSquare(String name)
            super();
            setName(name);
            addMouseListener(this);
        public void mouseClicked(MouseEvent e)
        public void mousePressed(MouseEvent e)
        public void mouseReleased(MouseEvent e)
        public void mouseEntered(MouseEvent e)
            System.out.println("wellcome to square " + getName());
        public void mouseExited(MouseEvent e)
        public static void main(String args[])
            JFrame frame = new JFrame();
            frame.setSize(200,200);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new BoardSquare("test square"));
            frame.setVisible(true);
    * Board.java
    * Created on November 29, 2006, 11:04 AM
    * @author Bilal El Uneis
    * [email protected]
    import java.awt.*;
    import javax.swing.*;
    public class Board extends JPanel
        protected BoardSquare[][] squares;
        /** Creates a new instance of Board */
        public Board()
            setSize(800,700);
            setLayout(new GridLayout(8,8));
            squares = new BoardSquare[8][8];
            createSquares();
        public Board(int h, int w)
            setSize(h,w);
            setLayout(new GridLayout(8,8));
            squares = new BoardSquare[8][8];
            createSquares();
        private void createSquares()
            for(int i=0;i<8;i++)
                for(int j=0;j<8;j++)
                    BoardSquare panel = new BoardSquare(""+i+""+j);
                    panel.setBackground(getColor(i,j));
                    add(panel);
                    squares[i][j] = panel;
        private Color getColor(int x, int y)
            if((x+y)%2 == 0)
                return Color.WHITE;
            else
                return Color.BLACK;
        public void addPiece(Piece p, int x, int y)
            squares[x][y].add(p);
            paintAll(getGraphics());
        public void removePiece(int x, int y)
            if(squares[x][y].getComponentCount() > 0)
                squares[x][y].remove(0);
                paintAll(getGraphics());
        public static void main(String args[])
            Board t = new Board();
            //add pawns to board
            for(int i=0; i<8; i++)
                t.addPiece(new Piece("Rpawn.gif"),1,i);
                t.addPiece(new Piece("Bpawn.gif"),6,i);
            //add castles
            t.addPiece(new Piece("Rrook.gif"),0,7);
            t.addPiece(new Piece("Brook.gif"),7,7);
            t.addPiece(new MoveablePiece("Rrook.gif"),0,0);
            t.addPiece(new Piece("Brook.gif"),7,0);
            //add horses
            t.addPiece(new Piece("Rknight.gif"),0,6);
            t.addPiece(new Piece("Bknight.gif"),7,6);
            t.addPiece(new Piece("Rknight.gif"),0,1);
            t.addPiece(new Piece("Bknight.gif"),7,1);
            //add pishops
            t.addPiece(new Piece("Rbishop.gif"),0,5);
            t.addPiece(new Piece("Bbishop.gif"),7,5);
            t.addPiece(new Piece("Rbishop.gif"),0,2);
            t.addPiece(new Piece("Bbishop.gif"),7,2);
            //add queen
            t.addPiece(new Piece("Rqueen.gif"),0,4);
            t.addPiece(new Piece("Bqueen.gif"),7,4);
            //add king
            t.addPiece(new Piece("Rking.gif"),0,3);
            t.addPiece(new Piece("Bking.gif"),7,3);
            //create jframe and add the board to it :)
            JFrame frame = new JFrame();
            frame.setSize(800,700);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.add(t);
            frame.setVisible(true);
            //test moving one piece to see if i can
            JOptionPane.showInputDialog("testing pawn move");
            t.removePiece(1,0);
            t.addPiece(new Piece("Rpawn.gif"),2,0);
    * Piece.java
    * Created on November 29, 2006, 11:35 AM
    * @author Bilal El Uneis
    * [email protected]
    import javax.swing.*;
    public class Piece extends JLabel
        /** Creates a new instance of Piece */
        public Piece()
            super(new ImageIcon("Bking.gif"));
            setName("Bking.gif");
        public Piece(String image_file)
            super(new ImageIcon(image_file));
            setName(image_file);
        public static void main(String args[])
            JFrame frame = new JFrame();
            frame.setSize(200,200);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Piece piece = new Piece("Rking.gif");
            frame.add(piece);
            frame.setVisible(true);
            System.out.println(piece.getName());
    * MoveablePiece.java
    * Created on December 8, 2006, 4:36 PM
    * @author Bilal El Uneis
    * [email protected]
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MoveablePiece extends Piece implements MouseListener
        /** Creates a new instance of MoveablePiece */
        public MoveablePiece()
            super();
            addMouseListener(this);
        public MoveablePiece(String piece_name)
            super(piece_name);
            addMouseListener(this);
        public void mouseClicked(MouseEvent e)
        public void mousePressed(MouseEvent e)
            System.out.println(getName() + " pressed..");
        public void mouseReleased(MouseEvent e)
        public void mouseEntered(MouseEvent e)
            System.out.println("u enterd " + getName());
            System.out.println("Parent is " + e.getComponent().getParent().getName());
        public void mouseExited(MouseEvent e)
        public static void main(String args[])
            MoveablePiece p = new MoveablePiece();
            JPanel panel = new JPanel();
            panel.setName("black panel");
            panel.setSize(50,50);
            panel.setBackground(Color.black);
            JFrame frame = new JFrame();
            frame.setName("frame");
            frame.setLayout(new GridLayout());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(300,300);
            frame.add(p);
            frame.add(panel);
            frame.setVisible(true);
    }i know i can go with the easy way and just hardwire the code so that i can move the piece is square was clicked or piece.. but im trying to make every class able to function on its own as standalone.. that way u can use what ever class u want and not have to be tied for using everything because every class needs the other in a way that is hard to understand..
    any suggestions will be greate, im just learning here :) . peace
    Bilal El Uneis

  • I can't airplay DVD's to my TV from my Mac, it just looks like a chess board, Help

    As above, iv tried Vlc but im a mong and cant work out how to get the dvd to play after downlaoding the software, iv gone to settings and changed the Cd DVD setting to Vlc but i still wont work, please help

    That's normal.  Blame the MPAA for being so uptight about broadcasting copyrighted video.  Some DVDs come with a specially formatted video that will work on iTunes.  Otherwise you are left with hardware only connections, such as described below:  https://discussions.apple.com/docs/DOC-2821

  • Scrolling display gray/white boxes (chess board pattern)

    When I am scrolling down in an email, it displays a "checkered page" with small gray and white boxes before each page loads. Is that normal?

    Yes. That is a temporary screen while it downloads more info from the server.

  • My MacBook Pro was hacked. A chess board appeared and when I clicked it code scrolled all over the screen and then my desktop disappeared. It all came back but now it shows a guest user and my screen looks completely different.

    Files on my computer were added. In the files were pics of my hard drive and flags. Text editor had a lot of code. Is there anyway to convert the code? Trying to see if my crazy ex did this. And did someone have to have access to my computer to do this?

    Disconnect from the network.
    Back up all data to at least two different storage devices, if you haven't already done so. The backups can be made with Time Machine or with a mirroring tool such as Carbon Copy Cloner. Preferably both.
    Reconnect to the network.
    Boot into Recovery (command-R at startup), launch Disk Utility, and erase the startup volume with the default options.This operation will destroy all data on the volume, so you had be better be sure of your backups. Quit Disk Utility and install OS X. When you reboot, you'll be prompted to go through the initial setup process. That’s when you transfer the data from one of your backups. For details of how this works, see here:
    Using Setup Assistant
    Transfer only "Users" and "Settings" – not "Applications" or "Other files." Don't transfer the Guest account, if it was enabled on the old system.
    Reinstall your third-party software from fresh downloads or original media.
    Change all Internet passwords.
    Note: You need an always-on Ethernet or Wi-Fi connection to the Internet to use Recovery. It won’t work with USB or PPPoE modems, or with proxy servers, or with networks that require a certificate for authentication.

  • Displaying the value of an array in swing? Almost like a chess baord

    Hi all.
    After a long time from coding I thought I'd have a bash.
    Here's a short outline of what I'm trying code.
    I have a robot, a simple robot, does nothing but move around, pick up objects and drop them.
    This robot lives in a world that is a square 1000x1000 for example.
    The world is populated with objects, the robot goes around, if the robot is not holding an object and comes across one it will pick it up.
    Then the robot moves around and if it comes across another object of the same type it will then drop the object.
    These are the class names that I've created, the names give it away what they are for:
    RobotProject (main class, not much in here apart from the starting parameters, such as starting position, how big the world is, number of objects in the world etc)
    SandBox (is the class that the world object will be created from)
    Robot (is the class the robot will be created from, I did it this way just in case I wanted more then one robot in the world)
    GridCheck (this is a static class as it's only a set of instructions to carry out depending where in the world it the robot is and what is around it)
    Movement (this class is not built yet, but all it does is check the current location of the robot, give options of where to move, then randomly picks a move)
    Gui (this is going to be used to display the world, not built yet)
    The object I create of SandBox is called world1, the only thing need to be known about this world is that it has an array, this array is what keeps track of each of the grid in the world and there state.
    So let?s imagine a chess board, top left grid is 0 going from left to right/ top to bottom we end up with 63 (or 64 arrays).
    What would be the best way to display this "chess board"?
    At the moment I have a method in the SandBox class that will return all the grids states and a string.
    This was put in there "just in case" but I think this is the wrong way to go.
    Really what I'm after is a few pointers to make this work, maybe my way of doing this is incorrect?
    I know I've been thinking that maybe I should have created an array of objects (SandBox, but with only an int rather than the array) rather than an object with an array var.
    Anyways, I hope that makes sense, if not feel free to "bust my chops"
    If you would like to see some of the mode feel free to ask, I'm not a student or anything, to be frank the last time I coded anything was over 4 years ago, so as you can guess the code is simply.
    Jon.
    Thanks in advance.
    Edited by: jontelling on Jan 12, 2009 9:47 AM

    I agree with BDLH that Swing would work well here. There are a million and one way to create your "grid" one option include using a 2D grid of JLabels, another being a single JPanel with a grid BufferedImage as its background image (which is probably how I'd do it), etc... which one to choose will depend on the rest of the program, so it may be very early to say. Perhaps at this point you just want to create an interface of invariant behaviors to represent the Grid and thus allowing you flexibility with its implementation.

  • Need code for the following chess game..plz help me out

    Hi,
    Problem:Move the chess piece "KNIGHT" from any location on a "3 x 3" Chess Board and make it go to the far right hand bottom corner.Chess Board in the problem is not the usual Chess Board of 8 x 8.KNIGHT starting position may be any position on board.Program should exit when knight moves to 3 x 3 corner.Here is how my Chess board looks.
    |.... |.... |.... |
    |.... |.... |.... |
    |.... |.... |Queen |<<--The Queen should reach this position
    Remember: KNIGHT moves in specific way such as 2 steps in one direction and 1 step left/right.If the KNIGHT starts are position (2,2) then it cannot move further and you have to throw exception with some error message.
    Run command: "java <some class> x y", where x is x-coordinate and y is y-coordinate(starting position of Knight) on the chess board. For this problem x & y could be 1(min) and 3(max) values and any value(2) in between.
    Deliver : 1) Send me the java code for above problem.
    2) Java code should compile and run.
    3) I will be interested in "Object Oriented Design" thaught process.
    4) Your coding style
    5) Javadoc
    6) Makefile
    I would be more interested in your class design, interface design and error handling.
    please mail the solution to [email protected]
    thanks n regards
    Chinu

    Hi, Here Knight moves like horse. Queen doesn't
    exist. If knight moves to (3,3). Game will be over.
    I am facing problem to move knight from one point
    to another point. And also i have some confussion on
    selecting interfaces and classes.<font size="10000">do your own homework</font>

  • Chess Piece display problem in applet

    Hi,
    I'm writing a chess game applet which will be played between to players over the internet. I'm currently working on the applet side at the moment and will develop the server side once I have completed the applet. I'm currently having problems displaying the actual chess pieces on the board at the moment. One of my design decisions was to make a Board class which extends a JPanel. I have painted the actual chess board squares within the Board JPanel. I then propose to draw the pieces on top of these squares (good design decsion? Can anyone suggest another way. I was thinking of having the images as a separate layer which will sit on top of the squares but wasn't sure how to implement it). The chess pieces are contained in a gif strip www.dur.ac.uk/j.d.p.murphy called ChessPieces02.gif . The problem I am having is to display several pieces at the same time. I lloked at a Java tutorial which suggested using g.clipRect() method to display a defined section of the strip (i.e. a single piece of a certain length). Below is the Board class that I am using.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Board extends JPanel{
    // Holds location of the mousePressed event
    Point point = null;
    // Size of a square square on the board
    int square_size = 40;
    // Mediatracker to monitor the loading of the images
    MediaTracker tracker;
    Image image;
    void init() {
    tracker = new MediaTracker(this);
    image = Toolkit.getDefaultToolkit().getImage("ChessPieces02.gif");
    tracker.addImage(image, 0);
    try {
    //Start downloading the images. Wait until they're loaded.
    tracker.waitForAll();
    } catch (InterruptedException e) {
    e.printStackTrace();
    throw new Error("error");
    if (tracker.isErrorAny()) {
    throw new Error("Could not load image");
    addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if (point == null)
    point = new Point(0, 0);
    int x = e.getX();
    int y = e.getY();
    System.out.println("X co-ord: " + x + " Y co-ord: " + y);
    // Floor the x and y values to the nearest unit of 25
    x = x - x % square_size;
    y = y - y % square_size;
    point.setLocation(x, y);
    repaint();
    System.out.println(point);
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    System.out.println("Chess Board Paint");
    // Loop to produce the black and white squares to represent the board
    for(int jj = 0; jj < 8; jj ++){
    for(int ii = 0; ii < 8; ii++){
    if(ii % 2 == jj % 2)
    g.setColor(Color.white);
    else
    g.setColor(Color.lightGray);
    g.fillRect(ii * square_size, jj * square_size, square_size, square_size );
    // Draw a highlighted square
    if (point != null){
    g.setColor(Color.green);
    g.fillRect( (int)point.getX(), (int)point.getY(), square_size, square_size);
    //imageStrip is the Image object representing the image strip.
    //imageWidth is the size of an individual image in the strip.
    //imageNumber is the number (from 0 to numImages)
    // of the image to paint.
    int stripWidth = image.getWidth(this);
    int stripHeight = image.getHeight(this);
    int imageWidth = stripWidth / 6;
    System.out.println("Width = " + imageWidth);
    g.clipRect(120, 0, imageWidth, stripHeight / 2);
    g.drawImage(image, 0 * imageWidth, 0, this);
    What code do i need to add more pieces to the board? I plan to make a ChessPiece array (8x8) which will holld all the chess pieces on the board. Should I hold this array in the board class to make drawing the pieces easier? Any other tips for game development would also be most welcome.
    Thanks

    cross post, I think.
    http://forum.java.sun.com/thread.jsp?thread=496287&forum=406

  • In need of checkers board

    I need a checkers board code written in Java. With, two differnet collors. Can someone please supply me with the code pleasE?

    Draw a chess board and allow placement of pawns and text,
    as a demo of Java's graphics capabilities.
    c:/Java/cs1073/cs1073/chessBoard/chessBoard.java
    Created: Thu Feb 06 09:49:28 2003
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ChessBoard extends JPanel implements MouseListener
    private Color[] squareColor = new Color[2];
    private final int NUMSQUARES = 8, WIDTH = 400, HEIGHT = 400;
    private int squareSize;
    private int boardSize;
    /* The constructor sets only some of the instance variables.
    The rest are set when the screen is painted.
    public ChessBoard()
    squareColor[0] = Color.lightGray;
    squareColor[1] = Color.gray;
    addMouseListener(this);
    setSize(WIDTH, HEIGHT);
    /* The paintComponent method is called every time the display
    needs to be repainted. Examples: When the window is
    first displayed, when the window is moved, resized,
    maximized, etc.
    Draws an 8x8 grid of alternately colored squares.
    Make the grid as large as it can be to fit in the
    current size of the drawing pane (which is the content pane
    for the JFrame).
    public void paintComponent (Graphics g)
    super.paintComponent(g); // Make sure background is cleared
    int paneHeight = this.getHeight();
    int paneWidth = this.getWidth();
    if (paneHeight < paneWidth)
    squareSize = paneHeight / NUMSQUARES;
    else
    squareSize = paneWidth / NUMSQUARES;
    boardSize = squareSize * NUMSQUARES;
    for (int row=0; row<NUMSQUARES; row++)
    { for (int col=0; col<NUMSQUARES; col++)
    { g.setColor(squareColor[(row+col)%2]);
    g.fillRect(col*squareSize, // x
    row*squareSize, // y
    squareSize, // width
    squareSize); // height
    } // end paintComponent
    /** The mouseClicked method responds to any mouse clicks.
    public void mousePressed(MouseEvent e)
    // Quit if the mouse press falls outside the board
    Point p = e.getPoint();
    int x = (int) p.getX();
    int y = (int) p.getY();
    if((x>boardSize) || (y>boardSize))
    return;
    // Determine which square (i.e. row, col) was selected
    int row = y / squareSize;
    int col = x / squareSize;
    if (row <= 1)
    drawPawn(row, col, Color.black);
    else
    if (row >= (NUMSQUARES-2))
    drawPawn(row, col, Color.white);
    else
    drawMessage(row, "Checkmate!");
    /******** QUESTIONS ****************
    1. What happens to the pawns when the window is resized?
    2. How could we alter the program to retain the pawns?
    // These four methods are not used, but must be
    // implemented because they are required by the
    // MouseListener interface.
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    /** The drawPawn method draws a pawn shape on the
    specified square in the chess board.
    public void drawPawn(int row, int col, Color c)
    Graphics g = this.getGraphics();
    g.setColor(c);
    // Calculate position of upper left corner of square
    int x = col*squareSize;
    int y = row*squareSize;
    // Draw circle for "head" of the pawn. Dimensions are
    // for the oval's "bounding box".
    g.fillOval(x+(2*squareSize/5), // x
    y+(squareSize/5), // y
    squareSize/5, // width
    squareSize/5); // height
    // Draw a polygon for the "body" of the pawn.
    Polygon body = new Polygon();
    body.addPoint(x+(2*squareSize/5),
    y+(2*squareSize/5));
    body.addPoint(x+(3*squareSize/5),
    y+(2*squareSize/5));
    body.addPoint(x+(4*squareSize/5),
    y+(4*squareSize/5));
    body.addPoint(x+(squareSize/5),
    y+(4*squareSize/5));
    g.fillPolygon(body);
    } // drawPawn
    /** The drawMessage method draws the given string in
    the given row of the chess board, centered
    horizontally.
    public void drawMessage(int row, String s)
    // Set a new font and color
    Font bigFont = new Font("Times New Roman", Font.BOLD, 36);
    Graphics g = this.getGraphics();
    g.setFont(bigFont);
    g.setColor(new Color(0.8F, 0.8F, 1.0F));
    // Determine the position of the string
    FontMetrics m = g.getFontMetrics();
    int x = (boardSize - m.stringWidth(s)) / 2;
    if (x < 0)
    x = 0;
    int y = ((row+1)*squareSize) - m.getDescent();
    if (y<0)
    y = m.getLeading() + m.getAscent();
    g.drawString(s, x, y);
    } // drawMessage
    public static void main(String[] args)
    {  JFrame f = new JFrame("Chess Board");
    ChessBoard board = new ChessBoard();
    f.getContentPane().add(board);
    f.setSize(board.WIDTH, board.HEIGHT);
    f.setVisible(true);
    f.addWindowListener
    ( new WindowAdapter()
    { public void windowClosing(WindowEvent e)
    { System.exit(0);
    } // end main
    } // end ChessBoard

  • Java chess moving problems

    Hi,
    I am producing a chess board where i need to move one piece on the board from one place to another. The pieces are made up of JLabels and i need to move them around the JPanel, any ideas how, i have posted the basic code which i have been working on :
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class Chess implements ActionListener
         private int tcpconnections = 1;
         private JTextField chatLine;
         private JTextArea chatText;
         private JPanel chessBoard;
         public void setupChat()
              JFrame frame01 = new JFrame("TCP Chat Window " + tcpconnections);
              frame01.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Set up the chat pane
                 JPanel chatPane = new JPanel(new FlowLayout());
                //text box
                chatText = new JTextArea(5, 30);
            chatText.setLineWrap(true);
            chatText.setEditable(false);
            chatText.setForeground(Color.blue);
            JScrollPane chatTextPane = new JScrollPane(chatText,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);      
            //text entering
            chatLine = new JTextField("Type Here!");
            chatLine.setPreferredSize(new Dimension(100,25));
            chatLine.addActionListener(this);
            //send button
            JButton button4 = new JButton("Send");
              button4.setActionCommand("send");
              button4.addActionListener(this);     
              //chessboard
              chessBoard = new JPanel();
              chessBoard.setLayout( new GridLayout(8, 8) );
            chessBoard.setPreferredSize(new Dimension (350, 350));
            chessBoard.setBounds(0, 0, 150, 150);
            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 ? Color.gray : Color.white );
                else
                    square.setBackground( i % 2 == 0 ? Color.white : Color.gray );
              JLabel piece = new JLabel( new ImageIcon("smallblackpawn.gif") );
            JPanel panel = (JPanel)chessBoard.getComponent( 0 );
            panel.add( piece );
              //adding
              chatPane.add(chessBoard);
              chatPane.add(chatTextPane);
              chatPane.add(chatLine);
              chatPane.add(button4);
             chatPane.setPreferredSize(new Dimension(350, 480));
              //adding to frame
              frame01.getContentPane().add(chatPane);
              frame01.pack();
              frame01.setLocationRelativeTo(null);
              frame01.setVisible(true);          
         public void actionPerformed(ActionEvent ae)
              String button = ae.getActionCommand();
              if (button.equals("send"))
                   JPanel from = (JPanel)chessBoard.getComponent(8);
                 JLabel chessPiece = (JLabel)from.getComponent(0);
                 JPanel to = (JPanel)chessBoard.getComponent(28);
         public Chess()
              setupChat();
         public static void  main (String[] args)
              new Chess();
    }The action listener is my attempt, any ideas cheers?!

    Hi,
    I am producing a chess board where i need to move one piece on the board from one place to another. The pieces are made up of JLabels and i need to move them around the JPanel, any ideas how, i have posted the basic code which i have been working on :
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class Chess implements ActionListener
         private int tcpconnections = 1;
         private JTextField chatLine;
         private JTextArea chatText;
         private JPanel chessBoard;
         public void setupChat()
              JFrame frame01 = new JFrame("TCP Chat Window " + tcpconnections);
              frame01.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Set up the chat pane
                 JPanel chatPane = new JPanel(new FlowLayout());
                //text box
                chatText = new JTextArea(5, 30);
            chatText.setLineWrap(true);
            chatText.setEditable(false);
            chatText.setForeground(Color.blue);
            JScrollPane chatTextPane = new JScrollPane(chatText,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);      
            //text entering
            chatLine = new JTextField("Type Here!");
            chatLine.setPreferredSize(new Dimension(100,25));
            chatLine.addActionListener(this);
            //send button
            JButton button4 = new JButton("Send");
              button4.setActionCommand("send");
              button4.addActionListener(this);     
              //chessboard
              chessBoard = new JPanel();
              chessBoard.setLayout( new GridLayout(8, 8) );
            chessBoard.setPreferredSize(new Dimension (350, 350));
            chessBoard.setBounds(0, 0, 150, 150);
            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 ? Color.gray : Color.white );
                else
                    square.setBackground( i % 2 == 0 ? Color.white : Color.gray );
              JLabel piece = new JLabel( new ImageIcon("smallblackpawn.gif") );
            JPanel panel = (JPanel)chessBoard.getComponent( 0 );
            panel.add( piece );
              //adding
              chatPane.add(chessBoard);
              chatPane.add(chatTextPane);
              chatPane.add(chatLine);
              chatPane.add(button4);
             chatPane.setPreferredSize(new Dimension(350, 480));
              //adding to frame
              frame01.getContentPane().add(chatPane);
              frame01.pack();
              frame01.setLocationRelativeTo(null);
              frame01.setVisible(true);          
         public void actionPerformed(ActionEvent ae)
              String button = ae.getActionCommand();
              if (button.equals("send"))
                   JPanel from = (JPanel)chessBoard.getComponent(8);
                 JLabel chessPiece = (JLabel)from.getComponent(0);
                 JPanel to = (JPanel)chessBoard.getComponent(28);
         public Chess()
              setupChat();
         public static void  main (String[] args)
              new Chess();
    }The action listener is my attempt, any ideas cheers?!

  • Chess: java swing help need

    Hi, I have just learn java swing and now creating a chess game. I have sucessfully create a board and able to display chess pieces on the board. By using JLayeredPane, I am able to use drag and drop for the piece. However, there is a problem which is that I can drop the chess piece off the board and the piece would disappear. I have try to solve this problem by trying to find the location that the chess piece is on, store it somewhere and check if the chess piece have been drop off bound. However, I could not manage to solve it. Also, I am very confuse with all these layer thing.
    Any suggestion would be very helpful. Thanks in advance
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class ChessBoard extends JFrame implements MouseListener, MouseMotionListener
    Object currentPosition;
    Color currentColor;
    Dimension boardSize = new Dimension(600, 600);
    JLayeredPane layeredPane;
    JPanel board;
    JPanel box;
    JLabel chessPiece;
    int xAdjustment;
    int yAdjustment;
    public ChessBoard()
    // 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
    board = new JPanel();
         // set "board" to the lowest layer (default_layer)
    layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
    board.setLayout( new GridLayout(8, 8) );
    board.setPreferredSize( boardSize );
    board.setBounds(0, 0, boardSize.width, boardSize.height);
         addShade();
         addPiece();
    public void addShade()
         for (int i = 0; i < 64; i++)
    box = new JPanel( new BorderLayout() );
    board.add( box, BorderLayout.CENTER );
         if( ((i / 8) % 2) == 0)
                   if( (i % 2) ==0)
                        box.setBackground(Color.lightGray);
                   } else {
                        box.setBackground( Color.white);
              } else {
                   if( (i % 2) ==0)
                        box.setBackground(Color.white);
                   } else {
                        box.setBackground(Color.lightGray);
    //Method for adding chess pieces to the board
    public void addPiece()
    // Add a few pieces to the board
         //black pieces
         for (int i = 0; i < 64; i++)
              //adding black pieces
              if (i < 8)
                   String fileName = i + ".gif";
                   JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );
                   JPanel panel = (JPanel)board.getComponent( i );
                   panel.add( blackPieces );
              //adding black pones
              if ((i > 7) && (i < 16))
                   String fileName = "8.gif";
                   JLabel blackPones = new JLabel( new ImageIcon( fileName ) );
                   JPanel panel = (JPanel)board.getComponent( i );
                   panel.add( blackPones );
              //jump to white position (Component 48)
              if (i == 16) i = 48;
              //adding white pones
              if(( i > 47 ) && (i < 56))
                   JLabel whitePones = new JLabel( new ImageIcon("48.gif") );
                   JPanel panel = (JPanel)board.getComponent( i );
                   panel.add( whitePones );
              //adding white pieces
              if (i > 55)
                   String fileName = i + ".gif";
                   JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );
                   JPanel panel = (JPanel)board.getComponent( i);
                   panel.add( whitePieces );
    ** Add the selected chess piece to the dragging layer so it can be moved
    public void mousePressed(MouseEvent e)
    chessPiece = null;
    Component c = board.findComponentAt(e.getX(), e.getY());
         c.setBackground(Color.red);
    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
    public void mouseReleased(MouseEvent e)
         Component c = board.findComponentAt(e.getX(), e.getY());
         int x = (int)c.getBounds().getX();
         int y = (int)c.getBounds().getY();
         System.out.println(c.getLocation());
         System.out.println(x + " "+ y);
         c.setBackground(currentColor);
    if (chessPiece == null) return;
    chessPiece.setVisible(false);
    if (c instanceof JLabel)
    Container parent = c.getParent();
         //remove the piece that is capture
    parent.remove(0);
    parent.add( chessPiece );
    else
    Container parent = (Container)c;
    parent.add( chessPiece );
    chessPiece.setVisible(true);
    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    private static void createAndShowGUI()
         //Make sure we have nice window decorations
         JFrame.setDefaultLookAndFeelDecorated(true);
         JFrame frame = new ChessBoard();
         frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
         //Display the window
         frame.pack();
         frame.setResizable( false );
         frame.setLocationRelativeTo( null );
         frame.setVisible(true);
    public static void main(String[] args)
         //Schedule a job for the event-dispatching thread:
         //creating and showing this application's GUI
         javax.swing.SwingUtilities.invokeLater( new Runnable()
                   public void run()
                        createAndShowGUI();
    }

    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class ChessBoardRx extends JFrame implements MouseListener, MouseMotionListener
        Object currentPosition;
        Color currentColor;
        Dimension boardSize = new Dimension(600, 600);
        JLayeredPane layeredPane;
        JPanel board;
        JPanel box;
        JLabel chessPiece;
        int xAdjustment;
        int yAdjustment;
        Container lastParent;
        public ChessBoardRx()
            // 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
            board = new JPanel();
            // set "board" to the lowest layer (default_layer)
            layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
            board.setLayout( new GridLayout(8, 8) );
            board.setPreferredSize( boardSize );
            board.setBounds(0, 0, boardSize.width, boardSize.height);
            addShade();
            addPiece();
    //        populateBoard();
        public void addShade()
            for (int i = 0; i < 64; i++)
                box = new JPanel( new BorderLayout() );
                board.add( box, BorderLayout.CENTER );
                if( ((i / 8) % 2) == 0)
                    if( (i % 2) ==0)
                        box.setBackground(Color.lightGray);
                    } else {
                        box.setBackground( Color.white);
                } else {
                    if( (i % 2) ==0)
                        box.setBackground(Color.white);
                    } else {
                        box.setBackground(Color.lightGray);
        //Method for adding chess pieces to the board
        public void addPiece()
            // Add a few pieces to the board
            //black pieces
            for (int i = 0; i < 64; i++)
                //adding black pieces
                if (i < 8)
                    String fileName = i + ".gif";
                    JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );
                    JPanel panel = (JPanel)board.getComponent( i );
                    panel.add( blackPieces );
                //adding black pones
                if ((i > 7) && (i < 16))
                    String fileName = "8.gif";
                    JLabel blackPones = new JLabel( new ImageIcon( fileName ) );
                    JPanel panel = (JPanel)board.getComponent( i );
                    panel.add( blackPones );
                //jump to white position (Component 48)
                if (i == 16) i = 48;
                //adding white pones
                if(( i > 47 ) && (i < 56))
                    JLabel whitePones = new JLabel( new ImageIcon("48.gif") );
                    JPanel panel = (JPanel)board.getComponent( i );
                    panel.add( whitePones );
                //adding white pieces
                if (i > 55)
                    String fileName = i + ".gif";
                    JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );
                    JPanel panel = (JPanel)board.getComponent( i);
                    panel.add( whitePieces );
        private void populateBoard() {
            int[][] pos = {
                { 9, 7, 5, 1, 3, 5, 7, 9 },
                { 8, 6, 4, 0, 2, 4, 6, 8 }
            for(int j = 0; j < 8; j++) {
                String fileName = "chessImages/" + pos[0][j] + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
            for(int j = 8; j < 16; j++) {
                String fileName = "chessImages/" + 11 + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
            for(int j = 56, k = 0; j < 64; j++, k++) {
                String fileName = "chessImages/" + pos[1][k] + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
            for(int j = 48; j < 56; j++) {
                String fileName = "chessImages/" + 10 + ".jpg";
                JLabel label = new JLabel( new ImageIcon( fileName ) );
                JPanel panel = (JPanel)board.getComponent( j );
                panel.add( label );
         ** Add the selected chess piece to the dragging layer so it can be moved
        public void mousePressed(MouseEvent e)
            chessPiece = null;
            Component c = board.findComponentAt(e.getX(), e.getY());
            c.setBackground(Color.red);
            if (c instanceof JPanel) return;
            lastParent = c.getParent();
            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
        public void mouseReleased(MouseEvent e)
            Component c = board.findComponentAt(e.getX(), e.getY());
            if(c == null) {
                layeredPane.remove(chessPiece);
                lastParent.add(chessPiece);
                Rectangle r = lastParent.getBounds();
                chessPiece.setLocation(r.x+xAdjustment, r.y+yAdjustment);
                lastParent.validate();
                lastParent.repaint();
                return;
            int x = (int)c.getBounds().getX();
            int y = (int)c.getBounds().getY();
            System.out.println(c.getLocation());
            System.out.println(x + " "+ y);
            c.setBackground(currentColor);
            if (chessPiece == null) return;
            chessPiece.setVisible(false);
            if (c instanceof JLabel)
                Container parent = c.getParent();
                //remove the piece that is capture
                parent.remove(0);
                parent.add( chessPiece );
            else
                Container parent = (Container)c;
                parent.add( chessPiece );
            chessPiece.setVisible(true);
        public void mouseClicked(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        private static void createAndShowGUI()
            //Make sure we have nice window decorations
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new ChessBoardRx();
            frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
            //Display the window
            frame.pack();
            frame.setResizable( false );
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI
            javax.swing.SwingUtilities.invokeLater( new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • Chess piece display problem

    Hi,
    I'm writing a chess game applet which will be played between to players over the internet. I'm currently working on the applet side at the moment and will develop the server side once I have completed the applet. I'm currently having problems displaying the actual chess pieces on the board at the moment. One of my design decisions was to make a Board class which extends a JPanel. I have painted the actual chess board squares within the Board JPanel. I then propose to draw the pieces on top of these squares (good design decsion? Can anyone suggest another way. I was thinking of having the images as a separate layer which will sit on top of the squares but wasn't sure how to implement it). The chess pieces are contained in a gif strip www.dur.ac.uk/j.d.p.murphy called ChessPieces02.gif . The problem I am having is to display several pieces at the same time. I lloked at a Java tutorial which suggested using g.clipRect() method to display a defined section of the strip (i.e. a single piece of a certain length). Below is the Board class that I am using.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Board extends JPanel{
    // Holds location of the mousePressed event
    Point point = null;
    // Size of a square square on the board
    int square_size = 40;
    // Mediatracker to monitor the loading of the images
    MediaTracker tracker;
    Image image;
    void init() {
    tracker = new MediaTracker(this);
    image = Toolkit.getDefaultToolkit().getImage("ChessPieces02.gif");
    tracker.addImage(image, 0);
    try {
    //Start downloading the images. Wait until they're loaded.
    tracker.waitForAll();
    } catch (InterruptedException e) {
    e.printStackTrace();
    throw new Error("error");
    if (tracker.isErrorAny()) {
    throw new Error("Could not load image");
    addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if (point == null)
    point = new Point(0, 0);
    int x = e.getX();
    int y = e.getY();
    System.out.println("X co-ord: " + x + " Y co-ord: " + y);
    // Floor the x and y values to the nearest unit of 25
    x = x - x % square_size;
    y = y - y % square_size;
    point.setLocation(x, y);
    repaint();
    System.out.println(point);
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    System.out.println("Chess Board Paint");
    // Loop to produce the black and white squares to represent the board
    for(int jj = 0; jj < 8; jj ++){
    for(int ii = 0; ii < 8; ii++){
    if(ii % 2 == jj % 2)
    g.setColor(Color.white);
    else
    g.setColor(Color.lightGray);
    g.fillRect(ii * square_size, jj * square_size, square_size, square_size );
    // Draw a highlighted square
    if (point != null){
    g.setColor(Color.green);
    g.fillRect( (int)point.getX(), (int)point.getY(), square_size, square_size);
    //imageStrip is the Image object representing the image strip.
    //imageWidth is the size of an individual image in the strip.
    //imageNumber is the number (from 0 to numImages)
    // of the image to paint.
    int stripWidth = image.getWidth(this);
    int stripHeight = image.getHeight(this);
    int imageWidth = stripWidth / 6;
    System.out.println("Width = " + imageWidth);
    g.clipRect(120, 0, imageWidth, stripHeight / 2);
    g.drawImage(image, 0 * imageWidth, 0, this);
    What code do i need to add more pieces to the board? I plan to make a ChessPiece array (8x8) which will holld all the chess pieces on the board. Should I hold this array in the board class to make drawing the pieces easier? Any other tips for game development would also be most welcome.
    Thanks

    And when a piece is taken, you set its position in the array to null, I guess.
    Well, after you draw the board, you can iterate through your array, then draw each piece if its not null, right?
    Or maybe for each square, first you draw the background, and then you draw the piece.
    So maybe you'd have something like:
    g.fillRect(ii * square_size, jj * square_size, square_size, square_size );
    pieces[ii][jj].draw(g);Though personally, I wouldn't code it like this. I'd make Board be a collection of Position objects, and each position object could contain a piece. Each position would also know its own background color, and its neighbors perhaps. Also it would know any of its own special properties, such as "if an opposing side's pawn lands here, it becomes a queen". You'd probably have a subclass of Position for positions that have special properties like that.

  • Programming a Chess-game - Design Tips

    Hello,
    I'm definatly not new to programming, but I'm a beginner at Java. Now I'm trying to program a little chess-game, which should teach me some OOP-techniques and to get some experience with Java.
    Well, I have some ideas for the game in mind and already realized a few things, but I want to do it the right way and get some advice from you.
    - The chess board:
    Currently, I have a class handling the drawing of the board, getting the screen-coordinates, etc.. The class "GameBoard" extends a JPanel and I overwrite the "paintComponent"-method to draw the board.
    I have a second class "Field" that stores informations of one field: What color the field is, which piece is placed on this field and which player "owns" it. Also, each one of these "Field" is getting passed its coordinates on the screen from "GameBoard". This helps me later, when I want to decide, if the field is clicked or not.
    Now, is this a good way to implement the board and the fields? I have another option, which would be, that I throw out the class "GameBoard" and instead have a "FieldHandler" class. Now, the class "Field" would extend JPanel, overwrite "paintComponent" and draw a square on the screen. "FieldHandler" gives each "Field" the information, if it should be black or white. "FieldHandler" would also calculate the x- and y-coordinates for each field.
    Is this method better? I don't really know performance wise, because I have to add 64 JPanels to the contentPane, which means, that all 64 Panels need to be drawn seperately. I don't know if this is a good way, but maybe it doesn't really matter. One advantage would be, that I could change the color of a field easily, for example when I click or hover it, which is not that nercassary, but still nice.
    Maybe there is an even better way?
    - The Pieces:
    Well, I don't really have a clue how to draw the pieces on the board. I could also make them extend JPanel and then draw the image onto some coordinates. But that doesn't seem too right. What about BufferedImage? I don't really know how to use it, neither when it is appropriate to use. I think I get more advantage of this, when I have animations, but that's definatly not my intention.
    The only thing I know is, that I can show an image on the screen with:
    ImageIcon test = new ImageIcon("Test.gif");
            public void paintComponents(Graphics g) {
                test.paintIcon(this, g, 100, 100);
            }But is this right or even way to do it? I'm somehow unsure, if an "ImageIcon" is right for a chess-piece. Any other ways of doing this?
    The "Piece"-class itself is just an interface that the classes "Knight", "King", etc. extend. It draws the piece onto the screen, set the owning player, sets the coordinates of a piece (with the help of the "Field"-class; The Field doesn't know it's exact coordinates, just "A7", "E3", etc.) and some other functions. All pieces are handled by a "PieceHandler", which could provide functions for counting all pieces on the field, initialising every piece and maybe some more things.
    Anybody got some advice on this approach?
    This should be enough for now. I would be very thankful for any kind help, I really want my first project to be as good as possible, since I want to learn OOP and Java better.

    - The chess board:
    Currently, I have a class handling the drawing of the
    board, getting the screen-coordinates, etc.. The
    class "GameBoard" extends a JPanel and I overwrite
    the "paintComponent"-method to draw the board.
    I have a second class "Field" that stores
    informations of one field: What color the field is,
    which piece is placed on this field and which player
    "owns" it. Also, each one of these "Field" is getting
    passed its coordinates on the screen from
    "GameBoard". This helps me later, when I want to
    decide, if the field is clicked or not.
    Now, is this a good way to implement the board and
    the fields? I have another option, which would be,
    that I throw out the class "GameBoard" and instead
    have a "FieldHandler" class. Now, the class "Field"
    would extend JPanel, overwrite "paintComponent" and
    draw a square on the screen. "FieldHandler" gives
    each "Field" the information, if it should be black
    or white. "FieldHandler" would also calculate the x-
    and y-coordinates for each field.
    Is this method better? I don't really knowWhat I'd do: just paint a chessboard pattern from a static image. Can be loaded from a file, or can be generated once dynamically. Don't care at all about fields.
    Have some pixel-to-field coordinate mapping somewhere. Should be nothing but a simple multiplication.
    Have a List of chess pieces. Have those know what they look like (maybe using a delegate object which contains an image), have those know where they are and where they can go. When painting, iterate over the list, transform the coordinates to pixels, get the UI delegate and paint its image. Why bother calculating 64 fields if all you have are 32 pieces or less? And whether a field is black or white doesn't matter to the game.
    When the user clicks onto the board, get the coordinates of the click and transform them to the field coordinates, that you can then look up in the list of figures. If you find one, you can still paint a marker onto the board and underneath the piece image.
    This is what I'd do. Other approaches might make sense as well..

Maybe you are looking for