In the first example, stars are drawn at random positions. By means of a simple conversion, random numbers are used to obtain random x and y coordinates between -180 and 180, which are useful for positioning the stars in a tile window. |
// Tu13.java import ch.aplu.turtle.*; import java.awt.Color; public class Tu13 { Turtle t = new Turtle(); public Tu13() { t.hideTurtle(); t.clear(Color.blue); t.setPenColor(Color.yellow); for (int i = 0; i < 50; i++) { double x = -180 + 360 * Math.random(); double y = -180 + 360 * Math.random(); star(x, y); } } void star(double x, double y) { t.setPos(x, y); t.fillToPoint(x, y); for (int i = 0; i < 6; i++) { t.forward(10); t.right(140); t.forward(10); t.left(80); } } public static void main(String[] args) { new Tu13(); } } |
clear(Color.blue) |
The background is coloured with the blue colour |
double x = -180 + 360 * Math.random() |
Math.random() returns a number between 0 and 1 with 16 decimal places, whereby the digits are random (e.g. 0.7290853765438503). To obtain random coordinates that fit into a Turtle window, we multiply these numbers by 360, resulting in a number between 0 and 360. By adding -180, we obtain coordinates between -180 and 180 |
star(x, y) | Call the star method with the variable values x, y |
setPos(x, y) | The turtle is moved to a random position (x, y) before the star is drawn |
fillToPoint(x, x) | The Turtle starts to draw a new star at the position (x, y). The fillToPoint() method fills the star figure from this point |
In the second example, random numbers are used to determine the pen colour, the length of the drawn line and the direction of movement of the turtle. This creates small works of art. A random colour is created by selecting a random integer between 0 and 255 for the red, blue and green RGB values: Color c = new Color((int)(Math.random() * 255),
|
wrap() |
When the Turtle arrives at the edge of the window, it is automatically moved to the opposite edge of the window (torus symmetry) |
Color c = new Color((int)(Math.random() * 255), (int)(Math.random() * 255), 255); |
(int) converts a decimal number into an integer by truncating the decimal places. The blue component is not chosen at random, but is given the highest possible value 255. This gives us a graphic in which the blue colours predominate |
if (Math.random() < 0.5) |
On average, 50% of the random numbers are smaller than 0.5, i.e. in about half of all cases the Turtle turns 90° to the right, otherwise to the left |
forward(60 * Math.random()) | The turtle moves forwards by a distance that has a random length between 0 and 60 |