我要创建一个多彩板,从第一个方块开始为黑色,然后是蓝色、红色和黄色,这些方块对角线填充,并且没有空的彩色方块。我知道我的算法是错误的,但我不知道如何修复它。
目前,我的代码打印如下
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
public class Grid extends JPanel {
private static final long serialVersionUID = 1L;
public static final int GRID_COUNT = 8;
private Color[] colors = { Color.black, Color.yellow, Color.red,
Color.blue };
private int colorIndex = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphics = (Graphics2D) g;
graphics.setColor(Color.black);
Dimension size = getSize();
Insets insets = getInsets();
int w = size.width - insets.left - insets.right;
int h = size.height - insets.top - insets.bottom;
int sqrWidth = (int)((double)w / GRID_COUNT);
int sqrHeight = (int)((double)h / GRID_COUNT);
for (int row = 0; row < GRID_COUNT; row++) {
for (int col = 0; col < GRID_COUNT; col++) {
int x = (int) (row * (double) w / GRID_COUNT);
int y = (int) (col * (double) h / GRID_COUNT);
if ((row + col) % 2 == 0) {
int colorIndex = (row + col) % 4;
graphics.fillRect(x, y, sqrWidth, sqrHeight);
graphics.setColor(colors[colorIndex]);
colorIndex = (colorIndex + 1) % colors.length;
}
}
public static void main(String[] args) {
Grid grid = new Grid();
grid.setPreferredSize(new Dimension(400, 400));
JFrame frame = new JFrame("Grid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(grid);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
让我们看看这个模式:
Bk Gr Pn Bl
Gr Pn Bl Bk
Pn Bl Bk Gr
Bl Bk Gr Pn
但为了简单起见,我们调用 Bk 0、Gr 1、Pn 2 和 Bl 3 即可得到:
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
这种模式很容易通过计算产生tile[x][y] = (x + y) % 4
对于每个图块,并使用查找表将这些数字转换为颜色(使用枚举,或者不为图块分配整数值,而是使用整数作为颜色表中的查找并将颜色分配给图块)瓦)
如果您以前从未见过,% 4 表示“除以 4 并返回除法的余数”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)