черепаха-графика черепахи
Графика черепах-популярный способ познакомить детей с программированием.Она была частью оригинального языка программирования Logo,разработанного Уолли Ферзейгом,Сеймуром Папертом и Синтией Соломон в 1967 году.
Представьте себе роботизированную черепаху, начинающуюся с точки (0, 0) в плоскости xy. После import turtle дайте ей команду turtle.forward(15) , и она переместится (на экране!) На 15 пикселей в направлении, в котором смотрит, рисуя линию при движении. Дайте ему команду turtle.right(25) , и он повернется на месте на 25 градусов по часовой стрелке.
Черепаха может рисовать сложные фигуры с помощью программ,которые повторяют простые движения.
from turtle import * color( ‘red’ , ‘yellow’ ) begin_fill() while True : forward( 200 ) left( 170 ) if abs (pos()) < 1 : break end_fill() done()
Комбинируя эти и подобные команды,можно легко нарисовать замысловатые формы и рисунки.
Модуль turtle — это расширенная реализация одноименного модуля из стандартного дистрибутива Python до версии Python 2.5.
Он пытается сохранить достоинства старого модуля turtle и быть (почти) на 100% совместимым с ним. Это означает, в первую очередь, чтобы дать возможность обучающемуся программисту использовать все команды, классы и методы в интерактивном режиме при использовании модуля из IDLE, запущенного с ключом -n .
Модуль turtle предоставляет примитивы графики turtle как объектно-ориентированным, так и процедурно-ориентированным способами. Поскольку он использует tkinter для базовой графики, ему нужна версия Python, установленная с поддержкой Tk.
Объектно-ориентированный интерфейс использует по существу два+два класса:
- Класс TurtleScreen определяет графические окна как игровую площадку для рисования черепашек. Его конструктору требуется tkinter.Canvas или ScrolledCanvas в качестве аргумента. Его следует использовать, когда turtle используется как часть какого-либо приложения. Функция Screen() возвращает одноэлементный объект подкласса TurtleScreen . Эту функцию следует использовать, когда turtle используется как самостоятельный инструмент для создания графики. Поскольку это одноэлементный объект, наследование от его класса невозможно. Все методы TurtleScreen/Screen также существуют как функции,т.е.как часть процедурно-ориентированного интерфейса.
- RawTurtle (псевдоним: RawPen ) определяет объекты Turtle, которые рисуются на TurtleScreen . Его конструктору требуется Canvas, ScrolledCanvas или TurtleScreen в качестве аргумента, чтобы объекты RawTurtle знали, где рисовать. Производным от RawTurtle является подкласс Turtle (псевдоним: Pen ), который рисует на «экземпляре» Screen , который создается автоматически, если еще не существует. Все методы RawTurtle/Turtle также существуют в виде функций,т.е.являются частью интерфейса,ориентированного на процедуру.
Процедурный интерфейс предоставляет функции, производные от методов классов Screen и Turtle . Они имеют те же имена, что и соответствующие методы. Экранный объект создается автоматически всякий раз, когда вызывается функция, производная от метода Screen. (Безымянный) объект черепахи автоматически создается всякий раз, когда вызывается любая из функций, производных от метода черепахи.
Для использования нескольких черепах на экране необходимо использовать объектно-ориентированный интерфейс.
В следующей документации приводится список аргументов для функций. У методов, конечно же, есть дополнительный первый аргумент self, который здесь опускается.
Обзор доступных методов «Черепаха» и «Экран
Turtle methods
Turtle motion Двигаться и рисовать Расскажите о состоянии Черепахи Настройка и измерение Pen control Drawing state Color control Filling Больше контроля над чертежами Turtle state Visibility Appearance Using events Специальные черепашьи методы
Методы TurtleScreen/Экран черепахи
Window control Animation control Использование событий экрана Настройки и специальные методы Input methods Методы,специфичные для экрана
Методы RawTurtle/Turtle и соответствующие функции
Большинство примеров в этом разделе относятся к экземпляру Turtle с именем turtle .
Turtle motion
расстояние – число (целое или с плавающей запятой)
Переместите черепаху вперед на указанное расстояние в том направлении, в котором она движется.
>>> turtle.position() (0.00,0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00)
расстояние — число
Переместите черепаху назад на расстояние , противоположное направлению движения черепахи. Не меняйте направление черепахи.
>>> turtle.position() (0.00,0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00,0.00)
угол – число (целое или с плавающей запятой)
Поверните черепаху вправо на угловые единицы. (Единицами измерения по умолчанию являются градусы, но их можно установить с помощью функций Degrees degrees() и radians() .) Ориентация угла зависит от режима черепахи, см. mode() .
>>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.0
угол – число (целое или с плавающей запятой)
Поверните черепаху влево на угловые единицы. (Единицами измерения по умолчанию являются градусы, но их можно установить с помощью функций Degrees degrees() и radians() .) Ориентация угла зависит от режима черепахи, см. mode() .
>>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.0
Если y равно None , x должен быть парой координат или Vec2D (например, возвращаемым функцией pos() ).
Переместите черепашку в абсолютное положение.Если перо опущено,нарисуйте линию.Не изменяйте ориентацию черепахи.
>>> tp = turtle.pos() >>> tp (0.00,0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00)
x – число (целое или с плавающей запятой)
Установите первую координату черепахи на x , вторую координату оставьте без изменений.
>>> turtle.position() (0.00,240.00) >>> turtle.setx(10) >>> turtle.position() (10.00,240.00)
y — число (целое или с плавающей запятой)
Установите вторую координату черепахи на y , первую координату оставьте без изменений.
>>> turtle.position() (0.00,40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00,-10.00)
to_angle – число (целое или с плавающей запятой)
Установите ориентацию черепахи на to_angle . Вот несколько общих направлений в градусах:
turtle — Turtle graphics¶
Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle , give it the command turtle.forward(15) , and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25) , and it rotates in-place 25 degrees clockwise.
Turtle can draw intricate shapes using programs that repeat simple moves.
from turtle import * color('red', 'yellow') begin_fill() while True: forward(200) left(170) if abs(pos()) 1: break end_fill() done()
By combining together these and similar commands, intricate shapes and pictures can easily be drawn.
The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.
It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The object-oriented interface uses essentially two+two classes:
- The TurtleScreen class defines graphics windows as a playground for the drawing turtles. Its constructor needs a tkinter.Canvas or a ScrolledCanvas as argument. It should be used when turtle is used as part of some application. The function Screen() returns a singleton object of a TurtleScreen subclass. This function should be used when turtle is used as a standalone tool for doing graphics. As a singleton object, inheriting from its class is not possible. All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface.
- RawTurtle (alias: RawPen ) defines Turtle objects which draw on a TurtleScreen . Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw. Derived from RawTurtle is the subclass Turtle (alias: Pen ), which draws on “the” Screen instance which is automatically created, if not already present. All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure-oriented interface.
The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle . They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called.
To use multiple turtles on a screen one has to use the object-oriented interface.
In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.
Turtle Programming in Python
“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward(…) and turtle.right(…) which can move the turtle around. Commonly used turtle methods are :
Method | Parameter | Description |
---|---|---|
Turtle() | None | Creates and returns a new turtle object |
forward() | amount | Moves the turtle forward by the specified amount |
backward() | amount | Moves the turtle backward by the specified amount |
right() | angle | Turns the turtle clockwise |
left() | angle | Turns the turtle counterclockwise |
penup() | None | Picks up the turtle’s Pen |
pendown() | None | Puts down the turtle’s Pen |
up() | None | Picks up the turtle’s Pen |
down() | None | Puts down the turtle’s Pen |
color() | Color name | Changes the color of the turtle’s pen |
fillcolor() | Color name | Changes the color of the turtle will use to fill a polygon |
heading() | None | Returns the current heading |
position() | None | Returns the current position |
goto() | x, y | Move the turtle to position x,y |
begin_fill() | None | Remember the starting point for a filled polygon |
end_fill() | None | Close the polygon and fill with the current fill color |
dot() | None | Leave the dot at the current position |
stamp() | None | Leaves an impression of a turtle shape at the current location |
shape() | shapename | Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’ |
Plotting using Turtle
To make use of the turtle methods and functionalities, we need to import turtle.”turtle” comes packed with the standard Python package and need not be installed externally. The roadmap for executing a turtle program follows 4 steps:
- Import the turtle module
- Create a turtle to control.
- Draw around using the turtle methods.
- Run turtle.done().
So as stated above, before we can use turtle, we need to import it. We import it as :
from turtle import * # or import turtle
After importing the turtle library and making all the turtle functionalities available to us, we need to create a new drawing board(window) and a turtle. Let’s call the window as wn and the turtle as skk. So we code as:
wn = turtle.Screen() wn.bgcolor("light green") wn.title("Turtle") skk = turtle.Turtle()
Now that we have created the window and the turtle, we need to move the turtle. To move forward 100 pixels in the direction skk is facing, we code:
We have moved skk 100 pixels forward, Awesome! Now we complete the program with the done() function and We’re done!
So, we have created a program that draws a line 100 pixels long. We can draw various shapes and fill different colors using turtle methods. There’s plethora of functions and programs to be coded using the turtle library in python. Let’s learn to draw some of the basic shapes.
Shape 1: Square