利用python/R语言绘制圣诞树实例代码

2022-07-19,,,,

目录

圣诞节快到了,想着用python、r来画画圣诞树玩,就在网络上各种找方法,不喜勿喷哈~~

python

1、

import turtle
 
screen = turtle.screen()
screen.setup(800,600)
 
circle = turtle.turtle()
circle.shape('circle')
circle.color('red')
circle.speed('fastest')
circle.up()
 
square = turtle.turtle()
square.shape('square')
square.color('green')
square.speed('fastest')
square.up()
 
circle.goto(0,280)
circle.stamp()
 
k = 0
for i in range(1, 17):
    y = 30*i
    for j in range(i-k):
        x = 30*j
        square.goto(x,-y+280)
        square.stamp()
        square.goto(-x,-y+280)
        square.stamp()
 
    if i % 4 == 0:
        x =  30*(j+1)
        circle.color('red')
        circle.goto(-x,-y+280)
        circle.stamp()
        circle.goto(x,-y+280)
        circle.stamp()        
        k += 2
 
    if i % 4 == 3:
        x =  30*(j+1)
        circle.color('yellow')
        circle.goto(-x,-y+280)
        circle.stamp()
        circle.goto(x,-y+280)
        circle.stamp() 
 
square.color('brown')
for i in range(17,20):
    y = 30*i
    for j in range(3):    
        x = 30*j
        square.goto(x,-y+280)
        square.stamp()
        square.goto(-x,-y+280)
        square.stamp()        
        
turtle.exitonclick()

2、

import random
height = 11
for i in range(height):
    print(' ' * (height - i), end='')
    for j in range((2 * i) + 1):
        if random.random() < 0.1:
            color = random.choice(['\033[1;31m', '\033[33m', '\033[1;34m'])
            print(color, end='')  #  the lights 
        else:
            print('\033[32m', end='')  #  green 
        print('*', end='')
    print()
print((' ' * height) + '|')

3、

n = 50
from turtle import *
speed("fastest")  #没有这一行,会very very慢
left(90)
forward(3*n)
color("orange", "yellow")
begin_fill()
left(126)
for i in range(5):
    forward(n/5)
    right(144)
    forward(n/5)
    left(72)
end_fill()
right(126)
color("dark green")
backward(n*4.8)
def tree(d, s):
    if d <= 0: return
    forward(s)
    tree(d-1, s*.8)
    right(120)
    tree(d-3, s*.5)
    right(120)
    tree(d-3, s*.5)
    right(120)
    backward(s)
tree(15, n)
backward(n/2)

 

4、

def paintleaves(m):
    for i in range(m):
        if(i == 10):
            print( ' '*(m-i) + '*'*( 2*i + 1-len( 'happy christmas')) + 'happy christmas'+ ' '*(m-i))
            continue
        if(i == 20):
            print( ' '*(m-i) + '*'*( 2*i + 1-len( 'i love you')) +'i love you'+ ' '*(m-i))
            continue
        if(i == m-1):
            print( ' '*(m-i) + 'liang yu'+ '*'*( 2*i + 1-len( 'liang yu')) + ' '*(m-i))
            continue   
        print(' '*(m-i) + '*'*(2*i + 1) + ' '*(m-i))   
def painttrunk(n):
    for j in range (8 ):
        print(' '*(n - 5) + '*'*10 + ' '*(n - 5))
paintleaves(25)
painttrunk(25)

 

5、

#!/usr/bin/env python
# coding:utf-8
import os
import sys
import platform
import random
import time
 
 
class ui(object):
    def __init__(self):
        os_name = platform.uname()[0]
        self.is_win = os_name == 'windows'
        self.is_mac = os_name == 'darwin'
        print(os_name)
        if self.is_win:
            self.red = 0x0c
            self.grey = 0x07
            self.blue = 0x09
            self.cyan = 0x0b
            self.link = 0x30
            self.black = 0x0
            self.green = 0x0a
            self.white = 0x0f
            self.purple = 0x0d
            self.yellow = 0x0e
        else:
            self.red = '\033[1;31m'
            self.grey = '\033[38m'
            self.blue = '\033[1;34m'
            self.cyan = '\033[36m'
            self.link = '\033[0;36;4m'
            self.black = '\033[0m'
            self.green = '\033[32m'
            self.white = '\033[37m'
            self.purple = '\033[35m'
            self.yellow = '\033[33m'
        self.p = self.win_print if self.is_win else self.os_print
 
    def clear(self):
        os.system('cls' if self.is_win else 'clear')
        return self
 
    def win_reset(self, color):
        from ctypes import windll
        handler = windll.kernel32.getstdhandle(-11)
        return windll.kernel32.setconsoletextattribute(handler, color)
 
    def win_print(self, msg, color, enter=true):
        color = color or self.black
        self.win_reset(color | color | color)
        sys.stdout.write(('%s\n' if enter else '%s') % msg)
        self.win_reset(self.red | self.green | self.blue)
        return self
 
    def os_print(self, msg, color, enter=true):
        color = color or self.black
        sys.stdout.write(
            ('%s%s%s\n' if enter else '%s%s%s') % (color, msg, self.black))
        return self
 
 
def tree(ui, level=3):
    a = range(0, (level + 1) * 4, 2)
    b = list(a[0:2])
    print(b)
    for i in range(2, len(a) - 2, 2):
        b.append(a[i])
        b.append(a[i + 1])
        b.append(a[i])
        b.append(a[i + 1])
    b.append(a[-2])
    b.append(a[-1])
    light = true
    while true:
        ui.clear()
        ui.p(u'\t圣诞节快乐!\n\t\t\tliang yu.shi 2021', ui.red)
        print
        light = not light
        lamp(ui, b, light)
        for i in range(2, len(b)):
            ui.p(
                '%s/' % (' ' * b[len(b) - i - 1]), ui.green, enter=false)
            neon(ui, 2 * b[i] + 1)
            ui.p('\\', ui.green, enter=true)
        time.sleep(1.2)
 
 
def neon(ui, space_len):
    colors = [ui.red, ui.grey, ui.blue, ui.cyan, ui.yellow]
    for i in range(space_len):
        if random.randint(0, 16) == 5:
            ui.p('o', colors[random.randint(0, len(colors) - 1)], enter=false)
        else:
            ui.p(' ', ui.red, enter=false)
 
 
def lamp(ui, tree_arr, light):
    colors = [ui.white, ui.blue]
    if not light:
        colors.reverse()
    ui.p(' ' * (tree_arr[-1] + 1), ui.black, enter=false)
    ui.p('|', colors[1])
    ui.p(' ' * tree_arr[-1], ui.black, enter=false)
    ui.p('\\', colors[1], enter=false)
    ui.p('|', colors[0], enter=false)
    ui.p('/', colors[1])
    ui.p(' ' * tree_arr[-2], ui.black, enter=false)
    ui.p('-', colors[0], enter=false)
    ui.p('-', colors[1], enter=false)
    ui.p('=', colors[0], enter=false)
    ui.p('o', colors[1], enter=false)
    ui.p('=', colors[0], enter=false)
    ui.p('-', colors[1], enter=false)
    ui.p('-', colors[0], enter=true)
 
    ui.p(' ' * tree_arr[-1], ui.black, enter=false)
    ui.p('/', colors[1], enter=false)
    ui.p('|', colors[0], enter=false)
    ui.p('\\', colors[1])
    ui.p(' ' * tree_arr[-2], ui.black, enter=false)
    ui.p('/  ', ui.green, enter=false)
    ui.p('|', colors[1], enter=false)
    ui.p('  \\', ui.green, enter=true)
 
 
def main():
    ui = ui()
    max_rows = 4
    tree(ui, max_rows)
 
 
main()

 

这个在使用python运行的时候,要用python2,python3的话,颜色是不会变的。 嗯,最起码我是这样的。

6、

import argparse
import os
import random
import time
 
ball = '⏺'
color = {
    'blue': '\033[94m',
    'yellow': '\033[93m',
    'cyan': '\033[96m',
    'green': '\033[92m',
    'magenta': '\033[95m',
    'white': '\033[97m',
    'red': '\033[91m'
}
star = '★'
 
 
def random_change_char(string, value):
    indexes = random.sample(range(0, len(string)), value)
    string = list(string)
    for idx in indexes:
        if string[idx] != ' ' and string[idx] == '_':
            string[idx] = ball
    return ''.join(string)
 
 
def tree(height=13, screen_width=80):
    star = (star, 3*star)
    if height % 2 != 0:
        height += 1
    body = ['/_\\', '/_\_\\']
    trunk = '[___]'
    begin = '/'
    end = '\\'
    pattern = '_/'
    j = 5
    for i in range(7, height + 1, 2):
        middle = pattern + (i - j) * pattern
        line = ''.join([begin, middle[:-1], end])
        body.append(line)
        middle = middle.replace('/', '\\')
        line = ''.join([begin, middle[:-1], end])
        body.append(line)
        j += 1
 
    return [line.center(screen_width) for line in (*star, *body, trunk)]
 
 
def balls(tree):
    for idx, _ in enumerate(tree[:-3], 2):
        tree[idx] = random_change_char(tree[idx], len(tree[idx])//8)
    return tree
 
 
def colored_stars_balls(tree):
    for idx, _ in enumerate(tree):
        string = list(tree[idx])
        for pos, _ in enumerate(string):
            if string[pos] == star:
                string[pos] = ''.join([color['yellow'], star, '\033[0m'])
            elif string[pos] == ball:
                string[pos] = ''.join([random.choice(list(color.values())), ball, '\033[0m'])
        tree[idx] = ''.join(string)
    return tree
 
 
def cli():
    parser = argparse.argumentparser(prog="python christmas tree by chico lucio from ciencia programada",
                                     epilog="ctrl-c interrupts the christmas :-(")
    parser.add_argument('-s', '--size', default=13, type=int,
                        help="tree height. if even it will be subtracted 1. if less than 7, considered 5. default: 13")
    parser.add_argument('-w', '--width', default=80, type=int,
                        help="screen width. used to center the tree. default: 80")
    parser.add_argument('-t', '--terminal', action='store_true',
                        help="uses the terminal size to center the tree. -s and -w will be ignored")
    args = parser.parse_args()
 
    if args.terminal:
        screen_width, height = os.get_terminal_size()
        height -= 2
    else:
        height = args.size
        screen_width = args.width
    while true:
        try:
            time.sleep(random.uniform(.1, 1))
            os.system('cls' if os.name == 'nt' else 'clear')
            print('\n'.join(colored_stars_balls(balls(tree(height, screen_width)))))
        except keyboardinterrupt:
            os.system('cls' if os.name == 'nt' else 'clear')
            print(f"\n{'merry christmas!!':^{screen_width}}", end='\n\n')
            break
 
 
if __name__ == '__main__':
    cli()

来源:a simple terminal christmas tree made with python | pythonrepo


update:2021-12-23

import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111, projection="3d")
def init():
    k=300
    z = [i for i in range(k)]
    x = [math.cos(i/5)*(k-i) for i in range(k)]
    y = [math.sin(i/5)*(k-i) for i in range(k)]
    ax.scatter(x,y,z, c="green", marker="^")
    step = 3
    c = [(i/k,abs(0.5-i/k),i/k) for i in range(1,k,step)]
    z = [i for i in range(1,k,step)]
    x = [math.cos(i/5+2)*(k-i+10) for i in range(1,k,step)]
    y = [math.sin(i/5+2)*(k-i+10) for i in range(1,k,step)]
    ax.scatter(x,y,z, c=c, marker="o",s=40)
    plt.xlim(-500,500)
    plt.ylim(-500,500)
    return fig,
def animate(f):
    fig.clear()
    ax = fig.add_subplot(111, projection="3d")
    k=300
    z = [i for i in range(k)]
    x = [math.cos(i/5+f/10)*(k-i) for i in range(k)]
    y = [math.sin(i/5+f/10)*(k-i) for i in range(k)]
    ax.scatter(x,y,z, c="green", marker="^")
    step = 3
    c = [(i/k,abs(0.5-i/k),i/k) for i in range(1,k,step)]
    z = [i for i in range(1,k,step)]
    x = [math.cos(i/5+2+f/10)*(k-i+10) for i in range(1,k,step)]
    y = [math.sin(i/5+2+f/10)*(k-i+10) for i in range(1,k,step)]
    ax.scatter(x,y,z, c=c, marker="o",s=40)
    plt.xlim(-500,500)
    plt.ylim(-500,500)
    return fig,
ani=animation.funcanimation(fig, animate, init_func=init,
                               frames=90, interval=50, blit=true)
ani.save("christmas_tree.mp4")

来源:https://medium.com/analytics-vidhya/how-to-draw-a-3d-christmas-tree-with-matplotlib-aabb9bc27864

r语言

1、

l <-  matrix(c(0.03,0,0,0.1,0.85,0.00,0.00,0.85,0.8,0.00,0.00,0.8,0.2,-0.08,0.15, 0.22, -0.2,0.08,0.15, 0.22,0.25, -0.1,0.12, 0.25,-0.2,0.1,0.12, 0.2),nrow=4)  
b <- matrix(c(0,0,0,1.5,0,1.5,0,0.85,0,0.85,0,0.3,0, 0.4),nrow=2) 
prob = c(0.02, 0.6,.08, 0.07, 0.07, 0.07, 0.07) 
n = 1e5 
x = matrix(na,nrow=2,ncol=n)
x[,1] = c(0,2)   
k <- sample(1:7,n,prob,replace=true) 
for(i in 2:n)
{  
 x[,i] = crossprod(matrix(l[,k[i]],nrow=2),x[,i-1]) + b[,k[i]]
}
par(bg='black',mar=rep(0,4))    
plot(x=x[1,],y=x[2,],col=grep('green',colors(),value=true),axes=false,cex=.1, xlab='', ylab='',pch='.')
bals <- sample(n,20) 
points(x=x[1,bals],y=x[2,bals]-.1,col=c('red','blue','yellow','orange'),cex=1.5,pch=19) 
text(x=-.7,y=8, labels='liangyushi', adj=c(.5,.5), srt=35,
vfont=c('script','plain'),cex=3,col='gold' ) 
text(x=0.7,y=8,labels='merry christmas',adj=c(.5,.5),srt=-35,
vfont=c('script','plain'),cex=3, col='gold' ) 
 
text(x=-0.6,y=0,cex=0.8,labels="by jimmy wu", col="white")

2、

par(bg='black',mar=rep(0,4))
plot(1:10,1:10,xlim=c(-5,5),ylim=c(0,10),type="n",xlab="",ylab="",xaxt="n",yaxt="n")
rect(-1,0,1,2,col="tan3",border="tan4",lwd=3)
polygon(c(-5,0,5),c(2,4,2),col="palegreen3",border="palegreen4",lwd=3)
polygon(c(-4,0,4),c(3.5,5.5,3.5),col="palegreen4",border="palegreen3",lwd=3)
polygon(c(-3,0,3),c(5,6.5,5),col="palegreen3",border="palegreen4",lwd=3)
polygon(c(-2,0,2),c(6.25,7.5,6.25),col="palegreen4",border="palegreen3",lwd=3)
points(x=runif(4,-5,5),y=rep(2,4),col=sample(c("blue","red"),size=4,replace=t),cex=3,pch=19)
points(x=runif(4,-4,4),y=rep(3.5,4),col=sample(c("blue","red"),size=4,replace=t),cex=3,pch=19)
points(x=runif(4,-3,3),y=rep(5,4),col=sample(c("blue","red"),size=4,replace=t),cex=3,pch=19)
points(x=runif(4,-2,2),y=rep(6.25,4),col=sample(c("blue","red"),size=4,replace=t),cex=3,pch=19)
points(0,7.5,pch=8,cex=5,col="gold",lwd=3)
xpres = runif(10,-4.5,4.5)
xwidth = runif(10,0.1,0.5)
xheight=runif(10,0,1)
for(i in 1:10){
  rect(xpres[i]-xwidth[i],0,xpres[i]+xwidth[i],xheight[i],col=sample(c("blue","red"),size=1))
  rect(xpres[i]-0.2*xwidth[i],0,xpres[i]+0.2*xwidth[i],xheight[i],col=sample(c("gold","grey87"),size=1))
}

 

后面再找到好玩的,好看的,会更新在这里~

总结

到此这篇关于利用python/r语言绘制圣诞树的文章就介绍到这了,更多相关python/r绘制圣诞树内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《利用python/R语言绘制圣诞树实例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。