精华内容
下载资源
问答
  • #18 turtle模块

    2019-10-01 02:42:23
    这一节继续记录模块,本节将记录Python中一个非常重要的画图模块——turtle,Here we go! 一、turtle模块 turtle(海龟)模块是Python中强大的内置画图模块,可以模拟真实的画图环境以及画图步骤来画图。通常,...

    前言

    这一节继续记录模块,本节将记录Python中一个非常重要的画图模块——turtle,Here we go!

    一、turtle模块

    turtle(海龟)模块是Python中强大的内置画图模块,可以模拟真实的画图环境以及画图步骤来画图。通常,我们画图需要两种工具,一个是画布,另一个是画笔;在turtle中,同样需要这两种工具,首先来学习画布的设置

    1. 画布

    画布无非不过设置画布大小、背景颜色、画布在桌面的位置,turtle模块中,有两种画布的设置方法,需要时可将它们结合起来使用:

    turtle.screensize(canvwidth=400, canvheight=300, bg=None)   「canvwidth表示画布宽、canvheight表示画布高、bg表示背景颜色」

    In [19]: import turtle                             # 导入turtle模块
    
    In [21]: turtle.screensize()                       # 设置默认尺寸
    Out[21]: (400, 300)
    
    In [22]: turtle.screensize(800,600)                # 将画布大小改为800x600,单位是像素
     
    In [23]: turtle.screensize(800,600,bg='green')     # 也可以设置背景颜色

    # 桌面上会出现一个画布,想要推出,输入turtle.done(),之后就可以点击画布上的x号关闭了

    turtle.setup(width=0.5, height=0.75, startx=None, starty=None)   「width表示画布宽、height表示画布高、startx表示画布在桌面上的坐标x位置、starty表示画布在桌面上的坐标y位置」

    In [26]: import turtle
    
    In [28]: turtle.setup()                # 设置默认画布大小
    
    In [29]: turtle.setup(800,600)         # 将画布大小改为800x600,单位是像素
    
    In [30]: turtle.setup(0.5,0.5)         # 将画布大小改为占当前屏幕的0.5x0.5,无单位,这是一个比例
    
    In [31]: turtle.setup(800,600,50,50)   # 设置画布初始位置为(50,50)

    # 注意:当宽高为大于1的整数时,单位为像素;当宽高为小于1的小数时,为占当前屏幕的比例

    如果要给有背景色的画布设置初始位置,则可以将上述两种方法结合起来使用:

    In [34]: import turtle
    
    In [36]: turtle.screensize(bg='green')   # 首先设置背景色
    
    In [37]: turtle.setup(800,600,200,200)   # 再设置宽高和位置

    2. 画笔

    说完了画布设置,就剩下画笔了,画笔这一部分有些复杂,因为不仅要设置画笔的粗细颜色等,还要给画笔前进后退旋转等动作

    2.1 画笔设置

    turtle.pensize(width=None)   「width表示画笔的宽度」

    In [39]: turtle.pensize(20)   # 设置画笔的宽度为20像素

    turtle.pencolor(*args)   「可以传入多种参数,例如直接传入颜色‘green’,也可以传入RGB配色0.2,0.8,0.55」

    In [42]: turtle.pencolor('green')   # 设置画笔颜色为绿色,直接传入颜色
    
    In [43]: turtle.pencolor(0.2, 0.8, 0.55)   # 传入RGB配色

    turtle.speed(speed=None)   「speed代表画笔速度」

    In [45]: turtle.speed(5)   # 设置画笔速度为5

    2.2 画笔动作

    turtle.forward(distance) / turtle.fd(distance)  「画笔前进,distance代表距离」

    turtle.backward(distance) / turtle.bk(distance) 「画笔后退,distance代表距离」

    In [50]: turtle.fd(200)   # 画笔前进200像素
    
    In [51]: turtle.bk(300)   # 画笔后退300像素

    turtle.seth(degree) 「画笔运动的方向,degree代表角度」

    In [77]: turtle.seth(90)   # 画笔运动方向为90度正方向
    
    # 注意:这个是轴的正方向,不是画笔的指向,有正负之分,90表示逆时针90度,-90表示顺时针90度

    turtle.left(degree) 「画笔逆时针旋转,degree代表角度」

    turtle.right(degree) 「画笔顺时针旋转,degree代表角度」

    In [52]: turtle.left(90)    # 画笔逆时针旋转90度
    
    In [54]: turtle.right(90)   # 画笔顺时针旋转90度

    turtle.goto(x,y) 「将画笔移动到坐标(x,y)处」

    In [55]: turtle.goto(300,300)   # 将画笔移动到坐标(300,300)处
    
    # 注意:假如画笔现在的位置为(10,10),使用上条命令后,画笔移动到(300,300)处,这时候会在画布上留下一条(10,10)到(300,300)的线段

    turtle.penup() 「提起画笔」

    In [56]: turtle.penup()     # 将画笔提起
    
    # 这时候使用前进后退或者goto方法都不会在画布上留下痕迹

    trutle.pendown() 「落下画笔」

    In [57]: turtle.pendown()   # 落下画笔
    
    # 之后使用前进后退或goto方法会在画布上留下痕迹

    turtle.circle(radius, extent=None, steps=None) 「画圆方法,radius表示半径、extent表示圆的角度、steps表示圆内切多边形的边数」

    In [59]: turtle.circle(50)           # 画一个半径为50像素的圆
    
    In [60]: turtle.circle(60,180)       # 画一个半径为60像素的半圆
    
    In [61]: turtle.circle(70,steps=6)   # 画一个内切于半径为70像素圆的6变形,注意:这是一个多边形,不是圆

    turtle.hideturtle() 「隐藏画笔箭头」

    turtle.showturtle() 「显示画笔箭头」

    In [62]: turtle.hideturtle()   # 隐藏画笔箭头
    
    In [63]: turtle.showturtle()   # 显示画笔箭头
    
    # turtle模块默认箭头时显示的,可以将其隐藏

    turtle.isvisile() 「返回画笔箭头是否存在的结果」

    In [71]: turtle.isvisible()   # 返回True,说明画笔箭头可见
    Out[71]: True
    
    In [72]: turtle.hideturtle()
    
    In [73]: turtle.isvisible()   # 返回False,说明画笔箭头不可见
    Out[73]: False

     turtle.fillcolor(*args) 「填充颜色设置,可以直接传入颜色,也可以传入RGB参数」

    In [65]: turtle.fillcolor('yellow')   # 设置填充颜色为黄色

    turtle.begin_fill() 「开始填充图形」

    turtle.end_fill() 「结束填充」

    In [66]: turtle.begin_fill()   # 准备开始填充图形
    
    In [67]: turtle.end_fill()     # 结束填充

    turtle.flling() 「返回当前图形是否在填充的结果」

    In [68]: turtle.filling()      # 返回False,说明当前图形不在填充
    Out[68]: False
    
    In [69]: turtle.begin_fill()
    
    In [70]: turtle.filling()      # 返回True,说明当前图形正在填充
    Out[70]: True

    turtle.undo() 「撤销上一个画笔动作」

    In [74]: turtle.undo()   # 撤销上一个画笔动作

    turtle.clear() 「清空画布,但保留当前画笔状态和位置」

    In [75]: turtle.clear()   # 清空画布,保留画笔状态和位置

    turtle.reset() 「清空画布,画笔不再保留原有状态和位置」

    In [76]: turtle.reset()   # 清空画布,不会保留画笔状态和位置
    
    # 注意:画布属性没有被重置,依然保留原画布大小、背景色和画布位置

    turtle.write(s[,font=("font-name",font_size,"font_type")])) 「画笔写字,s代表要写的字符串、font-name代表字体名称、font-size代表字体大小、font-type代表字体类型」

    In [78]: turtle.write('MinuteSheep')    # 写下MinuteSheep

    turtle.done() 「完成画作」

    In [79]: turtle.done()   # 完成画作
    
    # 此时可以点击图画上的x号关闭图画了

    3. 示例

    3.1 示例一:太阳花   「来自官网」

     1 from turtle import *
     2 color('red', 'yellow')   # 画笔颜色为red,填充颜色为yellow
     3 begin_fill()   # 开始填充
     4 while True:
     5     forward(200)
     6     left(170)
     7     if abs(pos()) < 1:
     8         break
     9 end_fill()
    10 done()

     效果如图: 

    3.2 示例二:小猪佩奇   「来自:https://www.cnblogs.com/nowgood/p/turtle.html#_nav_11

      1 # coding:utf-8
      2 import turtle as t
      3 # 绘制小猪佩奇
      4 # =======================================
      5 
      6 t.pensize(4)
      7 t.hideturtle()
      8 t.colormode(255)
      9 t.color((255, 155, 192), "pink")
     10 t.setup(840, 500)
     11 t.speed(10)
     12 
     13 # 鼻子
     14 t.pu()
     15 t.goto(-100,100)
     16 t.pd()
     17 t.seth(-30)
     18 t.begin_fill()
     19 a = 0.4
     20 for i in range(120):
     21     if 0 <= i < 30 or 60 <= i < 90:
     22         a = a+0.08
     23         t.lt(3)  # 向左转3度
     24         t.fd(a)  # 向前走a的步长
     25     else:
     26         a = a-0.08
     27         t.lt(3)
     28         t.fd(a)
     29         t.end_fill()
     30 
     31 t.pu()
     32 t.seth(90)
     33 t.fd(25)
     34 t.seth(0)
     35 t.fd(10)
     36 t.pd()
     37 t.pencolor(255, 155, 192)
     38 t.seth(10)
     39 t.begin_fill()
     40 t.circle(5)
     41 t.color(160, 82, 45)
     42 t.end_fill()
     43 
     44 t.pu()
     45 t.seth(0)
     46 t.fd(20)
     47 t.pd()
     48 t.pencolor(255, 155, 192)
     49 t.seth(10)
     50 t.begin_fill()
     51 t.circle(5)
     52 t.color(160, 82, 45)
     53 t.end_fill()
     54 
     55 #
     56 t.color((255, 155, 192), "pink")
     57 t.pu()
     58 t.seth(90)
     59 t.fd(41)
     60 t.seth(0)
     61 t.fd(0)
     62 t.pd()
     63 t.begin_fill()
     64 t.seth(180)
     65 t.circle(300, -30)
     66 t.circle(100, -60)
     67 t.circle(80, -100)
     68 t.circle(150, -20)
     69 t.circle(60, -95)
     70 t.seth(161)
     71 t.circle(-300, 15)
     72 t.pu()
     73 t.goto(-100, 100)
     74 t.pd()
     75 t.seth(-30)
     76 a = 0.4
     77 for i in range(60):
     78     if 0 <= i < 30 or 60 <= i <90:
     79         a = a+0.08
     80         t.lt(3)  # 向左转3度
     81         t.fd(a)  # 向前走a的步长
     82     else:
     83         a = a-0.08
     84         t.lt(3)
     85         t.fd(a)
     86         t.end_fill()
     87 
     88 # 耳朵
     89 t.color((255, 155, 192), "pink")
     90 t.pu()
     91 t.seth(90)
     92 t.fd(-7)
     93 t.seth(0)
     94 t.fd(70)
     95 t.pd()
     96 t.begin_fill()
     97 t.seth(100)
     98 t.circle(-50, 50)
     99 t.circle(-10, 120)
    100 t.circle(-50, 54)
    101 t.end_fill()
    102 
    103 t.pu()
    104 t.seth(90)
    105 t.fd(-12)
    106 t.seth(0)
    107 t.fd(30)
    108 t.pd()
    109 t.begin_fill()
    110 t.seth(100)
    111 t.circle(-50, 50)
    112 t.circle(-10, 120)
    113 t.circle(-50, 56)
    114 t.end_fill()
    115 
    116 #眼睛
    117 t.color((255, 155, 192), "white")
    118 t.pu()
    119 t.seth(90)
    120 t.fd(-20)
    121 t.seth(0)
    122 t.fd(-95)
    123 t.pd()
    124 t.begin_fill()
    125 t.circle(15)
    126 t.end_fill()
    127 
    128 t.color("black")
    129 t.pu()
    130 t.seth(90)
    131 t.fd(12)
    132 t.seth(0)
    133 t.fd(-3)
    134 t.pd()
    135 t.begin_fill()
    136 t.circle(3)
    137 t.end_fill()
    138 
    139 t.color((255, 155, 192), "white")
    140 t.pu()
    141 t.seth(90)
    142 t.fd(-25)
    143 t.seth(0)
    144 t.fd(40)
    145 t.pd()
    146 t.begin_fill()
    147 t.circle(15)
    148 t.end_fill()
    149 
    150 t.color("black")
    151 t.pu()
    152 t.seth(90)
    153 t.fd(12)
    154 t.seth(0)
    155 t.fd(-3)
    156 t.pd()
    157 t.begin_fill()
    158 t.circle(3)
    159 t.end_fill()
    160 
    161 #
    162 t.color((255, 155, 192))
    163 t.pu()
    164 t.seth(90)
    165 t.fd(-95)
    166 t.seth(0)
    167 t.fd(65)
    168 t.pd()
    169 t.begin_fill()
    170 t.circle(30)
    171 t.end_fill()
    172 
    173 #
    174 t.color(239, 69, 19)
    175 t.pu()
    176 t.seth(90)
    177 t.fd(15)
    178 t.seth(0)
    179 t.fd(-100)
    180 t.pd()
    181 t.seth(-80)
    182 t.circle(30, 40)
    183 t.circle(40, 80)
    184 
    185 # 身体
    186 t.color("red", (255, 99, 71))
    187 t.pu()
    188 t.seth(90)
    189 t.fd(-20)
    190 t.seth(0)
    191 t.fd(-78)
    192 t.pd()
    193 t.begin_fill()
    194 t.seth(-130)
    195 t.circle(100,10)
    196 t.circle(300,30)
    197 t.seth(0)
    198 t.fd(230)
    199 t.seth(90)
    200 t.circle(300,30)
    201 t.circle(100,3)
    202 t.color((255,155,192),(255,100,100))
    203 t.seth(-135)
    204 t.circle(-80,63)
    205 t.circle(-150,24)
    206 t.end_fill()
    207 
    208 #
    209 t.color((255,155,192))
    210 t.pu()
    211 t.seth(90)
    212 t.fd(-40)
    213 t.seth(0)
    214 t.fd(-27)
    215 t.pd()
    216 t.seth(-160)
    217 t.circle(300,15)
    218 t.pu()
    219 t.seth(90)
    220 t.fd(15)
    221 t.seth(0)
    222 t.fd(0)
    223 t.pd()
    224 t.seth(-10)
    225 t.circle(-20,90)
    226 
    227 t.pu()
    228 t.seth(90)
    229 t.fd(30)
    230 t.seth(0)
    231 t.fd(237)
    232 t.pd()
    233 t.seth(-20)
    234 t.circle(-300,15)
    235 t.pu()
    236 t.seth(90)
    237 t.fd(20)
    238 t.seth(0)
    239 t.fd(0)
    240 t.pd()
    241 t.seth(-170)
    242 t.circle(20,90)
    243 
    244 #
    245 t.pensize(10)
    246 t.color((240,128,128))
    247 t.pu()
    248 t.seth(90)
    249 t.fd(-75)
    250 t.seth(0)
    251 t.fd(-180)
    252 t.pd()
    253 t.seth(-90)
    254 t.fd(40)
    255 t.seth(-180)
    256 t.color("black")
    257 t.pensize(15)
    258 t.fd(20)
    259 
    260 t.pensize(10)
    261 t.color((240, 128, 128))
    262 t.pu()
    263 t.seth(90)
    264 t.fd(40)
    265 t.seth(0)
    266 t.fd(90)
    267 t.pd()
    268 t.seth(-90)
    269 t.fd(40)
    270 t.seth(-180)
    271 t.color("black")
    272 t.pensize(15)
    273 t.fd(20)
    274 
    275 # 尾巴
    276 t.pensize(4)
    277 t.color((255, 155, 192))
    278 t.pu()
    279 t.seth(90)
    280 t.fd(70)
    281 t.seth(0)
    282 t.fd(95)
    283 t.pd()
    284 t.seth(0)
    285 t.circle(70, 20)
    286 t.circle(10, 330)
    287 t.circle(70, 30)
    288 t.done()

    效果如图: 

    转载于:https://www.cnblogs.com/minutesheep/p/10356023.html

    展开全文
  • Windows IDLE 环境下,代码可直接使用**1,绘制奥运五环**第一步:import 导入turtle模块第二步:画圆第三部:run运行代码如下:import turtleturtle.width(20) # 确定圆圈的宽度turtle.circle(60) # 确定圆的半径...

    Windows IDLE 环境下,代码可直接使用

    **

    1,绘制奥运五环

    **

    第一步:import 导入turtle模块

    第二步:画圆

    第三部:run运行

    代码如下:

    import turtle

    turtle.width(20) # 确定圆圈的宽度

    turtle.circle(60) # 确定圆的半径

    turtle.penup()

    turtle.forward(140)

    turtle.pendown()

    turtle.color("red") # 确定圆圈的颜色

    turtle.circle(60)

    turtle.penup()

    turtle.forward(140)

    turtle.pendown()

    turtle.color("yellow")

    turtle.circle(60)

    turtle.penup()

    turtle.goto(210, -50)

    turtle.pendown()

    turtle.color("blue")

    turtle.circle(60)

    turtle.penup()

    turtle.goto(60, -50)

    turtle.pendown()

    turtle.color("green")

    turtle.circle(60)

    运行结果如图:

    **

    2,绘制棋盘

    **

    import turtle

    t = turtle.Pen()

    t.width(2)

    for i in range(0, 19):

    t.penup()

    t.goto(0, 15*i)

    t.pendown()

    t.forward(18*15)

    t.left(90)

    for i in range(0, 19):

    t.penup()

    t.goto(15*i, 0)

    t.pendown()

    t.forward(18*15)

    turtle.done()

    运行结果如下:

    **

    以上

    **

    如有错误,欢迎指正

    欢迎 复制 粘贴 评论 转发 点赞

    **

    轻轻一点 好运连连

    **

    展开全文
  • turtle库基本介绍turtle库,1969年诞生,被Python语言借鉴,成为Python的标准库。turtle名称含义为“海龟”,我们想象一只海龟,位于显示器上窗体的正中心,在画布上游走,它游走的轨迹就形成了绘制的图形。海龟的...

    :本文所有代码均经过Python 3.7实际运行检验,保证其严谨性。

    turtle库基本介绍

    turtle库,1969年诞生,被Python语言借鉴,成为Python的标准库。

    turtle名称含义为“海龟”,我们想象一只海龟,位于显示器上窗体的正中心,在画布上游走,它游走的轨迹就形成了绘制的图形。海龟的运动是由程序控制的,它可以变换颜色,改变尺寸、大小等。利用turtle可以制作很多复杂的绘图。

    turtle库绘图窗体布局
    turtle.setup(width, height[, startx, starty])

    setup()设置窗体大小及位置。width, height分别是窗体本身的宽度和高度,如下图所示。startx, starty是可选参数。

    7fc6d48233580ae69762b31bb244d873.png

    turtle的绘图窗体

    turtle空间坐标体系
    4df174a509c2a7dd06a1eb305df17485.png

    turtle空间坐标体系

    dad47ca17b22888e614c60af9c7e56d9.png

    turtle坐标

    5e726959ded7cb3cd597026803558366.png

    turtle坐标移动

    turtle绝对角度坐标体系
    d9262b62bcda2c23c2cd4e8c57028def.png

    turtle绝对角度的坐标系

    turtle.seth(angle)用来改变海龟行进方向,参数angle为绝对角度(角度制的度数值,不带°号)。

    8fe23a49d205ec4eabdb7581ce77f2c3.png

    turtle海龟角度的坐标系

    用turtle.right(angle)和turtle.left(angle)来改变turtle行进的方向角度。

    某个turtle绘图示例如下:

    import turtleturtle.left(45)turtle.fd(150)turtle.right(135)turtle.fd(300)turtle.left(135)turtle.fd(150)
    RGB色彩体系

    RGB由三种颜色构成的万物色。

    • RGB指红蓝绿三个通道的颜色组合。
    • 覆盖视力所能感知的所有颜色。
    • RGB每色取值范围是0~255整数,或0~1小数。

    turtle默认使用RGB的小数值改变颜色,turtle.colormode(mode)

    • 1.0:RGB小数值模式。
    • 255:RGB整数值模式。

    拿紫色的RGB整数值模式(160, 32, 240)做例子,将其每个颜色数值除以255,保留两位小数,就能得到其RGB小数值模式(160/255, 32/255, 240/255),即(0.63, 0.13, 0.94)。

    b28a0d98651fb2081f00b90df70aa5b1.png

    常用的RGB色彩1

    92d235431f60c30604d4fb05ed723658.png

    常用的RGB色彩2

    turtle画笔控制函数

    画笔操作后一直有效,一般成对出现。

    -turtle.penup(),别名turtle.pu()。

    抬起画笔,海龟在飞行。这时的轨迹不在画布上形成痕迹。

    -turtle.pendown(),别名turtle.pd()。

    落下画笔,海龟在爬行。这时的轨迹在画布上形成痕迹。

    turtle.pu()和turtle.pd()是成对出现的。

    -turtle.pensize(width) 别名 turtle.width(width)。

    画笔宽度,海龟的腰围。

    -turtle.pencolor(color),color为颜色字符串或RGB值。

    画笔颜色,海龟在涂装。

    pencolor(color)的color参数可以有三种形式:

    • 颜色字符串:-turtle.pencolor("purple")
    • RGB的小数值:turtle.pencolor(0.63, 0.13, 0.94)
    • RGB的元组值:turtle.pencolor((0.63, 0.13, 0.94))
    turtle运动控制函数

    控制海龟行进:走直线&走曲线:

    -turtle.forward(d) 别名 turtle.fd(d),走直线

    向前行进,海龟走直线。d:行进距离,可以为负数。

    -turtle.circle(r, extend=None),走曲线

    根据半径r绘制extent角度的弧形。r是默认圆心在海龟左侧r距离的位置。extent是绘制角度,默认是360°即整圆;当extent为正数时,圆从turtle当前位置逆时针方向(即顺象限方向)画圆心角为|extent|角度(角度制)的弧形;当extent为负数时,圆从turtle当前位置顺时针方向(即逆象限方向)画圆心角为|extent|角度(角度制)的弧形。

    turtle方向控制函数

    控制海龟面对方向:绝对角度&海龟角度

    -turtle.setheading(angle) 别名turtle.seth(angle)——绝对角度 改变行进方向,海龟走的绝对角度。angle:改变行进方向的绝对角度。

    -turtle.left(angle), turtle.right(angle)

    改变行进方向,海龟走的海龟角度。angle:改变行进方向的海龟角度。

    “Python蟒蛇绘制”代码实例

    import turtleturtle.setup(650, 350, 200, 200)turtle.penup()turtle.fd(-250)turtle.pendown()turtle.pensize(25)turtle.pencolor("purple")turtle.seth(-40)for i in range(4):    turtle.circle(40, 80)    turtle.circle(-40, 80)turtle.circle(40, 80/2)turtle.fd(40)turtle.circle(16, 180)turtle.fd(40 * 2/3)turtle.done() # 用来保持程序的图象存在。若没有这行,程序运行完成后会自动退出。

    turtle.done() 用来停止画笔绘制,但绘图窗体不关闭。

    To be continued.

    展开全文
  • Data Processing and Visulisation with Python Python Exercise 18Data Processing and Visulisation with Python """ Python Exercise 18 for the class of Data Processing and ...import turtle import r

    Data Processing and Visulisation with Python

    """
    Python Exercise 18
    for the class of
    Data Processing and Visulisation with Python
    2020-2021-1
    
    """
    
    # libraries to be used
    import turtle
    import random
    
    # initialize
    """
    feel free to change these settings and check the output, 
    or you could get these settings from user input
    """
    maxHeight = 700
    maxWidth = 1200
    rowCount = 70
    columnCount = 120
    screenPaddingWidth = 8
    screenPaddingHeight = 8
    backGroundColor = 'white'
    lineColor = 'black'
    
    
    """
    the following variables are calculated from the above settings
    * rowSize is the integer part of maxHeight divided by rowCount
    * colSize is the integer part of maxWidth divided by columnCount
    * cellHeight and cellWidth are set to the smaller value of rowSize and colSize
    * mazeWidth equals columnCount times cellWidth
    * mazeHeight equals rowCount times cellHeight
    * screenWidth is the sum of mazeWidth and screenPaddingWidth
    * screenHeight is the sum of mazeHeight and screenPaddingHeight
    """
    
    #-----------------code section - finish the code below-----------------
    rowSize = maxHeight // rowCount
    colSize = maxWidth // columnCount
    cellHeight = cellWidth = rowSize if rowSize < colSize else colSize
    mazeWidth = columnCount*cellWidth+1
    mazeHeight = rowCount*cellHeight+1
    screenWidth = mazeWidth + screenPaddingWidth
    screenHeight = mazeHeight + screenPaddingHeight
    #-------------------------end of code section-------------------------
    
    # disjoint sets
    """
    the following code implements smart union algorithm 
    it will be useful in finding which wall to destroy in order to make a maze
    you do not need to do anything with this part, it is ready for your later use
    """
    s = [-1] * rowCount * columnCount
    
    def findRoot(x):
        if s[x]<0:
            return x
        else:
            return findRoot(s[x])
    
    def unionSets(c1, c2):
        r1 = findRoot(c1)
        r2 = findRoot(c2)
        if s[r1] < s[r2]:
            s[r2] = r1
        else:
            if s[r1] == s[r2]:
                s[r2] -= 1
            s[r1] = r2
    
    def cellsConnected(x, y):
        return findRoot(x) == findRoot(y)
    
    
    # window and pen
    
    """
    settings of the screen window and turtle pen
    the code finishes the following settings
    * define a variable screen as a TurtleScreen instance via turtle.Screen() function
    * set the window size as screenWidth and screenHeight by calling screen.setup()
    * set the worldcoordinates as (0, 0, screenWidth-1, screenHeight-1) by calling screen.setworldcoordinates()
    * set the title of the window to "Maze created by YOUR NAME" by calling screen.title()
      (remember to replace YOUR NAME with your own name)
    * set the screen.tracer() to False in order to speed up drawing maze
    * define a variable pen as a Turtle instance via turtle.Turtle() function
    * hide turtle in window using hideturtle() function
    
    for more details of Turtle and Screen, please visit: 
        https://docs.python.org/3/library/turtle.html#turtle.screensize
        or in Chinese:
        https://docs.python.org/zh-cn/3/library/turtle.html#turtle.screensize
    """
    
    #-----------------code section - finish the code below-----------------
    screen = turtle.Screen()
    screen.setup(screenWidth, screenHeight)  
    screen.setworldcoordinates(0, 0, screenWidth-1, screenHeight-1)
    screen.title('Maze created by YE Huanzhuo')
    screen.tracer(False)
    pen = turtle.Turtle()
    # pen.speed(10)
    pen.hideturtle()
    #-------------------------end of code section-------------------------
    
    # build walls
    
    ## store all the walls available to be erased
    """
    store all the walls in a full grid into a list, name the list as wallErasable
    * the cells in the grid are numbered from 0 to rowCount*columnCount-1 starting from 
      lowerleft of the grid arranged in coloumn first order
    * normally, each cell has four walls, but in order not to miss any wall or recount any
      one, we define each cell with two walls, the upper wall and the right wall, except:
      - the upper most row, in which cells do not have upper walls
      - the right most column, in which cells do not have right walls
    * each wall is represented by a tuple (cellNo, position), in which
      - cellNo is the serial number of the cell
      - position show where the wall is to the cell, it has only two values:
        # 0: the wall is the upper wall of the cell
        # 1: the wall is the right wall of the cell 
    """
    
    #-----------------code section - finish the code below-----------------
    wallErasable = []
    for i in range(rowCount*columnCount):
        if i%columnCount != columnCount-1:
            wallErasable.append((i, 1))     # right wall to the cell
        if i < (rowCount-1)*columnCount:
            wallErasable.append((i , 0))    # upper wall to the cell
    #-------------------------end of code section-------------------------
    
    ## function to find the neighbor cell share the wall (cellNo, position)
    """
    this function returns the serial number of the cell which shares the wall
    represented by (cellNo, position) with the cell numbered cellNo
    """
    
    def neighbor(cellNo, position):
        #-----------------code section - finish the code below-----------------
        return cellNo + 1*position + columnCount*(1-position)
        #-------------------------end of code section-------------------------
    
    
    ## function to set a wall
    """
    the following code calcultes and draws the correspongding line with the current pen color 
    
    this function draws the wall represented by (cellNo, position)
    with the settings of columnCount, cellWidth and cellHeight, the pixels or line of 
    the wall (cellNo, position) can be easlily calculated
    """
    
    def setWall(cellNo, position):
        #-----------------code section - finish the code below-----------------
        row = cellNo // columnCount
        column = cellNo % columnCount
        if position:
            startPoint = ((column+1)*cellWidth, row*cellHeight)
        else:
            startPoint = (column*cellWidth, (row+1)*cellHeight)
        endPoint = ((column+1)*cellWidth, (row+1)*cellHeight)
        pen.up()
        pen.goto(startPoint)
        pen.down()
        pen.goto(endPoint)
        #-------------------------end of code section-------------------------
    
    
    ## randomly destroy rowCount*columnCount-1 walls to make rowCount*columnCount
    ## cells connected, thus build a maze
    """
    * build an empty list named wallToBuild to store the walls that should not be destroyed
    * each time randomly choose a destroyable / erasable wall from list wallErasable
      - find out the two cells sharing this wall
      - find out if the two cells are already connected using cellsConnected() function
        # if they are not connected yet
          + pop this wall out of wallErasable
        # otherwise (if they are already connected)
          + move this wall from wallErasable to wallToBuild
          + find another wall to destroy
    * repeat the above steps rowCount*columnCount-1 times to destroy rowCount*columnCount-1 walls
      in that way, rowCount*columnCount cells will be connected and the maze will be formed
    * move all the rest walls in wallErasable to wallToBuild
    """
    
    #-----------------code section - finish the code below-----------------
    numErased = 0
    wallToBuild = []
    while numErased < (rowCount*columnCount-1):
        numWall = random.randrange(len(wallErasable))
        cellNo, position = wallErasable[numWall]
        w = wallErasable.pop(numWall)    
        neighborCellNo = neighbor(cellNo, position)
        if not cellsConnected(cellNo, neighborCellNo):
            unionSets(cellNo, neighborCellNo)
            numErased += 1
        else:
            wallToBuild.append(w) 
    wallToBuild.extend(wallErasable)
    #-------------------------end of code section-------------------------
    
    ## build the maze
    ### build outer frame
    """
    * set the pen color to lineColor
    * draw the outline border of the maze, a rectangle set by
      - rowCount
      - columnCount
      - cellWidth
      - cellHeight
    """
    
    #-----------------code section - finish the code below-----------------
    pen.color(lineColor)
    pen.forward(cellWidth*columnCount)
    pen.left(90)
    pen.forward(cellHeight*rowCount)
    pen.left(90)
    pen.forward(cellWidth*columnCount)
    pen.left(90)
    pen.forward(cellHeight*rowCount)
    #-------------------------end of code section-------------------------
    
    
    ### build inner walls
    """
    take each wall from wallToBuild and draw it with current pen color
    """
    
    #-----------------code section - finish the code below-----------------
    for w in wallToBuild:
        setWall(*w)
    #-------------------------end of code section-------------------------
    
    
    ### dig out entrance and exit
    """
    make an entrance and an exit on the outline border
    * set the pen color to backGroundColor
    * draw the upper wall of the upperleft cell
    * draw the right wall of the lowerright cell
    """
    
    #-----------------code section - finish the code below-----------------
    pen.color(backGroundColor)
    setWall((rowCount-1)*columnCount, 0)
    setWall(columnCount-1, 1)
    #-------------------------end of code section-------------------------
    
    # well done
    screen.tracer(True)
    # screen.exitonclick()
    turtle.done()
    
    

    在这里插入图片描述

    展开全文
  • Minor turtle issues

    2021-01-10 09:00:00
    The <code>stamp()</code> method does not do anything.</li><li>[x] 18. <code>begin_fill()</code> and <code>end_fill()</code> are ignored.</li><li>[x] 19. If two or more turtles are on the screen, only...
  • python turtle画高达

    千次阅读 多人点赞 2019-01-29 19:33:50
    import turtle t=turtle.Turtle() turtle.Turtle().screen.delay(0) tleft=turtle.Turtle() #第一部分 t.penup() t.goto(0,0) t.pendown() t.left(20) t.forward(110) t.left(25) ...t.circle(18...
  • python中的turtle库函数简单使用教程更新时间:2018年07月23日 10:18:13 作者:就爱棒棒糖这篇文章主要介绍了python中的turtle库函数简单使用教程。本文通过图片的形式给大家展示的非常详细,具有一定的参考借鉴价值...
  • 使用turtle库画一朵玫瑰 import turtle import turtle # 设置初始位置 turtle.penup() turtle.left(90) turtle.fd(200) turtle.pendown() turtle.right(90) # 花蕊 turtle.fillcolor("red") ...turtle.circle(10,18...
  • Adding more Turtle blocks

    2020-12-30 14:31:58
    <p><a href="https://reviewable.io/reviews/roboerikg/blockly-android/18"><img src="https://reviewable.io/review_button.svg" height="40" alt="Review on Reviewable" /></a></p> 该提问来源于开源项目:...
  • turtle的文档:https://docs.python.org/3/library/turtle.html用Python的turtle库绘图是很简单...源码:'''Created on Nov 18, 2017@author: QiZhao'''import turtle# 设置初始位置turtle.penup()turtle.left(90)tu...
  • Created on Nov 18, 2017 @author: QiZhao ''' import turtle # 设置初始位置 turtle.penup() turtle.left(90) turtle.fd(200) turtle.pendown() turtle.right(90) # 花蕊 turtle.fillcolor(red) turtle.begin_f
  • turtle写一个猫和老鼠的小游戏,要求通过鼠标控制老鼠的移动,逃出电脑控制的猫的追捕
  • <h3>New Issue Checklist <ul><li>[x] Updated turtle-cli to the latest version (<code>yarn global add turtle-cli</code> or <code>npm install --...Feb 18 12:14:56 turtle[30722] INFO: Adding expo-bluetooth...
  • 本实例原本是Mooc课程上的一个案例,稍加修改后可以显示实时时间Python代码:# -*- coding: utf-8 -*-# @Author: Marte# @Date: 2020-07-22 18:34:56# @Last Modified by: Marte# @Last Modified time: 2020-07-23 13...
  • Python之Turtle库实例

    2020-07-23 13:58:31
    使用Python的Turtle库绘制一个显示时间的窗口 本实例来自Mooc课程上的一...# @Date: 2020-07-22 18:34:56 # @Last Modified by: Marte # @Last Modified time: 2020-07-23 13:23:30 # @Description: 七段数码管 ...
  • 这是我按照这个算法写的python程序,因为不太懂turtle库,写完运行发现并不绘制也没有报错,是我的turtle用错了吗? ![图片说明](https://img-ask.csdn.net/upload/201911/18/1574066706_763213.png)
  • at spawnAsyncThrowError (/Users/mojtaba/.nvm/versions/node/v10.15.0/lib/node_modules/turtle-cli/node_modules//xdl/build/detach/ExponentTools.js:89:18) at //xdl.1.4/src/detach/AndroidShellApp.js:1125...
  • Python中使用turtle绘制棋盘详解

    千次阅读 2018-11-29 13:43:43
    #声明棋盘的单元格宽度为30,数量为18 width = 30 num = 18 #设置画布大小 turtle.screensize(1200,900,"green") #声明列表来存取坐标 x1 = [(-400,400),(-400+width*num,400)] y1 = [(-400,400),(-400,...
  • But the problem is that the matrix block covers the turtle (the protagonist) <p>The default loading up should be changed to something like: <p><img alt="screenshot from 2016-01-18 23-55-36" src=...
  • turtle.pensize(18) turtle.penup() # 首圆起点 turtle.goto(-200,-100) # 绘制蓝色的圆 turtle.pencolor(.1,.6,.8) turtle.pendown() turtle.circle(100,-345) # 抬笔,去第二个圆的位置 turtle.penup() turtle...
  • Jun 10 18:17:50 turtle[203] INFO: /home/circleci/.turtle/workingdir/android/sdk33/packages/expo-module-scripts/bin/expo-module-configure: line 14: rsync: command not found platform: "android"...
  • Lemmmy ran <a href="https://gist.github.com/Lemmmy/18fb37954d7feef37d312590231155a2">this code</a> on it. Yemmel (admin user, respecting claims, not trusted in the claim) jumped on the turtle as it ...
  • at index.js:18 at p.run (browser.js:153) at d (browser.js:123) </anonymous></code></pre> <p>I don't see why the CURIE <code>dbr:Germany_at_the_2006–08_European_Nations_Cup</code> is ...
  • # -*- coding: utf-8 -*- # @Time : 2018/10/18 12:19 # @Author : Lucius Chen import turtle import time def drawline(draw): turtle.pendown() if draw else turtle.penup() turtle.fd(40) turt...
  • <p>turtle build:android -t app-bundle --output ~/projetos/novoprojeto/build -c ./app.json --keystore-path ../minha-chave.jks --keystore-alias meu-alias --gradle-args "--warning-mode all" --...
  • 用Python的turtle库绘图是很简单的...源码:'''Created on Nov 18, 2017@author: QiZhao'''import turtle# 设置初始位置turtle.penup()turtle.left(90)turtle.fd(200)turtle.pendown()turtle.right(90)# 花蕊turtle....
  • <p>i use the <strong> </strong>mu_2018-02-23_18_46_master_64db73d_32bit.exe<strong> </strong> on windows 10 64 bit system <pre><code> i guest the python version mu use does not packag the turtle ...
  • 目标:用Turtle绘制一个时钟。 在了解了turtle的基本用法之后就开始了绘制过程,结果遇到了很多坑,这里一一列出,在总结的同时也方便其他朋友...# @Time : 2019/12/6 18:24 # @Author : River.big import turtle...
  • <div><p>I have a Turtle file that <code>console.sh</code> reports as fine. (<code>console.sh</code> seems to use <code>org.eclipse.rdf4j.rio...) However, <code>Jena</code>'s <code>riot</code> ...

空空如也

空空如也

1 2 3 4 5 ... 12
收藏数 233
精华内容 93
关键字:

turtle18