def draw_state(self): """ the core of the class Interprete character: F: move forward +: turn right -: turn left [: push (position, heading) ]: pop (position, heading) """ import turtle state = self.lsystem().state() for c in state: if c == 'F': turtle.forward(self.length) if c == '+': turtle.right(self.angle) if c == '-': turtle.left(self.angle) if c == '[': self.stack.append((turtle.position(), turtle.heading())) if c == ']': if len(self.stack) == 0: raise ValueError('inconsistant state: using to much `]`') pos, head = self.stack.pop() turtle.penup() turtle.setpos(pos) turtle.setheading(head) turtle.pendown() return self
def von_koch(l, n): t.forward(l) von_koch(l / 3, n - 1) t.setheading(t.heading() + 60) von_koch(l / 3, n - 1) t.setheading(t.heading() - 120) von_koch(l / 3, n - 1) t.setheading(t.heading() + 60)
def main(): turtle.color('red') turtle.heading() turtle.left(80) turtle.speed(5) turtle.pendown() turtle.fill(True) turtle.circle(30,90)
def randomDirection(): if remainingX > 0 and remainingY > 0: if turtle.xcor() < 0 and forwardX > backwardX: randomInt = random.randrange(0,3) else: randomInt = random.randrange(0,2) if randomInt == 0: return NORTH elif randomInt == 1 and turtle.heading() != WEST: return EAST elif randomInt == 2 and turtle.heading() != EAST: return WEST
def main(): '''主程序''' turtle.speed(12) turtle.penup() x, y = 0, 0 # 画国旗主体 width, height = 540, 360 # 国旗比例是3:2 draw_rectangle(x, y, width, height) # 画大星星 pice = 20 center_x, center_y = x + 5 * pice, y + height - pice * 5 turtle.goto(center_x, center_y) turtle.left(90) turtle.forward(pice * 3) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice * 3) x_poses, y_poses = [10, 12, 12, 10], [2, 4, 7, 9] # 画小星星 for x_pos, y_pos in zip(x_poses, y_poses): turtle.goto(x + x_pos * pice, y + height - y_pos * pice) turtle.left(turtle.towards(center_x, center_y) - turtle.heading()) turtle.forward(pice) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice) # 隐藏海龟 turtle.ht() turtle.mainloop() # 显示绘图窗口
def makeDiamond(size, person=None, fill=False): origPosition = turtle.pos() origHead = turtle.heading() turtle.penup() goDown(size) turtle.pendown() if(person != None or fill==True): if(fill==True or person.affected): turtle.begin_fill() goNorthEast(2*size/np.sqrt(2)) goNorthWest(2*size/np.sqrt(2)) goSouthWest(2*size/np.sqrt(2)) goSouthEast(2*size/np.sqrt(2)) if(person != None or fill==True): if(fill==True or person.affected): turtle.end_fill() turtle.penup() turtle.goto(origPosition) turtle.setheading(origHead) if(person != None or fill==True): if(fill==True or person.affected): turtle.color('black') if(person.multipleNotShown == 0): turtle.write(str(person.name())+"\n"+probString(person), align="center") else: turtle.write(str(person.name())+"\n"+probString(person)+"\n\n"+str(person.multipleNotShown), align="center") turtle.color('blue') turtle.penup()
def draw_l(word): turtle.up() turtle.clear() turtle.setposition(0, 0) turtle.setheading(0) turtle.bk(INITIAL_POS[0]) turtle.down() turtle.st() stack = [] for char in word: if char == '0': turtle.fd(SIZE[0]) if char == '1': turtle.fd(SIZE[0]) if char == '[': stack.append((turtle.position(), turtle.heading())) turtle.lt(45) if char == ']': position, heading = stack.pop() turtle.up() turtle.setposition(position) turtle.setheading(heading) turtle.rt(45) turtle.down() turtle.ht()
def draw_path(length, angle, path, expalnation, lengthFactor): posList, angleList = [], [] for symbol in path: # print(expalnation[symbol]) if symbol == 'F': # t.color(getColor(), getColor(), getColor()) t.forward(length) elif symbol == '>': length = length * lengthFactor elif symbol == '<': length = length / lengthFactor elif symbol == '+': t.left(angle) elif symbol == '-': t.rt(angle) elif symbol == '[': posList.append(t.pos()) angleList.append(t.heading()) elif symbol == 'a': t.pensize(4) t.color("green") elif symbol == 'b': t.color("green") t.pensize(3) elif symbol == 'c': t.pensize(2) t.color("#18b418") elif symbol == ']': t.up() t.home() t.goto(posList.pop()) t.left(angleList.pop()) t.down()
def draw_arrow(): '''Draw an arrow toward the turtle's current heading, then return to position and heading.''' arrow_length = 7 # pixels arrow_width = 10 # pixels arrow_end = tt.position() old_heading = tt.heading() # move to back end of upper line tt.penup() tt.backward(arrow_length) tt.left(90) tt.forward(arrow_width) # draw upper line tt.pendown() tt.setposition(arrow_end) tt.setheading(old_heading) # move to back end of lower line tt.penup() tt.backward(arrow_length) tt.right(90) tt.forward(arrow_width) # draw lower line tt.pendown() tt.setposition(arrow_end) tt.setheading(old_heading) tt.penup()
def draw_plant(actions): stk = [] for action in actions: if action=='X': # do nothing pass elif action== 'F': # go forward turtle.forward(2) elif action=='+': # rotate right by 25 degrees turtle.right(25) elif action=='-': # rotate left by 25 degrees turtle.left(25) elif action=='[': # save the position and heading by "pushing" down on to the stack pos = turtle.position() head = turtle.heading() stk.append((pos, head)) elif action==']': # restore position and heading: by "popping" off the first item from stack pos, head = stk.pop() turtle.penup() turtle.setposition(pos) turtle.setheading(head) turtle.pendown() else: raise ValueError("don't recognize action", action) turtle.update()
def affichage5(mot): turtle.resetscreen() turtle.speed("fastest") turtle.left(90) turtle.penup() turtle.goto(0,-300) turtle.pendown() turtle.tracer(0, 0) pos=[] for k in mot: if k=="F" or k=="M" or k=="N" or k=="O" or k=="P" or k=="Y" or k=="Z": t.forward(2) elif k=="-": t.rotate_Z(22.5) elif k=="+": t.rotate_Z(-22.5) elif k=="&": t.rotate_Y(22.5) elif k=="^": t.rotate_Y(-22.5) elif k=="/": t.rotate_Y(-22.5) elif k=="|": t.rotate_Z(180) elif k=="[": pos.append( (turtle.position(),turtle.heading())) elif k=="]": turtle.penup() x=pos.pop() turtle.goto(x[0]) turtle.setheading(x[1]) turtle.pendown() turtle.update()
def tGraph(word='F', theta=0, alpha=0, step=10, x0=0, y0=0): #Run, turtle, RUN!!! #tr.clear() tr.radians() tr.speed(0) tr.pu() tr.setx(x0) tr.sety(y0) tr.seth(alpha) tr.pd() st = [] for c in word: if c == 'F': tr.fd(step) if c == 'b': tr.pu() tr.bk(step) tr.pd() if c == '[': st.append({'x': tr.xcor(), 'y': tr.ycor(), 'ang': tr.heading()}) if c == ']': pos = st.pop() tr.pu() tr.setx(pos['x']) tr.sety(pos['y']) tr.seth(pos['ang']) tr.pd() if c == '+': tr.lt(theta) if c == '-': tr.rt(theta)
def main(): turtle.speed(12) turtle.penup() x, y = -270, -180 width, height = 540, 360 draw_rectangle(x, y, width, height) '''绘制大星''' pice = 22 center_x, center_y = x + 5 * pice, y + height - 5 * pice turtle.goto(center_x, center_y) turtle.left(90) turtle.forward(3 * pice) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), 3 * pice) # 画小星星 x_poses, y_poses = [10, 12, 12, 10], [2, 4, 7, 9] for x_pos, y_pos in zip(x_poses, y_poses): turtle.goto(x + x_pos * pice, y + height - y_pos * pice) turtle.left(turtle.towards(center_x, center_y) - turtle.heading()) turtle.forward(pice) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice) # 隐藏海龟 turtle.ht() turtle.mainloop()
def draw_path(path, expalnation): posList, angleList = [], [] t.up() t.goto(0, -350) t.down() t.lt(90) for symbol in path: if symbol == 'F': t.forward(length) # 向前画出length长度 elif symbol == '+': t.left(angle) # 向左边旋转出angle角度 elif symbol == '-': t.rt(angle) # 向右边旋转出angle角度 elif symbol == '[': posList.append(t.pos()) # 记录当前位置的坐标值,将当前的坐标值放到一个列表中 angleList.append(t.heading()) # 记录当前位置的角度值,将当前的角度值放到一个列表中 # abc分别代表树干 树枝和树叶的颜色 elif symbol == 'a': t.pensize(4) t.color("#8c503c") elif symbol == 'b': t.color("#4ab441") t.pensize(3) elif symbol == 'c': t.pensize(2) t.color("#18b418") elif symbol == ']': t.up() t.home() t.goto(posList.pop()) # 复原最近添加的一个坐标值 t.left(angleList.pop()) # 复原最近添加的一个角度值 t.down()
def drawCircleAtPosition(turtle, circle, fill): # save current position and orientation (x,y) = turtle.position() heading = turtle.heading() # get center and radius of circle (x1, y1, radius) = circle # position turtle to center of circle turtle.penup() turtle.setposition(x1, y1-radius) turtle.setheading(0) # set fill color if fill != "none": turtle.color(fill) turtle.begin_fill() else: turtle.color("black") turtle.pendown() # draw circle turtle.circle(radius) # return turtle to original position and orientation turtle.penup() turtle.end_fill() turtle.setposition(x, y) turtle.setheading(heading) turtle.color("black")
def main(): #设置一个画面 windows = turtle.Screen() #设置背景 windows.bgcolor('black') #生成一个黄色乌龟 bran = turtle.Turtle() bran.shape('turtle') bran.color('white') turtle.home() turtle.dot() turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50) turtle.position() (100.00,-0.00) turtle.heading()
def draw_path(path, expalnation): posList, angleList = [], [] t.up() t.goto(0, -350) t.down() t.lt(90) for symbol in path: if symbol == 'F': t.forward(length) elif symbol == '+': t.left(angle) elif symbol == '-': t.rt(angle) elif symbol == '[': posList.append(t.pos()) angleList.append(t.heading()) elif symbol == 'a': t.pensize(4) t.color("#8c503c") elif symbol == 'b': t.color("#4ab441") t.pensize(3) elif symbol == 'c': t.pensize(2) t.color("#18b418") elif symbol == ']': t.up() t.home() t.goto(posList.pop()) t.left(angleList.pop()) t.down()
def makeTree(h, l, b, d, ad): Base(b) turtle.color("brown") if h > 0: if h == 1: turtle.color("green") if h== 4: Apple(b) if d == 0: makeTree(h-1 , l*.75, drawLimb(l, d*ad), d+1,ad) else: y = turtle.heading() makeTree(h-1 , l*.75, drawLimb(l*.75, d*ad/2.00), d,ad) Base(b) d = d*-1 turtle.setheading(y) makeTree(h-1 , l*.75, drawLimb(l*.75, d*ad/2.00), d,ad) else: Base(b)
def draw(cmds, size=2): #output tree stack = [] for cmd in cmds: if cmd=='F': turtle.forward(size) elif cmd=='-': t = random.randrange(0,7,1) p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"] turtle.color(p[t]) turtle.left(15) #slope left elif cmd=='+': turtle.right(15) #slope right t = random.randrange(0,7,1) #рандомная пер. для цвета p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"] #ряд цветов turtle.color(p[t]) #выбор цвета из ряда elif cmd=='X': pass elif cmd=='[': stack.append((turtle.position(), turtle.heading())) elif cmd==']': position, heading = stack.pop() turtle.penup() turtle.setposition(position) turtle.setheading(heading) turtle.pendown() turtle.update()
def draw_feathers(x,y): pos = [] turtle.goto(x + 170, y) sx = turtle.xcor() turtle.setheading(0) pos.append(turtle.position()) for e in range (9): turtle.pencolor(colors[e]) turtle.fillcolor(colors[e]) turtle.begin_fill() turtle.circle(30, 200) turtle.end_fill() a = turtle.heading() turtle.setheading(a + 180) pos.append(turtle.position()) x = turtle.xcor() cx = (sx + x) /2 for i in range(9): turtle.pencolor(colors[i]) turtle.fillcolor(colors[i]) turtle.goto(cx, -200) turtle.begin_fill() turtle.goto(pos[i]) turtle.goto(pos[i+1]) turtle.goto(cx, -200) turtle.end_fill() return cx
def drawString(dstring, distance, angle): """ Interpret the characters in string dstring as a series of turtle commands. Distance specifies the distance to travel for each forward command. Angle specifies the angle (in degrees) for each right or left command. The list of turtle supported turtle commands is: F : forward - : turn right + : turn left [ : save position, heading ] : restore position, heading """ stack = [] for c in dstring: if c == 'F': turtle.forward(distance) elif c == '-': turtle.right(angle) elif c == '+': turtle.left(angle) elif c == '[': stack.append(turtle.position()) stack.append(turtle.heading()) elif c == ']': turtle.up() turtle.setheading(stack.pop()) turtle.goto(stack.pop()) turtle.down() turtle.update()
def tree(turtle,size): # if size==100: # turtle.forward(100) if size <= 10: return else: # for i in range(2): p=turtle.pos() h=turtle.heading() turtle.left(30) turtle.forward(size*0.8) tree(tut,size*0.8) turtle.setpos(p) turtle.setheading(h) # turtle.bk(size*0.8) # turtle.left(180) # turtle.penup() # turtle.forward(size*0.8) # turtle.pendown() turtle.right(30) turtle.forward(size*0.8) tree(tut,size*0.8) turtle.setpos(p)
def main(): """主程序""" turtle.speed(12) turtle.penup() x, y = -270, -180 # 畫國旗主體 width, height = 540, 360 draw_rectangle(x, y, width, height) # 畫大星星 pice = 22 center_x, center_y = x + 5 * pice, y + height - pice * 5 turtle.goto(center_x, center_y) turtle.left(90) turtle.forward(pice * 3) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice * 3) x_poses, y_poses = [10, 12, 12, 10], [2, 4, 7, 9] # 畫小星星 for x_pos, y_pos in zip(x_poses, y_poses): turtle.goto(x + x_pos * pice, y + height - y_pos * pice) turtle.left(turtle.towards(center_x, center_y) - turtle.heading()) turtle.forward(pice) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice) # 隱藏海龜 turtle.ht() # 顯示繪圖窗口 turtle.mainloop()
def spiral(radius=1, advance=1, loops=3): ''' Draw a straight spiral When the pen begins to draw a circle, also move the pen left (relative to the canvas) {advance} units during each step of the circle drawing process. This creates one loop in of the spiral. Simply repeat this action to achieve the desired spiral length. ''' for loop_main in range(loops): spiral_heading = 0 for a in range(360): # Begin drawing a circle turtle.forward(radius) turtle.left(1) # Save the heading of the circle drawing process spiral_heading = turtle.heading() # Move the pen right by {advance / 10} # Because advancing by 1 pixel is too large turtle.setheading(0) turtle.forward(advance / 10) # Restore the original heading of the pen # Allows the circle drawing process to continue turtle.setheading(spiral_heading)
def draw(lr, ls): """draw""" t = turtle.Turtle() t.color("green") t.shape("turtle") for i in lr: t.forward(i.height) t.left(90) t.forward(i.width) t.left(90) t.forward(i.height) t.left(90) t.forward(i.width) t.left(90) t.setheading(turtle.heading() + 90) t.color("red") for i in ls: t.forward(i.size) t.left(90) t.forward(i.size) t.left(90) t.forward(i.size) t.left(90) t.forward(i.size) t.left(90)
def draw_figure(length, sides, status): """ Draws polygon of sides and length specified in arguments and fills polygon with color based on value of status. :pre: (relative) pos (0,0), heading (east), up :post: (relative) pos (0,length), heading (east), up :return: vertices of polygon, headings of the vertices, sum of length of all sides of polygon """ sum = 0 vertices = [] headings = [] turtle.down() if status == STATUS_FILL: turtle.pensize(FILL_PEN_WIDTH) turtle.color(PEN_COLOR, COLORS[sides]) turtle.begin_fill() elif status == STATUS_UNFILL: turtle.color(COLORS[sides]) angle = (SUM_OF_ALL_ANGLES_OF_POLYGON / sides) for x in range(sides): vertices.append(turtle.position()) headings.append(turtle.heading() + OFFSET_OF_POLYGON) turtle.forward(length) sum += length turtle.left(angle) if status == STATUS_FILL: turtle.end_fill() turtle.up() return vertices, headings, sum
def dessinerCouleur(chaine,motif,distance,angle,position,direction,xpos,ypos): import turtle as tt from LSysteme import dessiner, alphabet_dessin l1=len(chaine) l2=len(motif) L=[] k=0 while k<l1: #on parcourt la chaine b = True #booléen qui indique si la chaine est un motif if chaine[k] == motif[0]: if k+l2-1 < l1: #on vérifie que l'on ne va pas dépasser la chaine for m in range(l2): if alphabet_dessin.find(chaine[k+m]) != -1 and chaine[k+m] != motif[m]: b = False #on vérifie que l'on a un motif ou que les caractères n'influent pas le motif if b: #si c'est bien un motif, on le colorie en rouge tt.color((1,0,0)) xpos,ypos,L=dessiner(motif,L,distance,angle,position,direction,xpos,ypos) tt.color((0,0,0)) k+=l2 else : b = False else : b = False if not b: #si le ce n'est pas un motif, on éffectue les translations et rotations xpos,ypos,L=dessiner(chaine[k],L,distance,angle,position,direction,xpos,ypos) k+=1 position = tt.pos() direction = tt.heading() return xpos,ypos
def leaf(x, y, node): # til = turtle.heading() i = random.random() an = random.randint(10, 180) ye = random.randint(6, 9) / 10 turtle.color(ye, ye * 0.9, 0) turtle.fillcolor(ye + 0.1, ye + 0.05, 0) turtle.pensize(1) turtle.pendown() turtle.setheading(an + 90) turtle.forward(8 * i) px = turtle.xcor() py = turtle.ycor() turtle.begin_fill() turtle.circle(7.5 * i, 120) # 画一段120度的弧线 turtle.penup() # 抬起笔来 turtle.goto(px, py) # 回到圆点位置 turtle.setheading(an + 90) # 向上画 turtle.pendown() # 落笔,开始画 turtle.circle(-7.5 * i, 120) # 画一段120度的弧线 turtle.setheading(an + 100) turtle.circle(10.5 * i, 150) turtle.end_fill() # 画一段150度的弧线 turtle.penup() turtle.goto(x, y) turtle.setheading(til) turtle.pensize(node / 2 + 1)
def main(): """主程序""" turtle.speed(12) # 海龟速度 turtle.penup() # 抬起笔,默认按下 x, y = -270, -180 # 画国旗主体 width, height = 540, 360 draw_rectangle(x, y, width, height) # 画大星星 pice = 22 center_x, center_y = x + 5 * pice, y + height - pice * 5 turtle.goto(center_x, center_y) turtle.left(90) turtle.forward(pice * 3) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice * 3) # 海龟的x,y坐标 x_poses, y_poses = [10, 12, 12, 10], [2, 4, 7, 9] # 画小星星 for x_pos, y_pos in zip(x_poses, y_poses): # 将x_poses和y_poses打包为元组的列表,长度以最短为准,[(10,2),(12,4).....] turtle.goto(x + x_pos * pice, y + height - y_pos * pice) turtle.left(turtle.towards(center_x, center_y) - turtle.heading()) # 海龟初始朝向和海龟该点至目标点所成矢量的夹角 # heading为海龟的朝向 turtle.forward(pice) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice) # 隐藏海龟 turtle.ht() # 显示绘图窗口 turtle.mainloop()
def collistioncalc(turtle, bool=0): grada = turtle.heading() if bool == 0: turtle.setheading(180 - grada) else: turtle.setheading(360 - grada)
def drawString( dstring, distance, angle ): """ Interpret the characters in string dstring as a series of turtle commands. Distance specifies the distance to travel for each forward command. Angle specifies the angle (in degrees) for each right or left command. The list of turtle supported turtle commands is: F : forward - : turn right + : turn left [ : save position, heading ] : restore position, heading """ stack = [] for c in dstring: if c == 'F': turtle.forward(distance) elif c == '-': turtle.right(angle) elif c == '+': turtle.left(angle) elif c == '[': stack.append(turtle.position()) stack.append(turtle.heading()) elif c == ']': turtle.up() turtle.setheading(stack.pop()) turtle.goto(stack.pop()) turtle.down() turtle.update()
def makeSquare(size, person=None, fill=False): origPosition = turtle.pos() origHead = turtle.heading() turtle.penup() goDown(size) if(person != None or fill == True): if(fill==True or person.affected): turtle.begin_fill() turtle.pendown() goLeft(size) goUp(2*size) goRight(2*size) goDown(2*size) goLeft(size) if(person != None or fill==True): if(fill==True or person.affected): turtle.end_fill() turtle.penup() turtle.goto(origPosition) turtle.setheading(origHead) if(person != None or fill==True): if(fill==True or person.affected): turtle.color('black') if(person.multipleNotShown == 0): turtle.write(str(person.name())+"\n"+probString(person), align="center") else: turtle.write(str(person.name())+"\n"+probString(person)+"\n\n"+str(person.multipleNotShown), align="center") turtle.color('blue') turtle.penup()
def verificarPos(self): """ Desc: Método para verificar se a posição e sentido da tartaruga é igual ao inicial Use getPos() para pegar o inicial Printa: String = Erro Retorna: Boolean = True (caso esteja ok) ou False (caso não) Exemplo: cb.getPos() cb.casa(25, 50, 30) cb.verificarPos() """ self._retorno = True if (round(turtle.xcor()) != self.turtlePosX) or (round(turtle.ycor()) != self.turtlePosY): print("A posição atual da tartaruga difere da inicial ({0}, {1})\nEla está em: ({2}, {3})".format(str(self.turtlePosX), str(self.turtlePosY), str(round(turtle.xcor())), str(round(turtle.ycor())))) self._retorno = False if turtle.heading() != self.turtleDir: print("A direção atual da tartaruga difere da inicial (" + str(self.turtleDir) + ")\nEla está em:", str(turtle.heading())) self._retorno = False return self._retorno
def main(): turtle.speed(12) turtle.penup() x,y=-270,-180 width,height=540,360 #pint rectangle draw_rectangle(x, y, width, height) #pint big star pice = 22 center_x, center_y = x + 5 * pice, y + height - pice * 5 turtle.goto(center_x, center_y) turtle.left(90) turtle.forward(pice * 3) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice * 3) #pint little star x_poses, y_poses = [10, 12, 12, 10], [2, 4, 7, 9] for x_pos, y_pos in zip(x_poses, y_poses): turtle.goto(x + x_pos * pice, y + height - y_pos * pice) turtle.left(turtle.towards(center_x, center_y) - turtle.heading()) turtle.forward(pice) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice) # 隐藏海龟 turtle.ht() # 显示绘图窗口 turtle.mainloop()
def main(): """主程序""" # 画笔移动速度 turtle.speed(6) # 关闭画笔,不会在画布上留下路径 turtle.penup() x, y = -270, -180 # 画国旗主体 width, height = 500, 360 draw_rectangle(x, y, width, height) # 画大星星 pice = 22 center_x, center_y = x + 5 * pice, y + height - pice * 5 turtle.goto(center_x, center_y) turtle.left(90) turtle.forward(pice * 3) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice * 3) x_poses, y_poses = [10, 12, 12, 10], [2, 4, 7, 9] # 画小星星 for x_pos, y_pos in zip(x_poses, y_poses): turtle.goto(x + x_pos * pice, y + height - y_pos * pice) turtle.left(turtle.towards(center_x, center_y) - turtle.heading()) turtle.forward(pice) turtle.right(90) draw_star(turtle.xcor(), turtle.ycor(), pice) # 隐藏画笔 turtle.ht() # 显示绘图窗口 turtle.mainloop()
def drawKochCurve(startPosition, heading, length): if length < 1: # BASE CASE return else: # RECURSIVE CASE # Move to the start position. recursiveArgs = [] turtle.penup() turtle.goto(startPosition) turtle.setheading(heading) recursiveArgs.append({ 'position': turtle.position(), 'heading': turtle.heading() }) # Erase the middle third. turtle.forward(length / 3) turtle.pencolor('white') turtle.pendown() turtle.forward(length / 3) # Draw the bump. turtle.backward(length / 3) turtle.left(60) recursiveArgs.append({ 'position': turtle.position(), 'heading': turtle.heading() }) turtle.pencolor('black') turtle.forward(length / 3) turtle.right(120) recursiveArgs.append({ 'position': turtle.position(), 'heading': turtle.heading() }) turtle.forward(length / 3) turtle.left(60) recursiveArgs.append({ 'position': turtle.position(), 'heading': turtle.heading() }) for i in range(4): drawKochCurve(recursiveArgs[i]['position'], recursiveArgs[i]['heading'], length / 3) return
def dessiner(chaine, distance, angle, position, direction, xpos, ypos): """Fonction qui dessine la chaine qu'on lui donne en entrée""" import turtle as tt import random as rd L = [] wasdown = tt.isdown() # on vérifie si il faut dessiner ou pas tt.penup() #on "lève le crayon" pour ne pas dessiner lorsque l'on initialise la tortue tt.setheading(direction) tt.goto(position ) #on commence à la position voulue et avec la direction voulue if wasdown: tt.pendown() tt.speed(0) #on prend la vitesse maximale de la tortue tt.hideturtle() #on cache le curseur for k in chaine: # On peut définir l'angle avec une borne inférieure et une borne supérieure if not tt.fill(): if type(angle) == tuple: theta = rd.uniform(angle[0], angle[1]) else: theta = angle if k == 'F': tt.fd(distance) #on fait un trait simple elif k == 'f': #on "lève le crayon" pour avancer sans tracer tt.penup() tt.fd(distance) if wasdown: tt.pendown() elif k == '+': #on tourne la tortue à gauche tt.left(theta) elif k == '-': tt.right(theta) #on tourne à droite elif k == '|': #on tourne de 180° tt.right(180) elif k == '[': #on enregistre la position et la direction dans une liste x, y = tt.pos() d = tt.heading() L.append((x, y, d)) #tuple composé de la position (x,y) et de la direction (d) elif k == ']': #on déplace à la dernière position enregistrée dans la liste tt.penup() x, y, d = L.pop() #on sort la dernière position enregistrée et on l'affecte à x,y,d tt.goto((x, y)) #on déplace la tortue à la position x,y tt.setheading(d) #et on lui donne la direction d if wasdown: tt.pendown() elif k == '{': tt.fillcolor('green') tt.begin_fill() elif k == '}': tt.end_fill() (x, y) = tt.pos() xpos.append(x) #liste des positions en x ypos.append(y) #et des positions en y return xpos, ypos #on renvoie les positions
def drawFlame(size, degrees, fillcolor="yellow"): turtle.fillcolor(fillcolor) turtle.begin_fill() turtle.setheading(270) drawSemi(size, "right", degrees, "black") turtle.setheading(turtle.heading()+degrees+degrees-180) drawSemi(size, "right", degrees, "black") turtle.end_fill()
def drawFlame(size, degrees, fillcolor="yellow"): turtle.fillcolor(fillcolor) turtle.begin_fill() turtle.setheading(270) drawSemi(size, "right", degrees, "black") turtle.setheading(turtle.heading() + degrees + degrees - 180) drawSemi(size, "right", degrees, "black") turtle.end_fill()
def drawDome(size, degrees): turtle.setheading(90) turtle.fillcolor("red") turtle.begin_fill() drawSemi(size, "right", degrees, colour="black" ) turtle.setheading(turtle.heading()+degrees+degrees-180) drawSemi(size, "right", degrees, colour="black") turtle.end_fill()
def ballBounce(self,deflection): angleDiff = self.direction - deflection if((angleDiff)>0): newDirection = 30 else: newDirection = -30 turtle.setheading(self.direction+newDirection) self.direction = turtle.heading()
def drawDome(size, degrees): turtle.setheading(90) turtle.fillcolor("red") turtle.begin_fill() drawSemi(size, "right", degrees, colour="black") turtle.setheading(turtle.heading() + degrees + degrees - 180) drawSemi(size, "right", degrees, colour="black") turtle.end_fill()
def moveDir(turtle, direction): if turtle.heading() != direction: turtle.setheading(direction) turtle.forward(MOVING_DISTANCE) global remainingY newY = remainingY - 1 remainingY = newY
def sv_tree(trunk_length, levels): """create a tree diagram using recursion, color change in a certain period defined by cosine function.""" if levels == 0: return turtle.pensize(levels) turtle.pencolor(0.7 * math.fabs(math.cos(turtle.heading())), 0, 0.7 * math.fabs(math.cos(turtle.heading()))) turtle.forward(trunk_length) turtle.left(30) sv_tree(trunk_length * 0.9, levels - 1) turtle.right(60) sv_tree(trunk_length * 0.9, levels - 1) turtle.left(30) turtle.penup() turtle.backward(trunk_length) turtle.pendown() return
def tree(n, l): p = turtle turtle.pd() t = math.cos(math.radians(turtle.heading() + 45)) / 8 + 0.25 p.pencolor(t, t, t) p.pensize(n / 3) p.forward(l) if n > 0: b = random.random() * 15 + 10 c = random.random() * 15 + 10 d = l * (random.random() * 0.25 + 0.7) p.right(b) tree(n - 1, d) p.left(b + c) tree(n - 1, d) p.right(c) else: p.right(90) n = math.cos(math.radians(turtle.heading() - 45)) / 4 + 0.5 p.pencolor(n, n * 0.8, n * 0.8) p.circle(3) p.left(90) if random.random() > 0.7: p.pu() t = turtle.heading() print(t) an = -40 + random.random() * 40 turtle.setheading(an) dis = int(800 * random.random() * 0.5 + 400 * random.random() * 0.3 + 200 * random.random() * 0.2) p.forward(dis) p.setheading(t) p.pd() p.right(90) n = math.cos(math.radians(p.heading() - 45)) / 4 + 0.5 p.pencolor(n * 0.5 + 0.5, 0.4 + n * 0.4, 0.4 + n * 0.4) p.circle(2) p.left(90) p.pu() ts = turtle.heading() p.setheading(an) p.backward(dis) p.setheading(ts) p.pu() p.backward(l)
def tremember_state(self): state = {"heading": turtle.heading(), "position": turtle.position()} print( f"[DEBUG]: Remembering turtle state (heading, pox, posy)" f"[DEBUG]: ({state['heading']}, {state['position'][0]}, {state['position'][1]})" ) self.memory.append(state)
def creation_triangle(self): #choix de taille du triangle self.chx = random.randint(10, 100) tt.begin_fill() for _ in range(3): tt.forward(self.chx) tt.left(120) tt.end_fill() print("debug", tt.heading())
def e_branch(self): global length global NewNodeQue turtle.up() turtle.setpos(self.NodePosition) turtle.down() turtle.setheading(self.GrowAngle) d = Node('d',self.NodePosition,self.GrowAngle) dNodeQue.put(d) turtle.left(angle) turtle.forward(length) a = Node('a',turtle.pos(),turtle.heading()) NewNodeQue.put(a) turtle.up() turtle.setpos(d.NodePosition) turtle.down() turtle.setheading(d.GrowAngle) turtle.forward(length) b = Node('b',turtle.pos(),turtle.heading()) NewNodeQue.put(b)
def triforceFlower(turtle, center, heading, length, color): #draws a flower made up of triforces rotated around a point turtle.penup() turtle.goto(center) turtle.pendown() turtle.setheading(heading) turtle.color(color) for k in range(20): triforce(turtle, turtle.position(), turtle.heading(), length, turtle.color()[0], turtle.pensize()) turtle.left(120) turtle.right(18)
def sign(): turtle.color("chocolate") turtle.width(5) Base((-250,-200)) turtle.setheading(0) turtle.fd(100) Tip = turtle.pos() turtle.fill(True) for x in range (1,5): turtle.setheading(turtle.heading() + 90) if x % 2 != 0: turtle.fd(150) else: turtle.fd(75) if turtle.heading() == 180: turtle.fd(25) turtle.bk(25) turtle.fillcolor('chocolate') turtle.fill(False) def writing(): turtle.width(1) turtle.color("white") Base((-250,-100)) turtle.setheading(162) turtle.pu() turtle.fd(28) turtle.setheading(180) turtle.fd(10) turtle.write("Raphaella and Danes' ", font=("Calibri", 12, "italic")) turtle.fd(14) turtle.pd() turtle.write(" Apple Tree",font = ("Calibri",12,"bold")) writing() turtle.setheading(0)
def sjekk_landing(): x = turtle.xcor() vinkel = turtle.heading() if x < -200 or x > 0: print('Du landet utenfor basen!') elif abs(vinkel - 90) > 10: print('Du landet skjevt!') elif romskip['fart_y'] < -1: print('Du landet for hardt!') else: print('Perfekt landing!')
def Apple(b): turtle.color('red') y = turtle.heading() turtle.setheading(180) moveTurtle(15) turtle.setheading(90) turtle.begin_fill() turtle.circle(5) turtle.fillcolor("red") turtle.end_fill() Base(b) turtle.setheading(y)
def draw(self): "draws the lsystem on the screen" stack = [] tt.penup() tt.setpos(0, -200) tt.seth(90) tt.pendown() print "Drawing the lsystem ..." for i, codebit in enumerate(self.generation[-1]): if codebit in ['F', 'A', 'B']: tt.forward(self.length) print '[ FRWD ] ', codebit elif codebit == '+': tt.right(self.angle) print '[ RGHT ] ', codebit elif codebit == '-': tt.left(self.angle) print '[ LEFT ] ', codebit elif codebit == '[': stack.append((tt.pos(), tt.heading())) print '[ PUSH ] ', (tt.pos(), tt.heading()) elif codebit == ']': position,heading = stack.pop() print '[ POP ] ', (position, heading) tt.penup() tt.goto(position) tt.seth(heading) tt.pendown() else: print '[ NOP ] ', codebit if self.save_every_frame: self.save(frame=i) print "Done drawing" print "Saving file as %s.jpg" % self.name, self.save() print "Done"
def execute_L(turtle, state, command_array): saved_state = [] for command in command_array: if command == "F" or command == "f": turtle.forward(10) elif command == "+": turtle.right(5) elif command == "-": turtle.right(355) elif command == "[": saved_state = [turtle.heading(), turtle.pos()] elif command == "]": turtle.goto(saved_state[1]) turtle.seth(int(saved_state[0]))
def getPos(self): """ Desc: Método para pegar posição e sentido da tartaruga Use verificarPos() para verificar se é igual a inicial Exemplo: cb.getPos() cb.casa(25, 50, 30) cb.verificarPos() """ self.turtlePosX = round(turtle.xcor()) self.turtlePosY = round(turtle.ycor()) self.turtleDir = turtle.heading()
def connectFamily(parents, children, size, offset=0, color='blue'): origPosition = turtle.pos() origHead = turtle.heading() oldColor = turtle.pencolor() turtle.pencolor(color) turtle.penup() # parents are a tuple of positions for the parents # children are a tuple of positions of the children # all positions are from the center of each shape if(len(parents) == 2): # if we have 2 parents parentA = parents[0] parentB = parents[1] # draw horizontal line between parents turtle.goto(parentA) goDown(offset) goRight(size) turtle.pendown() goRight(parentB[0]-parentA[0]-2*size) goLeft((parentB[0]-parentA[0]-2*size)/2 + offset) goDown(2*size) else: # if unaffected mate == True parentA = parents[0] turtle.goto(parentA) goDown(size) turtle.pendown() goDown(offset) currentPosition = turtle.pos() for child in children: horizDist = currentPosition[0] - child[0] verticalDist = currentPosition[1] - child[1] - size goLeft(horizDist) goDown(verticalDist) turtle.penup() turtle.goto(currentPosition) turtle.pendown() turtle.penup() turtle.goto(origPosition) turtle.setheading(origHead) turtle.pencolor(oldColor) turtle.up()
def draw_flag(country_str, flag_width_float, orientation_str): """ Asks the for the name of the country, the width and the orientation and draws a the flag using turtle Recieve: The name of country, the width of the flag, and the orientation Return: Nothing Algorithm: Save the initial position Check to make sure the country is valid Check to make sure the width is valid and more than zero Check to make sure the orientation is vallid Check to see what country needs to be drawn and call the corresponding function Go back to the intial position """ turtle.colormode(255) initial_pos_list = [turtle.xcor(), turtle.ycor(), turtle.heading()] country_str = country_str.lower() orientation_str = orientation_str.lower() if is_valid_country(country_str) == False: print('***Invalid country name. Please try again.***') return if type(flag_width_float) == str or flag_width_float <= 0.00: print('***Invalid flag width. Please try again.***') return if orientation_str == 'landscape' or orientation_str == 'portrait': if orientation_str == 'portrait': turtle.right(90) else: print('***Invalid orientation. Please try again.***') return if country_str == 'denmark': draw_denmark(flag_width_float) elif country_str == 'sweden': draw_sweden(flag_width_float) elif country_str == 'faroe islands': draw_faroe_island(flag_width_float) elif country_str == 'norway': draw_norway(flag_width_float) elif country_str == 'iceland': draw_iceland(flag_width_float) elif country_str == 'finland': draw_finland(flag_width_float) go_to_pos(initial_pos_list) turtle.fillcolor('black')
def exercise_5_2(): try: n = int(raw_input("Nombre de côtés (> 2) : ")) # Pas de verif, on suppose que l'utilisateur est intelligent assert(n > 2) except: print("Un nombre plus grand que 2. C'est pourtant pas compliqué.") return t.hideturtle() t.speed("fastest") for i in range(n): t.forward(500 / n) t.setheading(t.heading() + 360 / n) t.up() t.goto(0, -50) t.write(str(n) + " côtés", True, align="center", font=("Arial", 16, "normal")) t.mainloop()
def consumeLSystem(lString): for k in lString: if k =="l": turtle.left(45) if k =="r": turtle.right(45) if k =="f": curLen = 0 if turtle.heading() % 90 > 1: curLen = diagLen else: curLen = horizLen turtle.forward(curLen) if k =="[": pushState() if k =="]": popState()
def tree(level, length): if level == 0: return turtle.forward(length) pos = turtle.position() heading = turtle.heading() turtle.left(45) tree(level - 1, length / 2) turtle.penup() turtle.setposition(pos) turtle.setheading(heading) turtle.pendown() turtle.right(45) tree(level - 1, length / 2)