Changing Colors
The default color for the line we drew is black, as we indicated in our code. You can change the colors to make your shapes look even better.
Look at the code below. It contains three integer variables called r
, g
, and b
.
public void act()
{
// Add your action code here.
int r = 255;
int g = 0;
int b = 124;
setColor(r, g, b);
moveAndDraw(50);
turn(90);
moveAndDraw(50);
}
Variables are a way of storing a value and giving it a name. For instance, there is a variable name r
with a value of 255
.
Run the code and see what happens.
The code doesn’t work because there is no setColor
method defined! We need to define it and also remove our default coloring in moveAndDraw
.
// New method to add
private void setColor(int r, int g, int b)
{
getWorld().getBackground().setColor(new Color(r, g, b));
}
// Modify existing moveAndDraw method; comment out the line that sets the color to be black.
private void moveAndDraw(int distance)
{
// getWorld().getBackground().setColor(Color.BLACK);
...
}
Try changing the values of the three variables, and see what happens. (Note: the maximum value is 255, and after this there will be no effect.) What do you think r
, g
, and b
represent?
Answer
r
, g
, and b
represent how much red, green, and blue will be used in the color. Each can have any value from 0 up to 255.
So to make yellow, you could try the following:
int r = 255;
int g = 255;
int b = 0;
RGB Colors
When we want to represent a color in a computer program, we can do this by defining the amounts of red, blue, and green that make up that color. These amounts are usually stored as a single byte and therefore as a number between 0 and 255.
Here’s a table showing some color values:
Red Green Blue Color
255 0 0 Red
0 255 0 Green
0 0 255 Blue
255 255 0 Yellow
255 0 255 Magenta
0 255 255 Cyan
You can find a nice color picker to play with at w3schools.
You can change the value of your variables either by setting them to a new value, or by increasing and decreasing them.
You can change the colour of the turtle as well. Run the code below to see what happens:
public void act()
{
// Add your action code here.
int r = 255;
int g = 0;
int b = 124;
setColor(r, g, b);
moveAndDraw(50);
turn(90);
moveAndDraw(50);
}
Challenge
Try to complete each of the challenges below.
- Complete the triangle above with a colour of your choice.
- Draw a square with sides which are four different shades of red.
- Draw a cross made of four different colors.
Hint 1
To change a color, you can just keep adding or subtracting values from the original variables.
Hint 2
So you could alter colors by doing the following:
// Add your action code here.
int r = 255;
int g = 0;
int b = 0;
setColor(r, g, b);
moveAndDraw(50);
turn(120);
r -= 20;
g += 20;
b += 5;
setColor(r, g, b);
moveAndDraw(50);
turn(120);