HomeTurtlegraficsGPanelRobotics WebTigerPython |
Python - Online |
Deutsch English |
YOU LEARN HERE... |
that you can create several Turtles in one programme and gain a first insight into object-oriented programming. |
EXAMPLES |
Example 1: Creating multiple Turtles In the previous examples, you used a global Turtle that does not need a name and can directly use all commands from the gturtle library. If you want to use several Turtles, you must give each Turtle a name.
Program: from gturtle import * john = Turtle() john.forward(50) john.right(90) john.forward(50) lia = Turtle() lia.setColor("red") lia.setPenColor("red") lia.back(50) lia.left(90) lia.forward(50)
Program: from gturtle import * john = Turtle() lia = Turtle() john.left(90) john.setPenColor("green") lia.right(90) lia.setPenColor("red") repeat 9: john.forward(150) lia.forward(150) john.left(160) lia.right(160)
Program: from gturtle import * def square(t): repeat 4: t.forward(40) t.right(90) t.forward(40) joe = Turtle() luka = Turtle() mia = Turtle() joe.setPenColor("red") luka.setPenColor("green") mia.setPenColor("blue") joe.setPos(-100, -100) luka.setPos(0,-100) mia.setPos(100, -100) repeat 5: square(joe) square(luka) square(mia)
Program: from gturtle import * def onMousePressed(x, y): t = Turtle() t.setPos(x, y) star(t) def star(t): t.setFillColor("red") t.startPath() repeat 4: t.forward(50) t.left(144) t.fillPath() makeTurtle(mousePressed = onMousePressed) hideTurtle() |
REMEMBER... |
With the instructions joe = Turtle(), luka = Turtle() etc. you can create several Turtles and have them drawn in the same graphics window. You use commands from the gturtle library, but each command must be preceded by the turtle name separated by a dot. This way of calling commands is characteristic of object-orientated programming (OOP). This programming technique is used in some professional programming languages such as Java or C++. |
TO SOLVE BY YOURSELF |
|