我正在尝试为每个新作品(由 4 个瓷砖组成)设置一个新的随机颜色。要将整块绘制到板上,我在 Board 类中有一个绘制组件:
public void paintComponent(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
for(int row = 0; row < grid.length; row++) {
for(int col = 0; col < grid[row].length; col++) {
if(grid[row][col] != null) {
//if there is a non-null space, that is a Tetris piece.. fill it red
g.setColor(color);
g.fillRect(row * tilesize, col * tilesize, tilesize, tilesize);
g.setColor(Color.WHITE);
g.drawString("(" + row + ", " + col + ")", row * tilesize, col * tilesize+10);
}
}
}
}
你可以看到g.setColor()
给定一个全局变量color
在 Board 构造函数中定义:
color = setColor();
设置颜色():
public Color setColor() {
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
return randomColor;
}
并且当发生碰撞时,会生成一个新的片段,它会color
用新的随机颜色覆盖全局变量......
public void collisionCheck() {
if (newPiece.isCollision()){
newPiece = new Piece(this, randomPiece());
color = setColor();
}
}
这给了我这个结果:
所有形状都设置为相同的颜色......不是我想要的
然后,如果生成了新作品,它们的颜色都会改变……再次,这不是我想要的。
我知道问题是什么......这是我不应该覆盖全局颜色变量......但是如果我不从 board 类中分配颜色......而是从 tile 类中获取颜色,像这样:
g.setColor(grid[row][col].getColor());
public void paintComponent(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
for(int row = 0; row < grid.length; row++) {
for(int col = 0; col < grid[row].length; col++) {
if(grid[row][col] != null) {
//if there is a non-null space, that is a Tetris piece.. fill it red
g.setColor(grid[row][col].getColor());
g.fillRect(row * tilesize, col * tilesize, tilesize, tilesize);
g.setColor(Color.WHITE);
g.drawString("(" + row + ", " + col + ")", row * tilesize, col * tilesize+10);
}
}
}
}
然后每次重新绘制瓷砖时,每个单独的瓷砖都会产生一种新的颜色......
我的目标是给一个单块(由 4 个瓷砖组成)随机颜色......然后当一个新的块生成时,第一块保持它的颜色......并且新的块保持它的颜色......
有什么想法吗?
谢谢!