圣诞节快到了,想着用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绘制圣诞树内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!