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 draw_l_system(turtle, instruction_list, positions, unit_length=1, unit_angle=1): stack = [] for command in instruction_list: turtle.pd() if command[0] in ["F"]: turtle.forward(command[1]*unit_length) elif command[0] == "f": turtle.pu() # pen up - not drawing turtle.forward(command[1]*unit_length) elif command[0] == "+": turtle.right(command[1]*unit_angle) elif command[0] == "-": turtle.left(command[1]*unit_angle) elif command[0] == "S": positions.append(turtle.position()) elif command[0] == "[": stack.append((turtle.position(), turtle.heading())) elif command[0] == "]": turtle.pu() # pen up - not drawing position, heading = stack.pop() turtle.goto(position) turtle.setheading(heading)
def draw_square_and_circle(): window = turtle.Screen() window.bgcolor("red") count = 0 while count < 4: turtle.position() turtle.forward(100) turtle.right(90) count = count + 1 angie = turtle.Turtle() angie.shape("arrow") angie.color("blue") angie.circle(100) todd = turtle.Turtle() todd.shape("arrow") todd.color("green") todd_count = 0 whilte todd_count < 3: todd.forward(300) todd.left(120) todd_count = todd_count + 1
def main(): #设置一个画面 windows = turtle.Screen() #设置背景 windows.bgcolor('pink') #生成一个黄色乌龟 bran = turtle.Turtle() bran.shape('turtle') bran.color('red') #开始你的表演 turtle.home() turtle.dot() for i in range(1, 10): turtle.fd(50) turtle.dot(30, "blue") turtle.fd(50) turtle.position() (100.00, -0.00) turtle.heading() 0.0 turtle.fd(50) turtle.right(90) turtle.fd(50) turtle.stamp() 11 turtle.fd(50) time.sleep(10)
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 that_thing (depth, size): if depth > 0: turtle.up() turtle.goto(size / 4, size / 4) turtle.down() turtle.right(90) turtle.forward(size * (4/6)) pos = turtle.position() turtle.forward(size * (2/6)) turtle.goto(pos) turtle.right(90) turtle.forward(size * (4 / 6)) pos = turtle.position() turtle.forward(size * (2 / 6)) turtle.goto(pos) turtle.right(90) turtle.forward(size * (4 / 6)) pos = turtle.position() turtle.forward(size * (2 / 6)) turtle.goto(pos) turtle.right(90) turtle.forward(size * (4 / 6)) pos = turtle.position() turtle.forward(size * (2 / 6)) turtle.goto(pos) that_thing(depth - 1, size / 2)
def drawTriangle(turtle,length,levels,xLocation,yLocation): test = raw_input("level is" + str(levels)+ "length is "+ str(length)) if levels == 0: return else: turtle.setposition(xLocation,yLocation) length = float(length/2) turtle.pendown() levels = levels - 1 point1 = turtle.position() x1location = float(point1[0]) y1location = float(point1[1]) turtle.forward(100) turtle.right(120) point2 = turtle.position() x2location = float(point2[0]) y2location = float(point2[1]) turtle.forward(100) turtle.right(120) point3 = turtle.position() x3location = float(point3[0]) y3location = float(point3[1]) turtle.forward(100) turtle.penup() turtle.setheading(90) drawTriangle(turtle,length,levels,x1location/2,y1location/2) drawTriangle(turtle,length,levels,x2location/2,y2location/2) drawTriangle(turtle,length,levels,x3location/2,y3location/2)
def draw(list_rectangles, list_squares): """ draw squares with turtle """ t = turtle.Turtle() t.color('red') t.pensize(5) t.shape('turtle') t.speed(1) for i in list_rectangles: t.penup() t.setx(i.x) t.sety(i.y) t.pendown() t.forward(i.width) t.left(90) t.forward(i.height) t.left(90) t.forward(i.width) t.left(90) t.forward(i.height) for u in list_squares: t.color('blue') t.penup() t.setx(u.x) t.sety(u.y) t.pendown() turtle.position() t.forward(u.size) t.left(90) t.forward(u.size) t.left(90) t.forward(u.size) t.left(90) t.forward(u.size)
def run(self): ''' 主函数入口 ''' t.speed(0) t.setup(self.length_and_width[0], self.length_and_width[1]) # 设置窗口尺寸 t.bgcolor(0, 0, 0) x = -self.length_and_width[0] / 2 y = -self.length_and_width[1] / 2 # 设置绘制标志的初始位置: 位于底部左小角 t.goto(x, y) print(x, y) print(self.length_and_width) print(t.position()) print(self.star_diameter) print("==================") print(self.blue_rectangle_width_10) print(self.blue_rectangle_length_12) self.draw_red_and_white_stripes(t, self.stripe_width, self.stripe_Length, x, y) self.draw_blue_rectangle(t) (x, y) = t.position() self.draw_fifty_stars(t, x, y) t.hideturtle() t.done()
def main(): path_data = open('path.txt').read() print turtle.position() turtle.penup() turtle.setposition(-400,200) turtle.pendown() turtle.speed(0) turtle.delay(0) for c in path_data: if c in 'NSEW*': if c == 'N': turtle.setheading(90) turtle.forward(1) if c == 'S': turtle.setheading(270) turtle.forward(1) if c == 'E': turtle.setheading(0) turtle.forward(1) if c == 'W': turtle.setheading(180) turtle.forward(1) if c == '*': if turtle.isdown(): turtle.penup() else: turtle.pendown()
def initPosition(left, up): print("init position: ", turtle.position()) turtle.penup() turtle.backward(left) turtle.left(90) turtle.forward(up) turtle.right(90) turtle.pendown() print("move to position: ", turtle.position())
def goto(point): turtle.goto(scale * point['X'], scale * point['Y']) posx = turtle.position()[0] posy = turtle.position()[1] screenx = screen.screensize()[0] screeny = screen.screensize()[1] if abs(posx) * 2 >= screenx: screen.screensize(canvwidth=2 * posx + 1) if abs(posy) * 2 >= screeny: screen.screensize(canvheight=2 * posy + 1)
def Rule1(i, sign): start = turtle.position() Urform(i, sign) stop = turtle.position() if i < level: turtle.goto(start) turtle.forward(480.0 * scale / (3**i)) turtle.right(90 * sign) Rule2(i + 1, -sign) turtle.goto(stop) else: Rule3()
def drawpic(): change = 0 #a super cute turtle draws my picture and this mode sets the whole drawing color to pink turtle.shape("turtle") turtle.colormode(255) turtle.color(215, 100, 170) turtle.speed(0) #draws the flower for angle in range(0, 360, 15): turtle.seth(angle) turtle.circle(50) turtle.penup() turtle.position() turtle.pendown() #draws the stem turtle.pencolor("green") turtle.pensize(5) turtle.right(75) turtle.forward(200) turtle.fillcolor("green") #draws the right leaf turtle.pensize(2) turtle.left(75) turtle.begin_fill() for ang in range(1, 20): leaf_right(turtle, ang, 10) for ang in range(20, 15, -1): leaf_right(turtle, ang, 24) turtle.end_fill() #draws the left leaf turtle.penup() yaxis = turtle.ycor() turtle.setposition(0, yaxis) turtle.pendown() turtle.right(80) turtle.begin_fill() for ang in range(1, 20): leaf_left(turtle, ang, 10) for ang in range(20, 15, -1): leaf_left(turtle, ang, 25) turtle.end_fill() turtle.exitonclick()
def forward(self, distance): '''makes the turtle go forward''' if self.style == 'normal': turtle.forward(distance) elif self.style == 'jitter': (x0, y0) = turtle.position() turtle.penup() turtle.forward(distance) (xf, yf) = turtle.position() curwidth = turtle.width() jx = random.gauss(0, self.jitterSigma) jy = random.gauss(0, self.jitterSigma) kx = random.gauss(0, self.jitterSigma) ky = random.gauss(0, self.jitterSigma) turtle.width(curwidth + random.randint(0, 2)) turtle.goto(x0 + jx, y0 + jy) turtle.pendown() turtle.goto(xf + kx, yf + ky) turtle.penup() turtle.goto(xf, yf) turtle.width(curwidth) turtle.pendown() elif self.style == 'jitter3': for i in range(3): (x0, y0) = turtle.position() turtle.penup() turtle.forward(distance) (xf, yf) = turtle.position() curwidth = turtle.width() jx = random.gauss(0, self.jitterSigma) jy = random.gauss(0, self.jitterSigma) kx = random.gauss(0, self.jitterSigma) ky = random.gauss(0, self.jitterSigma) turtle.width(curwidth + random.randint(0, 2)) turtle.goto(x0 + jx, y0 + jy) turtle.pendown() turtle.goto(xf + kx, yf + ky) turtle.penup() turtle.goto(xf, yf) turtle.width(curwidth) turtle.pendown() elif self.style == 'dotted': (x0, y0) = turtle.position() numcircles = (distance / self.dotSize + 1) for i in range(4): turtle.color(random.random(), random.random(), random.random()) turtle.dot(self.dotSize) turtle.penup() turtle.forward(distance * 2) turtle.pendown()
def triangulos(n, base, lado): #x0 = -base/2 #x1 = base/2 #y0 = y1 = sqrt((base/2)^2 + lado^2) x = -base/2 y = -math.sqrt((base/2)**2 + lado**2) #x e y são coordenadas do canto inferior esquerdo do triangulo maior for i in range(n): turtle.setheading(turtle.towards(x, y)) #aponta na direcao do canto inferior esquerdo turtle.forward((i+1)*lado) #avanca o comprimento de n (i+1) lados sendo n o numero do triangulo a desenhar atualmente turtle.goto(-turtle.position()[0],turtle.position()[1]) #vai para a posicao simetrica ao canto inferior esquerdo (canto inferior direito) turtle.goto(0,0) #volta à origem, canto superior turtle.hideturtle() turtle.exitonclick()
def left(who): global previousMove turtle, path = players[who] turtle.setheading(180) if previousMove != 'left': path.append(turtle.position()) previousMove = 'left' turtle.fd(15) #here it checks if the you have collided before making the next move if checkCollision(turtle.position(), path, players[1 - who][PATH]): collision(turtle)
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 rysuj(): turtle.tracer(0, 0) # wylaczenie animacji co KROK, w celu przyspieszenia turtle.hideturtle() # ukrycie glowki zolwika turtle.penup() # podnosimy zolwia, zeby nie mazal nam linii podczas ruchu ostatnie_rysowanie = 0 # ile kropek temu zostal odrysowany rysunek for i in xrange(ILE_KROPEK): # losujemy wierzcholek do ktorego bedziemy zmierzac do = random.choice(WIERZCHOLKI) # bierzemy nasza aktualna pozycje teraz = turtle.position() # ustawiamy sie w polowie drogi do wierzcholka, ktorego wczesniej obralismy turtle.setpos(w_polowie_drogi(teraz, do)) # stawiamy kropke w nowym miejscu turtle.dot(1) ostatnie_rysowanie += 1 if ostatnie_rysowanie == OKRES_ODSWIEZENIA: # postawilismy na tyle duzo kropek, zeby odswiezyc rysunek turtle.update() ostatnie_rysowanie = 0 pozdrowienia() turtle.update()
def random_walk(n): turtle.setposition(0,0) for i in range(n): turtle.setheading(random.random()*360) turtle.forward(10) return turtle.position()
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 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_rectangle (turtle,x,y,width,height=None,color="black"): """ This function draws Parameters turtle : `turtle.Turtle` x : float y : float width : float height : float color : string """ # store the current turtle position store_x,store_y = turtle.position() store_color = turtle.color()[0] move(turtle,x,y) turtle.color(color) # draw the rectangle turtle.goto(x,y-height) turtle.goto(x-width,y-height) turtle.goto(x-width,y) turtle.goto(x,y) # move(turtle,store_x,store_y) turtle.color(store_color)
def Adjust(): [x, y] = turtle.position() turtle.penup() x = x + 90 turtle.goto(x, 0) turtle.pendown() turtle.setheading(90)
def generateTurtle( self, n): # generates turtle graphics window that draws system stack = [] import turtle turtle.pensize(1) turtle.speed(0) turtle.hideturtle() turtle.setheading(30) turtle.bgcolor('light gray') turtle.screensize(10000, 10000) for k in self.returnString(n): if self.alphabet[k][1] == 'none': continue elif self.alphabet[k][1] == 'forward': turtle.forward(self.distance) elif self.alphabet[k][1] == 'left': turtle.left(self.angle) elif self.alphabet[k][1] == 'right': turtle.right(self.angle) elif self.alphabet[k][1] == 'push': stack.append((turtle.position(), turtle.heading())) elif self.alphabet[k][1] == 'pop': turtle.penup() position, heading = stack.pop() turtle.setposition(position) turtle.setheading(heading) turtle.pendown() turtle.bgcolor('white') turtle.exitonclick()
def turtle_draw(turtle, instructions): pos = [] ang = [] for char in instructions: angle = random.randrange(15, 36) steps = random.randrange(2, 7) if char == '1': turtle.forward(steps) elif char == '0': turtle.forward(steps) turtle.forward(-steps) elif char == '-': pos.append(turtle.position()) ang.append(turtle.heading()) turtle.left(angle) elif char == '+': turtle.up() turtle.goto(pos.pop()) turtle.down() turtle.setheading(random.randrange(75, 96)) turtle.forward(random.randrange(3, 8)) turtle.setheading(ang.pop()) turtle.right(angle)
def draw(chars, size=2): stack = [] for ch in chars: if ch == 'F': turtle.forward(size) elif ch == '-': turtle.left(25) elif ch == '+': turtle.right(25) elif ch == 'X': pass elif ch == '[': stack.append((turtle.position(), turtle.heading())) elif ch == ']': position, heading = stack.pop() turtle.penup() turtle.setposition(position) turtle.setheading(heading) turtle.pendown() else: raise ValueError('Unknown char: {}'.format(ord(ch))) turtle.update()
def drawBranch(startPosition, direction, branchLength): if branchLength < 5: # Base case; the branches are two small to keep drawing more: return # Go to the starting point & direction: turtle.penup() turtle.goto(startPosition) turtle.setheading(direction) # Draw the branch (thickness is 1/7 the length): turtle.pendown() turtle.pensize(max(branchLength / 7.0, 1)) turtle.forward(branchLength) # Record the position of the branch's end: endPosition = turtle.position() leftDirection = direction + LEFT_ANGLE leftBranchLength = branchLength - LEFT_DECREASE rightDirection = direction - RIGHT_ANGLE rightBranchLength = branchLength - RIGHT_DECREASE # Recursive case; draw two more branches: drawBranch(endPosition, leftDirection, leftBranchLength) drawBranch(endPosition, rightDirection, rightBranchLength)
def printTextInStatus(text): logger.msg(f"Printing status: {text}") currentposition = turtle.position() currentheading = turtle.heading() turtle.up() turtle.goto(0, 0) turtle.seth(direct['NORTH']) turtle.forward(tilesize * (mapwidth / 2)) turtle.color('white', 'white') turtle.down() turtle.begin_fill() turtle.seth(direct['WEST']) turtle.forward(tilesize * (mapwidth / 2)) turtle.seth(direct['NORTH']) turtle.forward(turtle.window_height() * 0.1) turtle.seth(direct['EAST']) turtle.forward(tilesize * mapwidth) turtle.seth(direct['SOUTH']) turtle.forward(turtle.window_height() * 0.1) turtle.seth(direct['WEST']) turtle.forward(tilesize * (mapwidth / 2)) turtle.end_fill() turtle.up() turtle.color('black') turtle.write(text, False, "center", ("Arial", 18, "bold")) turtle.goto(currentposition) turtle.seth(currentheading)
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 drawInfill(): '''Draw a simple picture using a turtle''' turtle.title('Donatello') print(turtle.window_height()) print(turtle.window_width()) print(turtle.position()) turtle.penup() turtle.setpos(0, -250) turtle.begin_fill() turtle.left(90) turtle.stamp() turtle.pendown() turtle.color('red') turtle.right(90) turtle.speed(10) turtle.circle(250) turtle.end_fill() turtle.penup() turtle.setpos(-250, 0) turtle.color('black') turtle.stamp() turtle.penup() turtle.setpos(0, 250) turtle.right(90) turtle.stamp() turtle.setpos(250, 0) turtle.right(90) turtle.stamp() turtle.pendown()
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 restart(): x, y = turtle.position() if ((x - c_x)**2 + (y - c_y)**2) <= 50**2: turtle.reset() turtle.home() draw_circle() turtle.pendown()
def plot(self, screen, iterations, size, reset=True, tracer=(0, 0)): if reset: screen.clearscreen() screen.tracer(*tracer) stack = [] for c in self.expand(iterations): if c == "F": fd(size) elif c == "G": pu() fd(size) pd() elif c == "+": rt(self.angle) elif c == "-": lt(self.angle) elif c == "[": stack.append((position(), heading())) elif c == "]": p, h = stack.pop() pu() setposition(p) setheading(h) pd() screen.update()
def draw_bars(self, turtle, binary, length): ''' This function draws the bars for a UPC given the turtle to use, the binary associated with the bars and the length the width of every bar will be 3 pixels wide White = 0 Black = 1 Direction 0 = down Direction 1 = up :param turtle: The turtle to use :param binary: A string containing the binary digits to be drawn :param length: The length of the line from top to bottom in pixels :return: None ''' starty = -97 direction = 0 x = turtle.position()[0] turtle.setposition( x, starty ) # I reset the top of the UPC (y coordinate) each time because the bar code was being draw # like stair steps because it was starting at the bottom where the other section left off. for i in (binary): if i == '0': color = ('white') elif i == '1': color = ('black') else: color = ( 'red' ) # Only here for error checking if I see red bars I know something is wrong. if direction == 0: self.draw_down_line(turtle, color, length) direction = 1 elif direction == 1: self.draw_up_line(turtle, color, length) direction = 0
def __drawHelp(self, size, pos): """ The private helper method to draw the tree. Parameters: size (int): How large the tree is to be. pos (int): The starting position of the root. """ if (size < 20): if (size % 2 == 0): # let's only dot about every second one t.dot(50, random.choice(self.leafColours)) return elif (size < 50): t.dot(50, random.choice(self.leafColours)) # inorder traversial t.penup() t.setposition(pos) t.pendown() t.forward(size) thisPos = t.position() thisHeading = t.heading() size = size - random.randint(10, 20) t.setheading(thisHeading) t.left(25) self.__drawHelp(size, thisPos) t.setheading(thisHeading) t.right(25) self.__drawHelp(size, thisPos)
def genTree(length, level): if level != 0: t.pensize(level) t.forward(length) curPosition = t.position() curHead = t.heading() t.left(30) genTree(int(length * 0.9), level - 1) t.penup() t.setposition(curPosition) t.setheading(curHead) t.pendown() lev = level - 1 if lev != 0: t.pensize(lev) t.right(90) genTree(int(length * 0.5), lev - 1) t.penup() t.setposition(curPosition) t.setheading(curHead) t.pendown()
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 ("none" = outline in black, with no fill) 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 draw(): turtle.setup(800, 600) turtle.up() turtle.goto(starting_position) turtle.setheading(starting_angle) turtle.down() for letter in lsystem_string: if letter in ['A', 'B', 'C', 'D', 'E', 'F']: turtle.forward(lsystem_length) elif letter in ['G', 'H', 'I', 'J', 'K', 'L']: turtle.up() turtle.forward(lsystem_length) turtle.down() elif letter in ['M', 'N', 'O', 'P', 'X', 'Y']: pass elif letter == '[': item = [turtle.position(), turtle.heading()] stack.append(item) elif letter == ']': item = stack.pop() turtle.up() turtle.goto(item[0]) turtle.setheading(item[1]) turtle.down() elif letter == '+': turtle.left(lsystem_angle) elif letter == '-': turtle.right(lsystem_angle) elif letter == '^': turtle.left(180) else: turtle.pencolor(lsystem_colours[int(letter)])
def drawBranch(startPosition, direction, branchLength): if branchLength < 5: # BASE CASE return # Go to the starting point & direction. turtle.penup() turtle.goto(startPosition) turtle.setheading(direction) # Draw the branch (thickness is 1/7 the length). turtle.pendown() turtle.pensize(max(branchLength / 7.0, 1)) turtle.forward(branchLength) # Record the position of the branch's end. endPosition = turtle.position() leftDirection = direction + LEFT_ANGLE leftBranchLength = branchLength - LEFT_DECREASE rightDirection = direction - RIGHT_ANGLE rightBranchLength = branchLength - RIGHT_DECREASE # RECURSIVE CASE drawBranch(endPosition, leftDirection, leftBranchLength) drawBranch(endPosition, rightDirection, rightBranchLength)
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 drawLine(x,y,rotation,width,length): turtle.penup() turtle.goto(x,y) turtle.width(width) turtle.setheading(rotation) turtle.pendown() turtle.forward(length) return turtle.position()
def draw_truss(all_l, start_pos, top_hss, diag_hss, bot_hss, scale): """ List of all values, start_pos(x, y), hss widths(mm), scale(pixels/m). """ length = all_l[0] base = all_l[5] top_lens = all_l[1] diag_lens = all_l[2] thetas = all_l[3] alphas = all_l[4] top_rvrs = top_lens[::-1] del thetas[-1] thetas_rvrs = thetas[::-1] alphas_rvrs = alphas[::-1] del alphas_rvrs[0] # last one is shared, drawn already diag_rvrs = diag_lens[::-1] del diag_rvrs[0] # last one is shared # scale = 1600 / length for comfortable scaling turtle.penup() turtle.setpos(start_pos) turtle.pendown() turtle.pensize(top_hss / 1000 * scale) # drawing for top chord for i in range(1, len(top_lens)): # top lens starts at 1 turtle.setheading(0) turtle.left(thetas[i]) turtle.forward(top_lens[i] * scale) for i in range(len(top_rvrs) - 1): # stop before last element for reverse turtle.setheading(0) turtle.right(thetas_rvrs[i]) turtle.forward(top_rvrs[i] * scale) turtle.penup() turtle.setpos(start_pos) # return to start to draw bottom chord and diagonal members turtle.pendown() for i in range(1, len(top_lens)): turtle.pensize(bot_hss / 1000 * scale) turtle.setheading(0) # face east again turtle.forward(base * scale) # draw the bottom section turtle.setheading(180) # face west turtle.right(alphas[i]) turtle.pensize(diag_hss / 1000 * scale) # switch to diagonal size turtle.forward(diag_lens[i] * scale) turtle.setheading(0) # face east turtle.right(alphas[i]) turtle.forward(diag_lens[i] * scale) # end up at the node for i in range(len(top_rvrs) - 1): turtle.pensize(bot_hss / 1000 * scale) turtle.setheading(0) # face east again turtle.forward(base * scale) # draw the bottom section turtle.setheading(0) # face west turtle.left(alphas_rvrs[i]) turtle.pensize(diag_hss / 1000 * scale) # switch to diagonal size turtle.forward(diag_rvrs[i] * scale) turtle.setheading(180) # face east turtle.left(alphas_rvrs[i]) turtle.forward(diag_rvrs[i] * scale) # end up at the node return turtle.position() # return turtle's last position
def fly_romskip(): while True: x, y = turtle.position() if y < -270: return romskip['fart_y'] += gravitasjon turtle.setposition(x + romskip['fart_x'], y + romskip['fart_y'])
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 create_field_line(B, y_m, start_point_px, end_condition): '''Go to the start point and call draw_line_piece(B, y_m) until end_condition happens. end_condition should be a lambda expresssion taking a tuple representing the current position as its only argument.''' tt.penup() tt.setposition(start_point_px) while not end_condition(tuple(tt.position())): draw_line_piece(B, y_m) draw_arrow()
def testBasicShapesAndConnecting(): turtle.home() turtle.speed(1000000) turtle.clear() turtle.color("blue") makeCircle(25) parentA = turtle.position() turtle.penup() goRight(75) turtle.pendown() makeSquare(25) parentB = turtle.position() turtle.penup() goLeft(32.5) goDown(100) goLeft(32.5) turtle.pendown() makeSquare(25) childA = turtle.position() turtle.penup() goRight(75) turtle.pendown() makeDiamond(25) childB = turtle.position() turtle.penup() goRight(75) goDown(49) turtle.pendown() makeDiamond(25) childC = turtle.position() connectFamily([parentA, parentB], [childA, childB, childC], 25)
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)
def check_direction(): """Pre-condition: Checks to see what direction the circle will be drawn in. Post-condition: Finds the position of turtle. - Sets conditions for certain cases and sets the heading of the turtle accordingly. """ x, y = turtle.position() if x - 20 < -180: turtle.setheading(0) elif x + 20 > 180: turtle.setheading(180) elif y - 20 < -180: turtle.setheading(90) elif y + 20 > 180: turtle.setheading(270)
def moveOneDiagonal(): # Where are we? (x,y) = turtle.position() # where should we go? if (isNE()): x += scale y += scale elif (isSE()): x += scale y -= scale elif (isSW()): x -= scale y -= scale else: # isNW() x -= scale y += scale # go there! turtle.setposition(x,y)
def tree(levels, degrees, distance, thickness, scale): if levels == 0: return turtle.width(thickness) initial_heading = turtle.heading() r, g, b = GREEN[0] + levels*dR, GREEN[1] + levels*dG, GREEN[2] + levels*dB turtle.color((r, g, b)) turtle.forward(distance) start = turtle.position() turtle.left(degrees) tree(levels-1, degrees, scale*distance, scale*thickness, scale) turtle.color((r,g,b)) turtle.up() turtle.goto(*start) turtle.down() turtle.setheading(initial_heading) turtle.right(degrees) tree(levels-1, degrees, scale*distance, scale*thickness, scale) return
def drawTree(length, alphaR, alphaL, depth): if depth == 0: return t.forward(length) top = t.position() upangle = t.heading() # Draw the right half of the tree t.right(alphaR) drawTree((ratioR)*length, alphaR, alphaL, depth-1) # Go back to the start t.penup() t.goto(top) t.setheading(upangle) t.pendown() # Draw the left half of the tree t.left(alphaL) drawTree((ratioL)*length, alphaR, alphaL, depth-1)
def draw(cmds, size=2): stack = [] for cmd in cmds: if cmd=='F': turtle.forward(size) elif cmd=='-': turtle.left(25) elif cmd=='+': turtle.right(25) 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() else: raise ValueError('Unknown Cmd: {}'.format(ord(cmd))) turtle.update()
def Executioner(letter): ''' This function will execute a letter's function on the turtle. Parameters: letter - The letter to be executed. ''' if(letter == 'G' or letter == 'F'): turtle.pd() turtle.forward(STEP_DISTANCE) elif(letter == '+'): turtle.right(ANGLE_DELTA) elif(letter == '-'): turtle.left(ANGLE_DELTA) elif(letter == 'f' or letter == 'g'): turtle.pu() turtle.forward(STEP_DISTANCE) elif(letter == '['): POSITION_STACK.append(turtle.heading()) POSITION_STACK.append(turtle.position()) elif(letter == ']'): turtle.pu() turtle.setposition(POSITION_STACK.pop()) turtle.setheading(POSITION_STACK.pop())
def draw_line_piece(B, y_m): '''Starting from the turtle's current position, find the B vector there and follow it.''' # get real position in meters (x_px, z_px) = tuple(tt.position()) (x_m, z_m) = (float(x_px) / float(PIXELS_PER_M), float(z_px) / float(PIXELS_PER_M)) # get B vector at that position and calculated needed things (Bx, By, Bz) = B(x_m, y_m, z_m) # check for nan for var in [Bx, By, Bz]: if math.isnan(var): print "[draw] Interpolation error at (%s, %s, %s): B = (%s, %s, %s)." % (x_m, y_m, z_m, Bx, By, Bz) angle = math.atan2(Bz, Bx) * (360 / (2 * math.pi)) magnitude = math.sqrt(Bx**2 + Bz**2) color = get_color(magnitude) # set color and thickness tt.pensize(2) tt.pencolor(color) print "[draw] -------" print "[draw] Pixel position: (%s px, %s px)" % (x_px, z_px) print "[draw] Real position: (%s m, %s m)" % (x_m, z_m) print "[draw] (Bx, Bz): (%s, %s)" % (Bx, Bz) print "[draw] Angle: %s degrees" % angle print "[draw] Magnitude: %s mG" % magnitude print "[draw] RGB color: (%s, %s, %s)" % color # draw tt.setheading(angle) tt.pendown() tt.forward(1) tt.penup()
def do_position(self, arg): 'Print the current turle position: POSITION' print('Current position is %d %d\n' % turtle.position())
y = mb['accelerometer']['y'] a = mb['button_a']['down'] b = mb['button_b']['down'] if abs(x) < 10: x = 0 if abs(y) < 10: y = 0 if abs(y) > abs(x): speed -= y/100 else: turtle.right(x) turtle.forward(speed) tx,ty = turtle.position() if tx < -width: angle = turtle.heading() if angle > 90 and angle < 270: turtle.setheading(180 - angle) turtle.setposition(-2*width - tx,ty) elif tx > width: angle = turtle.heading() if angle < 90 or angle > 270: turtle.setheading(180 - angle) turtle.setposition(2*width - tx,ty) if ty < -height: angle = turtle.heading() if angle > 180: turtle.setheading(- angle) turtle.setposition(tx,-2*height - ty)
def draw_art(): window = turtle.Screen() window.bgcolor ("cyan") turtle.position() (0.00,0.00) turtle.home() ##Draw first Rosace (a and b) #Create the turtle a - Draws a circle from squares a = turtle.Turtle() a.shape("circle") a.color("white") a.speed(8) for i in range (1,25): draw_square(a) a.right(15) #change colors a.color("cyan") window.bgcolor ("white") #Create the turtle b b = turtle.Turtle() b.shape("circle") b.color("aquamarine") b.speed(8) for i in range (1,13): draw_circle(b) b.right(30) #change colors back window.bgcolor ("cyan") a.color("white") b.color("fuchsia") ##Second Rosace on the right (d and e) #Create turtle d d = turtle.Turtle() d.shape("circle") d.color("white") d.speed(8) d.goto(240,-250) turtle.distance(d) 240.0 for i in range (1,25): draw_square(d) d.right(15) #Create turtle e e = turtle.Turtle() e.shape("circle") e.color("fuchsia") e.speed(8) e.goto(240,-250) turtle.distance(e) 240.0 for i in range (1,13): draw_circle(e) e.right(30) ##Second Rosace on the right (d and e) #Create turtle d d = turtle.Turtle() d.shape("circle") d.color("white") d.speed(8) d.goto(240,250) turtle.distance(d) 240.0 for i in range (1,25): draw_square(d) d.right(15) #Create turtle e e = turtle.Turtle() e.shape("circle") e.color("fuchsia") e.speed(8) e.goto(240,250) turtle.distance(e) 240.0 for i in range (1,13): draw_circle(e) e.right(30) ##Third Rosace above(f and g) f = turtle.Turtle() f.shape("circle") f.speed(8) f.goto(-240,-250) turtle.distance(f) 240.0 f.color("white") for i in range (1,25): draw_square(f) f.right(15) g = turtle.Turtle() g.shape("circle") g.color("fuchsia") g.speed(8) g.goto(-240,-250) turtle.distance(g) 240.0 for i in range (1,13): draw_circle(g) g.right(30) ##Forth Rosace left(h and i) h = turtle.Turtle() h.shape("circle") h.color("white") h.speed(8) h.goto(-240,250) turtle.distance(h) 240.0 for i in range (1,25): draw_square(h) h.right(15) #Create turtle j j = turtle.Turtle() j.shape("circle") j.color("fuchsia") j.speed(8) j.goto(-240,250) turtle.distance(j) 240.0 for i in range (1,13): draw_circle(j) j.right(30) #change colors window.bgcolor("white") a.color("cyan") b.color("cyan") d.color("cyan") e.color("cyan") f.color("cyan") j.color("cyan") window.exitonclick()