L4K ︰ Python Turtle《二》

道德經‧六十四章

其安易持,其未兆易謀。其脆易泮,其微易散。為之於未有,治之於未亂。合抱之木,生於毫末;九層之臺,起於累土;千里之行,始於足下。為者敗之,執者失之。是以聖人無為故無敗;無執故無失。民之從事,常於幾成而敗之。慎終如始,則無敗事,是以聖人欲不欲,不貴難得之貨;學不學,復衆人之所過,以輔萬物之自然 ,而不敢為。

 

『重複』 repeat 之概念深矣。積步能至千里,故而易曰︰

馴致其道,至堅冰也。

︰初六:履霜,堅冰至。
象傳︰履霜堅冰,陰始凝也。馴致其道,至堅冰也。

 

怎麼體會『簡單行為』之『重複』所產生的『壯觀現象』耶?想起早年讀過之一本很有啟發性的書︰

Turtle Geometry

The Computer as a Medium for Exploring Mathematics

Overview

Turtle Geometry presents an innovative program of mathematical discovery that demonstrates how the effective use of personal computers can profoundly change the nature of a student’s contact with mathematics. Using this book and a few simple computer programs, students can explore the properties of space by following an imaginary turtle across the screen.The concept of turtle geometry grew out of the Logo Group at MIT. Directed by Seymour Papert, author of Mindstorms, this group has done extensive work with preschool children, high school students and university undergraduates. Harold Abelson is an associate professor in the Department of Electrical Engineering and Computer Science at MIT. Andrea diSessa is an associate professor in the Graduate School of Education, University of California, Berkeley.

9780262510370

 

書裡有個範例,頗能展現個中三昧,特以 Python3 Turtle 將之改寫 ,映此歲末年終之思夫︰

pi@raspberrypi:~ $ python3
Python 3.4.2 (default, Oct 19 2014, 13:31:11) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import turtle
>>> turtle.setup(width=800, height=600)
>>> turtle.shape('turtle')
>>> turtle.mode('logo')
>>> 
>>> def thing():
...     turtle.forward(100)
...     turtle.right(90)
...     turtle.forward(100)
...     turtle.right(90)
...     turtle.forward(50)
...     turtle.right(90)
...     turtle.forward(50)
...     turtle.right(90)
...     turtle.forward(100)
...     turtle.right(90)
...     turtle.forward(25)
...     turtle.right(90)
...     turtle.forward(25)
...     turtle.right(90)
...     turtle.forward(50)
... 
>>> thing()
>>> turtle.reset()
>>> 
>>> def thing1():
...     for repeat in range(4):
...         thing()
... 
>>> thing1()
>>> turtle.reset()
>>> 
>>> def thing2():
...     for repeat in range(9):
...         thing()
...         turtle.right(10)
...         turtle.forward(50)
... 
>>> thing2()
>>> turtle.reset()
>>> 
>>> def thing3():
...     for repeat in range(8):
...         thing()
...         turtle.left(45)
...         turtle.forward(100)
... 
>>> thing3()
>>> 

 

【Thing】

python-turtle-graphics_thing

 

【Thing1】

python-turtle-graphics_thing1

 

【Thing2】

python-turtle-graphics_thing2

 

【Thing3】

python-turtle-graphics_thing3

 

 

 

 

 

 

 

 

 

 

L4K ︰ Python Turtle 《一》

且先摘要

24.1. turtleTurtle graphics

 

文本,打造一個 TurtleArt 相似之環境︰

24.1.2.2. Methods of TurtleScreen/Screen

Window control

turtle.reset()

Delete the turtle’s drawings from the screen, re-center the turtle and set variables to the default values.

>>> turtle.goto(0,-22)
>>> turtle.left(100)
>>> turtle.position()
(0.00,-22.00)
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0

 

Settings and special methods

turtle.mode(mode=None)

Parameters: mode – one of the strings “standard”, “logo” or “world”

Set turtle mode (“standard”, “logo” or “world”) and perform reset. If mode is not given, current mode is returned.

Mode “standard” is compatible with old turtle. Mode “logo” is compatible with most Logo turtle graphics. Mode “world” uses user-defined “world coordinates”. Attention: in this mode angles appear distorted if x/y unit-ratio doesn’t equal 1.

Mode Initial turtle heading positive angles
“standard” to the right (east) counterclockwise
“logo” upward (north) clockwise

 

>>> mode("logo")   # resets turtle heading to north
>>> mode()
'logo'

 

Methods specific to Screen

setup()

turtle.setup(width=_CFG[“width”], height=_CFG[“height”], startx=_CFG[“leftright”], starty=_CFG[“topbottom”])

Set the size and position of the main window. Default values of arguments are stored in the configuration dictionary and can be changed via a turtle.cfg file.

Parameters:
  • width – if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen
  • height – if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen
  • startx – if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if None, center window horizontally
  • starty – if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if None, center window vertically

 

>>> screen.setup (width=200, height=200, startx=0, starty=0)
>>>              # sets window to 200x200 pixels, in upper left of screen
>>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
>>>              # sets window to 75% of screen by 50% of screen and centers

 

Turtle motion

Move and draw
turtle.forward(distance)
turtle.fd(distance)
Parameters: distance – a number (integer or float)

Move the turtle forward by the specified distance, in the direction the turtle is headed.

>>> 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.backward(distance)
Parameters: distance – a number

Move the turtle backward by distance, opposite to the direction the turtle is headed. Do not change the turtle’s heading.

>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)
 turtle.right(angle)
turtle.rt(angle)
Parameters: angle – a number (integer or float)

Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on the turtle mode, see mode().

>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0

turtle.left(angle)

turtle.lt(angle)

Parameters: angle – a number (integer or float)

Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on the turtle mode, see mode().

>>> turtle.heading()
22.0
>>> turtle.left(45)
>>> turtle.heading()
67.0

 

Turtle state

Appearance

turtle.shape(name=None)

Parameters: name – a string which is a valid shapename

Set turtle shape to shape with given name or, if name is not given, return name of current shape. Shape with name must exist in the TurtleScreen’s shape dictionary. Initially there are the following polygon shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”. To learn about how to deal with shapes see Screen method register_shape().

>>> turtle.shape()
'classic'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'

 

然後使用 Python3 互動 Shell ,寫個打招呼程式︰

pi@raspberrypi:~ $ python3
Python 3.4.2 (default, Oct 19 2014, 13:31:11) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import turtle
>>> turtle.setup(width=800, height=600)
>>> turtle.shape('turtle')
>>> turtle.mode('logo')
>>> 
>>> def square():
...     for repeat in range(4): 
...         turtle.forward(100)
...         turtle.right(90)
... 
>>> 
>>> square()
>>>

 

確認符合預期也︰

python-turtle-graphics

 

 

 

 

 

 

 

 

 

L4K ︰小海龜繪圖《X》

雖然 TurtleArt

turtle-art-text-string-value

 

能寫作美麗之『遞迴』程式︰

Recursion

Recursion occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics and computer science, where a function being defined is applied within its own definition. While this apparently defines an infinite number of instances (function values), it is often done in such a way that no loop or infinite chain of references can occur.

Formal definitions

In mathematics and computer science, a class of objects or methods exhibit recursive behavior when they can be defined by two properties:

  1. A simple base case (or cases)—a terminating scenario that does not use recursion to produce an answer
  2. A set of rules that reduce all other cases toward the base case

For example, the following is a recursive definition of a person’s ancestors:

  • One’s parents are one’s ancestors (base case).
  • The ancestors of one’s ancestors are also one’s ancestors (recursion step).

The Fibonacci sequence is a classic example of recursion:

  \text{Fib}(0)=0\text{ as base case 1,}

  \text{Fib}(1)=1\text{ as base case 2,}

\text{For all integers }n>1,~\text{ Fib}(n):=\text{Fib}(n-1) + \text{Fib}(n-2).

Many mathematical axioms are based upon recursive rules. For example, the formal definition of the natural numbers by the Peano axioms can be described as: 0 is a natural number, and each natural number has a successor, which is also a natural number. By this base case and recursive rule, one can generate the set of all natural numbers.

Recursively defined mathematical objects include functions, sets, and especially fractals.

There are various more tongue-in-cheek “definitions” of recursion; see recursive humor.

……

The recursion theorem

In set theory, this is a theorem guaranteeing that recursively defined functions exist. Given a set X, an element a of X and a function f: X \rightarrow X, the theorem states that there is a unique  F: \mathbb{N} \rightarrow X (where \mathbb {N} denotes the set of natural numbers including zero) such that

F(0) = a
F(n + 1) = f(F(n))

for any natural number n.

Proof of uniqueness

Take two functions F: \mathbb{N} \rightarrow X and  G: \mathbb{N} \rightarrow X such that:

  F(0) = a
  G(0) = a
F(n + 1) = f(F(n))
G(n + 1) = f(G(n))

where a is an element of X.

It can be proved by mathematical induction that

F(n) = G(n) for all natural numbers n:

Base Case: F(0) = a = G(0) so the equality holds for  n=0.
Inductive Step: Suppose F(k) = G(k) for some  k\in \mathbb {N} . Then F(k+1) = f(F(k)) = f(G(k)) = G(k+1).
Hence F(k) = G(k) implies F(k+1) = G(k+1).

By induction, F(n) = G(n) for all  n\in \mathbb {N} .

───

 

終究像用『 λ表達式』之『Y組合子』表現『遞迴』般的咬文嚼字 ?故而特此介紹『派生三』 Python3 之『小海龜繪圖』模組︰

24.1. turtleTurtle graphics

Source code: Lib/turtle.py


24.1.1. Introduction

Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966.

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.

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:

  1. 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.

  2. 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.

Note

In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.

 

盼將『遞迴』之奧妙『視覺化』也!!

 

 

 

 

 

 

 

 

 

L4K ︰小海龜繪圖《IX》

圖文費疑猜?

turtle-art-if-then-else-if-then-else-operator-that-uses-boolean-operators-from-numbers-palette

 

流程難分明??

Flow Palette

TAflow.png

These blocks control program flow.

  • wait: pause program execution (unit is seconds)
  • forever: continuously repeat execute stack under the right flow
  • repeat: repeat the execution of stack under the right flow a specified number of times
  • if/then: conditional execution of the stack under the right flow (uses boolean operators found on the Number palette)
  • if/then/else: conditional execution of the stack under the center and right flows (uses boolean operators found on the Number palette)
  • vertical spacer
  • stop stack: interrupt execution
  • while: execute stack under right flow while the condition is true (uses boolean operators found on the Number palette) (Only available with Turtle Blocks)
  • until: execute stack under right flow until the condition is true (uses boolean operators found on the Number palette) (Only available with Turtle Blocks)

Note: Nesting while and/or until blocks is not always reliable. If you encounter an error, try putting the nested block in a separate stack, accessed with an action block.

 

會意細推敲!

turtle-art-greater-than-logical-greater-than-operator

 

遲早能貫通!!

turtle-art-number-used-as-numeric-input-in-mathematic-operators

 

 

 

 

 

 

 

 

 

L4K ︰小海龜繪圖《VIII》

Turtle Art 程式指南文本之作者用『鞋盒』

A SHOEBOX

When explaining boxes in workshops, I often use a shoebox. I have someone write a number on a piece of paper and put it in the shoebox. I then ask repeatedly, “What is the number in the box?” Once it is clear that we can reference the number in the shoebox, I have someone put a different number in the shoebox. Again I ask, “What is the number in the box?” The power of the box is that you can refer to it multiple times from multiple places in your program.

 

的想法解釋小海龜繪圖裡的『箱子』積木

2. Boxes

Boxes let you store an object, e.g., a number, and then refer to the object by using the name of the box. (Whenever you name a box, a new block is created on the Boxes palette that lets you access the content of the box.) This is used in a trivial way in the first example below: putting 100 in the box and then referencing the box from the Forward block. In the second example, we increase the value of the number stored in the box so each time the box is referenced by the Forward block, the value is larger.

Putting a value in a Box and then referring to the value in Box

We can change the value in a Box as the program runs. Here we add 10 to the value in the *Box( with each iteration. The result in this case is a spiral, since the turtle goes forward further with each step.

If we want to make a more complex change, we can store in the Box some computed value based on the current content of the Box. Here we multiply the content of the box by 1.2 and store the result in the Box. The result in this case is also a spiral, but one that grows geometrically instead of arithmetically.

In practice, the use of boxes is not unlike the use of keyword-value pairs in text-based programming languages. The keyword is the name of the Box and the value associated with the keyword is the value stored in the Box. You can have as many boxes as you’d like (until you run out of memory) and treat the boxes as if they were a dictionary. Note that the boxes are global, meaning all turtles and all action stacks share the same collection of boxes.

 

這個看似簡單直覺的概念

一個命了名的『箱子』,裡面裝著粅件。

用以表達『名稱‧賦值』這件事情。

若是問起『未賦值』的『空箱子』裡有什麼呢?

【命名為 my box 的箱子】

turtle-art-box-named-variable-numeric-value

 

【box 1 箱子積木】

turtle-art-box-1-variable-1-numeric-value

 

【命名為 box 1 的箱子】

turtle-art-box-1-variable-1-numeric-value_1

 

有點令人驚訝吧!語言之理解務求精確乎☆

 

turtle-art-flow-palette-of-flow-operators