python turtle 基本功法(五)

产生随机数:random.randint(0,255)

介绍一个新的python库 random,用于生成随机数random.randint(0,255)生成一个0至255的随机整数

python turtle 设置颜色模式的方法:

colormode(255) 或colormode(1)
如果colormode的参数是255,则颜色值为0-255
如果colormode有参数是1,则颜色值为0-1

RGB颜色模式

我们前面设置颜色是用color('red'),参数是颜色的英文单词,那更多颜色怎么表示。电脑中常用RBG模式

R red

G greed

B blue

三元颜色占比不同混合成各种各样的颜色
如果用RGB模式设置
colormode(255)模式下
黑色color(0,0,0)
红色color(255,0,0)
绿色color(0,255,0)
蓝色clolor(0,0,255)
白色color(255,255,255)
colormode()模式下
黑色color(0,0,0)
红色color(1,0,0)
绿色color(0,1,0)
蓝色clolor(0,0,1)
白色color(255,255,255)
你可以 改变 rgb颜色值形成你自己需要的颜色

代码示例

from turtle import *
import random

colormode(255)
pensize(4)
for i in range(6):
    r = random.randint(0,255)
    g = random.randint(0,255)
    b = random.randint(0,255)
    color(r,g,b)
    for j in range(6):
        fd(100)
        rt(60)
    rt(60)

mainloop()
运行效果

我们上面代码外循环增加一倍,12次,改变外循环的角度为30,尝试下,是不是出现下面的图形了啊,当然颜色是随机的,你的图形线条颜色可能和这里的不一样


增加循环次数,改变角度

我们再把内循环改成八边形,转角改为45度,注意把边长改短点。


改变内循环

三层循环画出随机填充色
from turtle import *
import random

colormode(255)
up()
goto(-190,190)
rt(90)
for i in range(5):
    for j in range(8):
        r = random.randint(0,255)
        g = random.randint(0,255)
        b = random.randint(0,255)
        color(r,g,b)
        begin_fill()
        for k in range(2):
            fd(30)
            lt(90)
            fd(60)
            lt(90)
        end_fill()        
        fd(50)
    bk(400)
    lt(90)
    fd(80)
    rt(90)

mainloop()
随机色块
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容