gpt4 book ai didi

Java - 递归地交替循环颜色

转载 作者:行者123 更新时间:2023-11-30 03:38:37 24 4
gpt4 key购买 nike

我将如何修改棋盘格的当前代码,以便棋盘棋子的颜色递归地交替?需要明确的是,我不希望每件作品都是纯色的 - 我希望它们本身具有颜色交替的级别。例如,当前的黄色 block 将变为黄色和蓝色 block ,外部为黄色,然后是蓝色,然后是黄色,等等。我希望这有意义吗?我不相信我可以突出显示代码,但检查器片段在 checkerBoard 方法中的第一个嵌套 for 语句之后开始。有2种情况,第一种是顶部2行,第二种是底部2行。

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

public class Checkerboard extends Applet
{
private final int DIST = 100;
private final int SIZE = 1000;

public void checkerBoard(int row, int col, int x, int y, boolean b, Graphics g)
{
for ( row = 0; row < 8; row++ )
{
for ( col = 0; col < 8; col++)
{
x = col * 100;
y = row * 100;
if ( (row % 2) == (col % 2) )
g.setColor(Color.black);
else
g.setColor(Color.red);
g.fillRect(x, y, 100, 100);
}
}

for ( row = 0; row < 2; row++ )
{
for ( col = 0; col < 8; col++)
{
x = col * 100;
y = row * 100;
g.setColor(Color.yellow);
g.fillOval(x, y, 100, 100);
}
}

for ( row = 7; row > 5; row-- )
{
for ( col = 0; col < 8; col++)
{
x = col * 100;
y = row * 100;
g.setColor(Color.green);
g.fillOval(x, y, 100, 100);
}
}
}

public void paint(Graphics g)
{
checkerBoard(0, 0, 0, 0, true, g);
}
}

最佳答案

这就是你想要的

for ( row = 0;  row < 2;  row++ ) 
{
for ( col = 0; col < 8; col++)
{
for ( int ring = 0; ring < 5; ring++) {
x = col * 100 + (ring * 10);
y = row * 100 + (ring * 10);
if((ring & 1) == 0){
g.setColor(Color.yellow);
}else{
g.setColor(Color.blue);
}
g.fillOval(x, y, 100-(ring*20), 100-(ring*20));
}
}
}

递归方法就像,

private void drawCircle(int x, int y, int circleSize, int ringSize, Color primary, Color alternate, Graphics g){
if(circleSize > 0){
g.setColor(primary);
g.fillOval(x, y, circleSize,circleSize);
drawCircle(x+ringSize/2,y+ringSize/2,circleSize-ringSize,ringSize,alternate,primary, g);
}
}



for ( row = 0; row < 2; row++ )
{
for ( col = 0; col < 4; col++)
{
int y = row * 100;
int x = ((col * 2) + (col & 1)) * 100; // want to alternate squares
drawCircle(x, y, 100, 20, Color.Yellow, Color.Blue,g);
}
}

关于Java - 递归地交替循环颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27284475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com