Using RGB values by generating a random 0-255
value for each component might not only create colors that are similar to the background, you can also end up with very similar colors for the balls.
I'd probably choose a less random approach and create colors that are guaranteed to be different instead. You could create a color for each ~32 degrees in the hue range and alternate the brightness or saturation (use HSV color-model instead of RGB).
So something like this:
numColors = 20;
stepSize = 360 / (numColors / 2 + 1); // hue step size
for(i = 0; i < numColors; i++){
color = HSV(i / 2 * stepSize, 0.5 + (i % 2) * 0.5, 1.0)
}
which will create 20 colors, nicely distributed. This assumes you're using integer math, so i = 0
and i = 1
will create the same hue value.
Of course this doesn't scale too well.. if you have 100 color values to create, the hue spacing might not be enough and you'll end up with similar colors again.
In that case you could also vary the V
(brightness) value.
I don't know what your background color is like, but HSV makes it also easier to compare colors (just compare the 3 components and don't forget that HUE is circular (0 == 360)).