0

我正在尝试创建一个与蛇具有相同系统的游戏。我创建了一个窗口,上面有一个JPanel,给它一个背景和画线来向用户展示正方形。

板为 600x600(601x601 以使所有人可见)。正方形是 20x20。

现在我正在尝试添加一种将彩色方块放在板上的方法,并检测彩色方块是否已经理想地存在。

public class CreateWindow extends JFrame {

    JPanel GameArea;
    static JLayeredPane Java_Window;
    Image Background;

    public void CreateWindow() {
        Dimension Panel_Size = new Dimension(800, 800);
        this.setSize(800,800);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible( true );
        this.setTitle("LineRage");
        getContentPane().setBackground(Color.white); 

        Java_Window = new JLayeredPane();
        this.add(Java_Window);
        Java_Window.setPreferredSize(Panel_Size);

        GameArea = new JPanel()
        {
            @Override
            public void paint(Graphics g) {
                g.setColor(Color.BLACK);
                g.fillRect(0,0,601,601);

                g.setColor(Color.GRAY);
                // Cut map into sections
                int x;
                //draw vertical lines
                for(x = 0; x < 31; x++) {
                    g.drawLine(x*20,0,x*20,600);
                }    
                //draw horizontal lines
                for(x = 0; x < 31; x++) {
                    g.drawLine(0,x*20,600,x*20);
                }     
            }

            public void PaintSquare (int x,int y) {
                //Check if square painted

                //Paint square
                Rectangle rect = new Rectangle(x, y, 20, 20);
                GameArea.add(rect);
            }
        };
        Java_Window.add(GameArea, JLayeredPane.DEFAULT_LAYER);
        GameArea.setBounds(20, 20, 601, 601);
        GameArea.setVisible(true);
    }
}

所以Java_Window(800x800) 有一个白色背景, Game_Area(601x601) 有黑色背景,有 32 条线沿着并穿过它以将其划分为正方形。

public void PaintSquare (int x, int y) {
    //Check if square painted

    //Paint square
    Rectangle square = new Rectangle(x, y, 20, 20);
    GameArea.add(square);
}

PaintSquare将从另一个对象(主游戏)调用并检查正方形的背景,如果它是空闲的,它将在其上绘制一个正方形(20x20)。

4

2 回答 2

1

您的确切问题尚不清楚,但这里有一些提示:

  • 使用paintComponent而不是paint在 Swing 中进行自定义绘画时。别忘了打电话super.paintComponent(g)
  • java.awt.Rectangle不是从JComponent(或Component)派生的,因此不能添加到容器中。
  • 采取的一种方法是使用fillRect并“绘制”正方形:

此外,在 Java 中,方法以小写字母开头。将这一点和上一点相加,您可以执行以下操作:

public void paintSquare(Graphics g, int x, int y) {
   g.fillRect(x, y, 20, 20);
}

在这里,该paintSquare方法将从 调用paintComponent

于 2013-03-04T12:58:31.600 回答
0

遵循Reimeus的建议,此外,您需要创建一个 GUI 模型。

在游戏模型类中定义一个与游戏板大小相同的 Rectangle 数组。

Rectangle[][] board;

这样,您可以在模型类中测试重叠的蛇,而不必担心已经绘制的内容。

您的paintComponent 方法变得非常简单。

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    model.draw(g);
}

请参阅此答案以获得更完整的解释。

于 2013-03-04T17:31:14.090 回答