java中的国际象棋棋盘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2535417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:59:43  来源:igfitidea点击:

chess board in java

javachess

提问by ranzy

This is my code below

这是我下面的代码

import javax.swing.*;
import java.awt.*;

public class board2 {

JFrame frame;
JPanel squares[][] = new JPanel[8][8];

public board2() {
    frame = new JFrame("Simplified Chess");
    frame.setSize(500, 500);
    frame.setLayout(new GridLayout(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.black);
            } else {
                squares[i][j].setBackground(Color.white);
            }   
            frame.add(squares[i][j]);
        }
    }

    squares[0][0].add(new JLabel(new ImageIcon("rookgreen.png")));
    squares[0][2].add(new JLabel(new ImageIcon("bishopgreen.png")));
    squares[0][4].add(new JLabel(new ImageIcon("kinggreen.png")));
    squares[0][5].add(new JLabel(new ImageIcon("bishopgreen.png")));
    squares[0][7].add(new JLabel(new ImageIcon("rookgreen.png")));

    squares[7][0].add(new JLabel(new ImageIcon("rookred.png")));
    squares[7][2].add(new JLabel(new ImageIcon("bishopred.png")));
    squares[7][4].add(new JLabel(new ImageIcon("kingred.png")));
    squares[7][5].add(new JLabel(new ImageIcon("bishopred.png")));
    squares[7][7].add(new JLabel(new ImageIcon("rookred.png")));

    for (int i = 0; i < 8; i++) {
        squares[1][i].add(new JLabel(new ImageIcon("pawngreen.png")));
        squares[6][i].add(new JLabel(new ImageIcon("pawnred.png")));
    }

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

public static void main(String[] args) {
    new board2();
}
}

I am trying to create a chess game sort of and I need help with putting labels on all sides of the board to label the rows and columns in either A-H or 1-8. I have no idea how to do it. Also later on I'll be adding a feature to drag and drop the pieces. Is it best to use JLabels? Anyways I would I go about putting the labels on the side? Thanks!

我正在尝试创建一种国际象棋游戏,我需要帮助将标签放在棋盘的所有侧面以标记 AH 或 1-8 中的行和列。我不知道该怎么做。稍后我将添加一个功能来拖放碎片。最好使用 JLabels 吗?无论如何,我会把标签放在一边吗?谢谢!

回答by John Kane

Go here. This shows some of the different layouts you can use. One thing you may want to look into is the grid layout. This would make it easy for you to add JPanels for the squares. You could also use it to add labels around the board, but that is just one way of doing it. Go through the examples on the site, there is example code too.

这里。这显示了您可以使用的一些不同布局。您可能想要研究的一件事是网格布局。这将使您轻松为正方形添加 JPanel。您也可以使用它在板周围添加标签,但这只是一种方法。通过网站上的示例,也有示例代码。

回答by Alexey Godin

I would like submitting a simple chess board drawing example using Unicode characters. There 3 classes involved into this tiny project.

我想提交一个使用 Unicode 字符的简单棋盘图示例。这个小项目涉及 3 个班级。

ChessLabel.java

国际象棋标签

import java.awt.Color;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.SwingConstants;


public class ChessLabel extends JLabel {

    Font font     = new Font("Ariel", Font.PLAIN, 24);
    Color bgLight = new Color(222, 184, 135);
    Color bgDark  = new Color(139, 69, 19);

    ChessLabel(String s)
    {
        super(s);
    }

    void set(int idx, int row)
    {
      setFont(font);
          setOpaque(true);
          setBackground((idx+row)%2 == 0 ? bgDark : bgLight);
          setHorizontalAlignment( SwingConstants.CENTER );
    }

}

Board.java

Board.java

import java.awt.*;
import javax.swing.JFrame;


public class Board extends JFrame {


   //Initialise arrays to hold panels and images of the board

    private ChessLabel[] labels = new ChessLabel[] {

    // white
    new ChessLabel("\u2656"), new ChessLabel("\u2658"), new ChessLabel("\u2657"), 
    new ChessLabel("\u2655"), new ChessLabel("\u2654"), new ChessLabel("\u2657"), 
    new ChessLabel("\u2658"), new ChessLabel("\u2656"), new ChessLabel("\u2659"), 
    new ChessLabel("\u2659"), new ChessLabel("\u2659"), new ChessLabel("\u2659"),
    new ChessLabel("\u2659"), new ChessLabel("\u2659"), new ChessLabel("\u2659"), 
    new  ChessLabel("\u2659"), 
    // empty
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "),
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "),
    // black
    new ChessLabel("\u265F"), new ChessLabel("\u265F"), new ChessLabel("\u265F"), 
    new ChessLabel("\u265F"), new ChessLabel("\u265F"), new ChessLabel("\u265F"), 
    new ChessLabel("\u265F"), new ChessLabel("\u265F"), new ChessLabel("\u265C"), 
    new ChessLabel("\u265E"), new ChessLabel("\u265D"), new ChessLabel("\u265B"), 
    new ChessLabel("\u265A"), new ChessLabel("\u265D"), new ChessLabel("\u265E"), 
    new ChessLabel("\u265C")
    };

    public Board() 
    {

    } // Board()

    void display()
    {
        setTitle("Chess board with unicode images");

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Container contentPane = getContentPane();
        GridLayout gridLayout = new GridLayout(8, 8);

        contentPane.setLayout(gridLayout);

        int row = -1;
        for (int i = 0; i < labels.length; i++) 
        {
            if(i % 8 == 0) row ++; // increment row number
            labels[i].set(i, row);
            contentPane.add(labels[i]);
        } // i

        setSize(600, 600);
        setLocationRelativeTo(null);
        setVisible(true);
     } // display()

} // class Board

And ChessBoardTest.java

ChessBoardTest.java

public class ChessBoardTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        Board board = new Board();

        board.display();
    }

}

回答by Олег Игоревич

 public void paintComponent(Graphics g) {                
    Graphics2D g2 = (Graphics2D)g;
    g2.setColor(Color.WHITE);
    int row = 0; 
    int col = 0;
    int sq = 65;

    while(row != (sq * 8)){
        if(row % 10 != 0 && col % 10 == 0)g2.setColor(Color.BLACK);
        if(row % 10 != 0 && col % 10 != 0)g2.setColor(Color.WHITE);
        if(row % 10 == 0 && col % 10 == 0)g2.setColor(Color.WHITE);
        if(row % 10 == 0 && col % 10 != 0)g2.setColor(Color.BLACK);

        g2.fillRect(row, col, sq, sq);
        row = row + sq;
        if(row == (sq * 8)){
            row = 0;
            col = col + sq;
            if(col == (sq * 8))break;
        }
    }


}

回答by Олег Игоревич

public class Pieces {

}

class Pawn_1 extends JComponent {

        private BufferedImage img;
        private Point imgPoint = new Point(0, 65);

        public Pawn_1() {
            try {
                img = ImageIO.read(new File("C:\imgs\b_pawn.png"));

            } catch (IOException ex) {
                ex.printStackTrace();
            }

            MouseAdapter ma = new MouseAdapter() {

                private Point offset;

                @Override
                public void mousePressed(MouseEvent e) {
                    Rectangle bounds = getImageBounds();
                    Point mp = e.getPoint();
                    if (bounds.contains(mp)) {
                        offset = new Point();
                        offset.x = mp.x - bounds.x;
                        offset.y = mp.y - bounds.y;
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    offset = null;
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    if (offset != null) {
                        Point mp = e.getPoint();
                        imgPoint.x = mp.x - offset.x;
                        imgPoint.y = mp.y - offset.y;
                        repaint();
                    }
                }

            };
            addMouseListener(ma);
            addMouseMotionListener(ma);
        }

        protected Rectangle getImageBounds() {
            Rectangle bounds = new Rectangle(0, 0, 0, 0);
            if (img != null) {
                bounds.setLocation(imgPoint);
                bounds.setSize(img.getWidth(), img.getHeight());
            }
            return bounds;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(65, 65);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.drawImage(img, imgPoint.x, imgPoint.y, this);
                g2d.dispose();
            }
        }
    }

回答by Sami

import java.applet.*;
import java.lang.*;
import java.awt.*;

public class E10_2 extends Applet
{
    public void paint(Graphics g)
    {
        for(int x = 10; x < 330; x+=80)
        {
            for(int y = 10; y < 330; y+=80)
            {
                g.drawRect(8,8,322,322);
                g.drawRect(9,9,322,322);
                g.fillRect(x,y,40,40);
                g.fillRect(x+40,y+40,40,40);
            }
        }
    }
}

回答by Gaurav Sali

import java.awt.*;
import java.applet.*;
public class MyChes extends Applet
{
    public void paint(Graphics g)
    {
        for(int i=50;i<=400;i+=50)
        {
           for(int j=50;j<=400;j+=50)
           {
               if((i+j)%100==0)
               {
                  g.setColor(Color.black);
                  g.fillRect(i,j,50,50);
               }
           }
           g.drawRect(50,50,400,400);
         }
     }
}