
2.2 第6课:小海龟的绝学
2.2.1 小海龟画线段

认识小海龟后,接下来看看小海龟的作图本领吧。先从简单的线段开始,看看小海龟是怎么画线段的。画线段只要小海龟往前走就好了,我们找到控制小海龟往前走的方法就可以了。
新建文件,依次单击File→New File选项,进入程序编辑界面。

编写代码:


将文件另存为海龟画线段.py。

依次单击Run→Run Module选项,运行程序。

小海龟在屏幕上画出了一条线段。

小海龟画线段使用的是turtle.forward(distance)方法,这个方法的作用是沿着小海龟朝着的方向,向前移动指定的距离distance。
turtle.forward(distance)控制小海龟向前走括号里的距离。如果是100,就走100;如果是500,就走500。


2.2.2 小海龟画正方形
学会了用小海龟画线段,接下来画个复杂点的图形——正方形。
在画之前,我们先分析正方形的画法。正方形是由4条相同长度的线段组成的,线段与线段之间的夹角是90度。要画成正方形,就需要每画完一条线段,小海龟都朝着同一个方向旋转90度。
画线段的方法我们已经掌握,只要学会了转弯的方法,就可以轻松地画出正方形。
转弯分为左转弯和右转弯,分别用turtle.left(angle)和turtle.right(angle)来实现。

转弯需要角度,大胆猜测一下方法中括号里填写什么呢?
· turtle.left(angle):将小海龟朝左转angle度,如turtle.left(90)就是将小海龟朝左转90度。
我们实验一下让小海龟朝左转90度,步骤如下:
新建文件,依次单击File→New File选项,进入程序编辑界面,编写如下代码:

保存文件并依次单击Run→Run Module选项,运行程序,可以很明显地看到效果。小海龟画了一条线段,然后朝左转了90度。

· turtle.right(angle):将小海龟朝右转angle度,如turtle.right(90)就是将小海龟朝右转90度。
我们实验一下让小海龟朝右转90度,步骤如下:
新建文件,依次单击File→New File选项,进入程序编辑界面,编写如下代码:

保存文件并依次单击Run→Run Module选项,运行程序,可以很明显地看到效果。小海龟画了一条线段,然后朝右转了90度。

学习了小海龟转向的方法,我们开始画正方形。以左上角为起点,先让小海龟往前走一段距离,然后让小海龟右转90度。


再往前走一段距离,再右转90度。


再往前走一段距离,再右转90度。


小海龟再往前走一段距离。


正方形就画成了。
汇总如下:
新建文件,依次单击File→New File选项,进入程序编辑界面,编写如下代码:

保存文件并依次单击Run→Run Module选项,运行程序,正方形就画成功了。

2.2.3 拓展长方形
我们再来尝试画一个长方形,长方形和正方形有什么不同呢?长方形4条边的长度是不一样的。我们尝试修改一下正方形的代码来画一个长方形。


保存文件并依次单击Run→Run Module选项,运行文件,长方形就画成功了。
