我正在尝试创建一个与蛇具有相同系统的游戏。我创建了一个窗口,上面有一个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)。