# 請教各位大大教導如何寫顏色變數

## 1.一條線變藍 2.二條線變紅 3.三條線變黃

``````int num = 50, radius = 50;
int[] posX, posY, speedX, speedY;

void   setup() {
size(800, 600);
stroke(255);
strokeWeight(15);

posX = new int[num];
posY = new int[num];
speedX = new int[num];
speedY = new int[num];

for (int i=0; i<num; i++) {
posX[i] = int(random(width));
posY[i] = int(random(height));
speedX[i] = int(random(-5, 5));
speedY[i] = int(random(-5, 5));
}
}

void  draw() {
background(0);
for (int i=0; i<num; i++) {
ball(i);
}
}

void ball(int i) {
posX[i] = posX[i] + speedX[i];
posY[i] = posY[i] + speedY[i];

if (posX[i] > width) {
speedX[i] = -1 * speedX[i];
} else if (posX[i] < 0) {
speedX[i] = -1 * speedX[i];
}

if (posY[i] > height) {
speedY[i] = -1 * speedY[i];
} else if (posY[i] < 0) {
speedY[i] = -1 * speedY[i];
}
point(posX[i], posY[i]);

for (int j = 0; j < num; j++) {
if(dist(posX[i], posY[i], posX[j], posY[j]) < radius)  {
strokeWeight(1);
line(posX[i], posY[i], posX[j], posY[j]);
strokeWeight(15);
}
}
}
``````
1 Like

Ask you how to write color variables

Great, everyone.
The younger brother wants to ask questions about the ball. As long as the ball has a line, it will change color. The two lines will change to another color. The three lines will change color.
Then how should my code be better? Please give me a big advice.

1. One line turns blue
2. Two lines turn red
3. Three lines turn yellow
1 Like
``````int num = 50, radius = 50;

Ball[] balls = new Ball[num];

void setup() {
size(800, 600);
for (int i=0; i<num; balls[i++] = new Ball() );
strokeWeight(2);
}

void draw() {
background(0);
stroke(255);
for ( int i = 0; i < num; i++) {
for (int j = i+1; j < num; j++) {
if (dist(balls[i].px, balls[i].py, balls[j].px, balls[j].py) < radius) {
line(balls[i].px, balls[i].py, balls[j].px, balls[j].py);
balls[i].count++;
balls[j].count++;
}
}
}
for (int i=0; i<num; balls[i++].draw() );
}

class Ball {
float px, py, vx, vy;
int count = 0;
Ball() {
px = int(random(width));
py = int(random(height));
vx = int(random(-5, 5));
vy = int(random(-5, 5));
}
void draw() {
px+=vx;
py+=vy;
vx*=(px<0||px>width)?-1:1;
vy*=(py<0||py>height)?-1:1;
noStroke();
fill(255);
if( count == 1 ){
fill(0,0,255);
} else if( count == 2 ){
fill(255,0,0);
} else if( count == 3 ){
fill(255,255,0);
}
ellipse(px, py, 15, 15);
count = 0;
}
}
``````
2 Likes

Google Translate: Thank you for your great answer, thank you very much.

I don’t think I need Google translate to tell me that that was the answer he wanted.

4 Likes