def love(x, y): lv = turtle.Turtle() # 处于复杂图形时,隐藏turtle能明显加快绘制速度 lv.hideturtle() lv.up() # 定位到(x,y) lv.goto(x, y) # 画圆弧 def curve_move(): for i in range(20): lv.right(10) lv.forward(2) lv.color('red', 'pink') lv.speed(6) turtle.delay(1) lv.pensize(1) # 开始画爱心 lv.down() lv.begin_fill() lv.left(140) lv.forward(22) curve_move() lv.left(120) curve_move() lv.forward(22) lv.write("我-你", font=("Arial", 10, "normal"), align="center") # 画完复位 lv.left(140) lv.end_fill()
def make_tower(x,y): turtle.bgcolor("yellow") turtle.color('blue','blue') turtle.shape("circle") turtle.shapesize(0.2,0.2,0) start_time=time.time() start=400 mult=1 step=25 turtle.delay(0.1) turtle.penup() turtle.setpos(0,start) turtle.pendown() turtle.setpos(0,-1*start) turtle.penup() turtle.setpos(-1*mult*start,0) turtle.pendown() turtle.setpos(mult*start,0) i=1 while (i*step<=start): turtle.pendown() turtle.setpos(mult*(start+step*(1-i)),0) turtle.setpos(0,-1*i*step) turtle.setpos(-1*mult*(start+step*(1-i)),0) turtle.setpos(0,i*step) turtle.setpos(mult*(start+step*(1-i)),0) turtle.penup() i+=1 turtle.exitonclick()
def drawtree(root): def height(root): return 1 + max(height(root.left), height(root.right)) if root else -1 def jumpto(x, y): t.penup() t.goto(x, y) t.pendown() def draw(node, x, y, dx): if node: t.goto(x, y) jumpto(x, y - 20) t.write(node.val, align='center', font=('Arial', 12, 'normal')) draw(node.left, x - dx, y - 60, dx / 2) jumpto(x, y - 20) draw(node.right, x + dx, y - 60, dx / 2) import turtle t = turtle.Turtle() t.speed(0) turtle.delay(0) h = height(root) jumpto(0, 30 * h) draw(root, 0, 30 * h, 40 * h) t.hideturtle() turtle.mainloop()
def drunkardsWalk(): turtle.speed(0) turtle.delay(0) turtle.screensize(100, 100) winWidth = turtle.window_width() winHeight = turtle.window_height() steps = 0 yCor = 0 xCor = 0 headingInt = 0 heading = 0 while (xCor <= winWidth and yCor <= winHeight): headingInt = random.randint(1, 4) heading = (headingInt-1) * 90 turtle.setheading(heading) turtle.pendown() turtle.forward(20) steps += 20 xCor = abs(turtle.xcor()) yCor = abs(turtle.ycor()) print(steps) return steps
def Hexagon_of_Hexagons(side=4, length=85, origin=(-300,-200), thickness=5, color="black"): name = "Hexagon of Hexagons "+str(side) # Maximize screen and add a title: screen = turtle.Screen() screen.screensize() screen.setup(width = 1.0, height = 1.0) screen.title(name) turtle.hideturtle() turtle.delay(0) # Draw the triangles: angle = 0 radius = length/sqrt(3.0) delta = (sqrt(3.0)*radius, 3.0*radius/2.0) for h in range(side): for w in range(side+h): center = (origin[0]+delta[0]*w-delta[0]*h/2.0, origin[1]+delta[1]*h) hexagon(center, radius, angle, thickness, color) for w in range(side+h): center = (origin[0]+delta[0]*w-delta[0]*h/2.0, origin[1]+delta[1]*(2*side-h-2)) hexagon(center, radius, angle, thickness, color) # Save the drawing: if SAVE_IMAGES: name = "Boards/"+name turtle.getscreen().getcanvas().postscript(file=name+".ps") name = name.replace(" ", "\ ") conversion = "gs -dSAFER -dBATCH -dQUIET -dNOPAUSE -sDEVICE=pngalpha" conversion += " -dEPSCrop -r600 -sOutputFile="+name+".png "+name+".ps" os.system(conversion) # Close the window: turtle.exitonclick()
def draw_tree(tree): # ve cay def height(r): return 1 + max(height(r.left), height(r.right)) if r else -1 def jump_to(x, y): t.penup() t.goto(x, y) t.pendown() def draw(node, x, y, dx): if node: t.goto(x, y) jump_to(x, y - 20) t.write(node.data, align='center', font=('Arial', 12, 'normal')) draw(node.left, x - dx, y - 60, dx / 2) jump_to(x, y - 20) draw(node.right, x + dx, y - 60, dx / 2) t = turtle.Turtle() t.speed(0) turtle.delay(0) h = height(tree) jump_to(0, 30 * h) draw(tree, 0, 30 * h, 40 * h) t.hideturtle() turtle.mainloop()
def stairway1(x,y): t1=turtle.Turtle() turtle.delay(0.5) sides=11 coord_list=[] coord_list.append(t1.pos()) for i in range(sides-1): t1.forward(15) coord_list.append(t1.pos()) t1.left(360/sides) time.sleep(1) print(coord_list) i=0 n=100 while(i<n): l=0.1+(i/10) for j in range(sides): #t1.right(t1.towards(coord_list[j])) del_x=-t1.pos()[0]+coord_list[j][0] del_y=-t1.pos()[1]+coord_list[j][1] den=math.sqrt(del_x**2+del_y**2) del_x=del_x/den del_y=del_y/den t1.goto(coord_list[j]) t1.goto(coord_list[j][0]+del_x*l,coord_list[j][1]+del_y*l) coord_list[j]=t1.pos() #time.sleep(1) i+=1
def spirographv1(x,y): #R/r should be a fraction like 10/3 for good patterns.If you want pointy ends, w2 should be R/r (10/3 in this case) #If you want end loops, w2 should be greater than previously mentioned value. If you do not want loops, w2 should be less than that value #To increase the speed of the drawing, increase w1 and w2 in same ratio turtle.delay(5) t1=turtle.Turtle("circle") t2=turtle.Turtle("circle") t1.shapesize(0.2,0.2,0) t2.shapesize(0.2,0.2,0) R=[316.67,198.26153,107.15370] r=[53.33,64.73846,26.3762] w1=[1,1,1] w2=[6.8714/2,3.0628*2/2,(4.0625*3+3)/2] cl=["green","blue","black"] tl=[50.26544*2,50.26544*2,31.45] t=[] for i in range(3): t.append(turtle.Turtle("circle")) t[i].shapesize(0.2,0.2,0) t[i].color(cl[i]) t[i].penup() t[i].setpos(R[i],r[i]) if i>0 else t[i].setpos(R[i]+r[i],0) t[i].pendown() start=time.time() el=0 while(el<max(tl)): el=time.time()-start for i in range(3): if(i>0) and el<tl[i]: t[i].setpos(R[i]*math.cos(w1[i]*el)+r[i]*math.sin(w2[i]*el),R[i]*math.sin(w1[i]*el)+r[i]*math.cos(w2[i]*el)) elif i<=0 and el<tl[i]: t[i].setpos(R[i]*math.cos(w1[i]*el)+r[i]*math.cos(w2[i]*el),R[i]*math.sin(w1[i]*el)+r[i]*math.sin(w2[i]*el))
def move(): wn.update() global X, Y, pdx, pdy, score1 turtle.delay(8) ball.setx(X + pdx) ball.sety(Y + pdy) X = ball.xcor() Y = ball.ycor() Xpr1 = pr1.xcor() Ypr1 = pr1.ycor() deltaX1 = abs(Xpr1 - X) deltaY1 = abs(Ypr1 - Y) if deltaX1 < 18 and deltaY1 < 40: if X > -200: score1 += 1 s1.undo() s1.write(score1, font=FONT) pdx = -pdx if X < -290: score1 = score1 - 1 s1.undo() s1.write(score1, font=FONT) pdx = -pdx if X > 290: pdx = -pdx if Y < -290: pdy = -pdy if Y > 290: pdy = -pdy turtle.ontimer(move, 5)
def set_turtle(t): turtle.delay(0) t.speed(10) t.pensize(2) t.pencolor("red") t.fillcolor("blue") t.ht()
def _render(self, bool): self.rendering = bool if bool: loadWindow = turtle.Screen() turtle.speed(0) turtle.delay(0) turtle.hideturtle() turtle.colormode(255) turtle.pencolor((255,255,255)) turtle.setpos(0, 0) turtle.pensize(5) for i in range(0, self.sw): for j in range(0, self.sh): if i in [0, self.sw - 1] or j in [0, self.sh -1]: self.draw(i,j, (0,0,0)) turtle.setup(750, 750) elif self.rendering == True: self.rendering = True for i in range(0, self.sw): for j in range(0, self.sh): if i in [0, self.sw - 1] or j in [0, self.sh -1]: self.draw(i,j, (255,255,255)) for p in self.snake.parts: self.draw(p[0], p[1], (255,255,255)) self.draw(self.food.position[0], self.food.position[1], (255,255,255)) self.rendering = False
def Rectangle_of_Squares(width=8, height=7, length=85, origin=(-300,-100), thickness=8, color="black"): name = "Rectangle of Squares "+str(width)+"x"+str(height) # Maximize screen and add a title: screen = turtle.Screen() screen.screensize() screen.setup(width = 1.0, height = 1.0) screen.title(name) turtle.hideturtle() turtle.delay(0) # Draw the squares: angle = 0 radius = length/sqrt(2.0) delta = (sqrt(2.0)*radius, sqrt(2.0)*radius) for h in range(height): for w in range(width): center = (origin[0]+delta[0]*w, origin[1]-150+delta[1]*h) square(center, radius, angle, thickness, color) # Save the drawing: if SAVE_IMAGES: name = "Boards/"+name turtle.getscreen().getcanvas().postscript(file=name+".ps") name = name.replace(" ", "\ ") conversion = "gs -dSAFER -dBATCH -dQUIET -dNOPAUSE -sDEVICE=pngalpha" conversion += " -dEPSCrop -r600 -sOutputFile="+name+".png "+name+".ps" os.system(conversion) # Close the window: turtle.exitonclick()
def spirographv2(x,y): turtle.delay(5) hypo=turtle.Turtle("circle") epi=turtle.Turtle("circle") hypo.shapesize(0.2,0.2,0) epi.shapesize(0.2,0.2,0) R=100 r=10 w=10 a=10 start=time.time() el=0 epi.penup() hypo.penup() epi.setpos(R-r+a*r,0) hypo.setpos(R+r-a*r,0) epi.pendown() hypo.pendown() while(True): el=time.time()-start el=w*el #hypo.setpos((R-r)*math.cos((r/R*el))+a*r*math.cos((1-(r/R))*el),(R-r)*math.sin((r/R*el))-a*r*math.sin((1-(r/R))*el)) epi.setpos((R+r)*math.cos((r/R*el))-a*r*math.cos((1+(r/R))*el),(R+r)*math.sin((r/R*el))-a*r*math.sin((1+(r/R))*el))
def plot_plain_stars(picture_size, coordinates_dict): ''' Function for drawing a picture based off the given coordinates from the read_coords function. ''' turtle.bgcolor('black') turtle.color('white') turtle.hideturtle() turtle.speed(100) turtle.delay(0) turtle.tracer(0, 0) turtle.update() turtle.screensize(picture_size, picture_size) # Set up for the turtle commands for i in coordinates_dict: turtle.penup() # Picks up pen so the dots are not connected turtle.setx(coordinates_dict[i][0] * (picture_size / 2)) turtle.sety(coordinates_dict[i][1] * (picture_size / 2)) # Sets the coordinates base off the given size turtle.pendown() turtle.begin_fill() turtle.forward(2) turtle.left(90) turtle.forward(2) turtle.left(90) turtle.forward(2) turtle.end_fill()
def print_path(path, pen, maze): turtle.delay(9) if not path: t = turtle.Turtle(visible=False) t.penup() t.color("red") t.write("Caminho não encontrado", align="center", font=("Arial", 30, "bold")) else: # Starting point for drawing p = 650 / len(maze) if len(maze) % 2 == 0: start_pos = (len(maze) / 2) * p else: start_pos = ((len(maze) - 1) / 2) * p # Skip the start and the end path = path[1:-1] pen.color("yellow") for pos in path: y = pos[0] x = pos[1] screen_x = -start_pos + (x * p) screen_y = start_pos - (y * p) pen.goto(screen_x, screen_y) pen.stamp()
def Canvas_init(w=800, h=600, s=5): scr = turtle.Screen() scr.setup(w, h) scr.bgcolor("white") turtle.delay(0) t = turtle.Turtle() t.reset() t.width(1) t.speed(0) t.color("lightgray") t.ht() t.goto(0,0) t.goto(0,-1000) t.goto(0,0) t.goto(1000,0) t.goto(0,0) t.goto(0,1000) t.goto(0,0) t.goto(-1000,0) t.goto(0,0) t.width(4) t.forward(0) t.color("black") return scr, t, s
def flower(): petals = abs( inputInt("How many petals would you like the flower to have? ")) radius = abs( inputInt( "Enter radius of a circle sector (Enter 0 for default radius): ")) angle = abs( inputInt("Enter angle of a circle sector(Enter 0 for default angle): ") % 181) if radius == 0: radius = 100 if angle == 0: angle = 90 t = Turtle() t.speed(100) t.width(2) t.ht() delay(0) stepAngle = 360 / petals for l in range(petals): turtCircle(t, radius, angle) t.left(180 - angle) turtCircle(t, radius, angle) t.right(180 + angle) t.left(stepAngle) 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 spyral(n): import turtle as t t.shape("turtle") t.delay(0) for i in range(100, n): t.forward(i / 1000) t.left(1)
def Chaos_2(sides=3, k=0.5, color="darkblue", origin=(0,0), r=200, points=2000, restricted=False): # Basic turtle setup: turtle.hideturtle() turtle.delay(0) turtle.speed(0) turtle.penup() turtle.color(color) # Generate Polygon: a = 2.0*pi/sides P = [(origin[0] - r*sin(a*i), origin[1] + r*cos(a*i)) for i in range(sides)] for i in range(sides): P.append(((P[i-1][0]+P[i][0])/2.0, (P[i-1][1]+P[i][1])/2.0)) # Draw the polygon vertices: for point in P: turtle.goto(point) turtle.dot() # Draw the rest of the fractal: vertex = P[0] point = P[0] for i in range(points*sides): if restricted: vertex = random.choice([v for v in P if v != vertex]) else: vertex = random.choice(P) point = (k*vertex[0]+(1.0-k)*point[0], k*vertex[1]+(1.0-k)*point[1]) turtle.goto(point) turtle.dot(2,)
def main(edges,gridDelta,magnetDelta,gridInit,magInit,skipMag=itertools.cycle([0])): #3 = hex, 4 = square #main rule # lsystem.SYSTEM_RULES["X"] = "X+X-X-X-X+X+X+X-X" lsystem.SYSTEM_RULES["F"] = "F+F" + "-F"*(edges-1) + "+F"*(edges-1) +"-F" # lsystem.SYSTEM_RULES["F"] = "F+F-F-F+F+F-F" #lsystem.SYSTEM_RULES["U"] = "UHV-X-X+X+X+X-X" axiom = "F" # axiom = "X" iterations=4 model= lsystem.derivation(axiom,iterations) pitch, magH, magW = 35, 15 ,8 # pitch, magH, magW = 100, 40 , 20 # pitch, magH, magW = 20, 12 ,6 turtle.clearscreen() squirtle = lsystem.set_turtle(gridInit)#lsystem.NORTH) # create turtle object turtle_screen = turtle.Screen() # create graphics window turtle_screen.screensize(10000, 10000) turtle.delay(0) # squirtle.ht() # turtle.tracer(0, 0) lsystem.draw_l_system(squirtle, model[-1], pitch, gridDelta,magH,magW,magnetDelta,magInit,skipMag) # draw model return model, turtle_screen
def drawtree(root): def height(root): return 1 + max(height(root.left), height(root.right)) if root else -1 def jumpto(x, y): t.penup() t.goto(x, y) t.pendown() def draw(node, x, y, dx): if node: t.goto(x, y) jumpto(x, y - 20) t.write(node.val, align='center', font=('Arial', 12, 'normal')) draw(node.left, x - dx, y - 60, dx / 2) jumpto(x, y - 20) draw(node.right, x + dx, y - 60, dx / 2) import turtle t = turtle.Turtle() t.speed(0); turtle.delay(0) h = height(root) jumpto(0, 30 * h) draw(root, 0, 30 * h, 40 * h) t.hideturtle() turtle.mainloop() # Uncomment to draw a tree visually # if __name__ == '__main__': # drawtree(deserialize('[1,2,3,null,null,4,null,null,5]')) # drawtree(deserialize('[2,1,3,0,7,9,1,2,null,1,0,null,null,8,8,null,null,null,null,7]'))
def spiral_draw(a=3, b=5, delta=pi / 2, base_length=100, origin=(0, 0), step=0.005): half_length = base_length / 2.0 turtle.hideturtle() turtle.delay(0) turtle.speed(0) turtle.penup() x = origin[0] y = origin[1] + half_length * sin(delta) turtle.goto((x, y)) turtle.pendown() for t in range(1, int(ceil(2 * pi / step)) + 1): x = origin[0] + half_length * sin(a * t * step) y = origin[1] + half_length * sin(b * t * step + delta) turtle.goto((x, y))
def __init__(self, size=8): self.size = size self.scr = turtle.Screen() self.scr.title("Train tracks") self.turtle = turtle.Turtle() turtle.mode("standard") turtle.screensize(1000, 1000) self.screen_size = 1000 self.cell_size = self.screen_size / (size + 1) turtle.setworldcoordinates(0, 0, self.screen_size, self.screen_size) self.turtle.hideturtle() self.turtle.speed("fast") turtle.delay(0) turtle.tracer(0, 0) self.turtle.penup() self.layout = [] for row in range(size): col_list = [] for col in range(size): col_list.append(Cell(row, col, self.cell_size)) self.layout.append(col_list) self.start = 0 self.end = 0 self.move_count = 0 self.move_max = 1000000 self.col_count = [] self.row_count = [] self.col_perm = [] self.row_perm = []
def chooseSettings(): #Get user input to determine to settings. global mapwidth, tilesize, generator #Ask the user which generator they want to use. gen = turtle.numinput('DigiMapGen', 'Input a generator number:', 1, minval=0, maxval=gencount) #Make sure the user put in a real generator. if gen in range(gencount + 1): generator = gen else: logger.warn('ERROR: Invalid generator.') chooseSettings() #Ask the user how many tiles across they want the map to be. mapwidth = int(turtle.numinput('DigiMapGen', 'Set map width:', 50)) #Get animation delay from user. delay = turtle.numinput('DigiMapGen', 'Set animation delay:', 0) if delay <= 0: turtle.tracer(False) turtle.delay(delay) turtle.speed(0) else: turtle.delay(delay) #Get the window size from the config. if conf.windowsize / 100 > 1: winsize = 1 else: winsize = conf.windowsize / 100 getMonitorDimensions() turtle.setup(monitorheight * winsize, monitorheight * winsize) newTileSize(mapwidth)
def initialize_plotter(width, height, min_x, max_x, min_y, max_y): """ Initializes the plotter with a window with dimensions width x height, the x-axis ranging from min_x to max_x, and the y-axis ranging from min_y to max_y. Establishes the global beginning and ending x values for the plot and the global x_increment value. Draws the x- and y-axes. """ # Global variables that the plot function must access global x_begin, x_end, x_increment #turtle.tracer(1, 0) # Speed up rendering turtle.delay(0) # Speed up rendering # Establish global x and y ranges x_begin, x_end = min_x, max_x # Set up window size, in pixels turtle.setup(width=width, height=height) # Set up screen size, in pixels turtle.screensize(width, height) turtle.setworldcoordinates(min_x, min_y, max_x, max_y) # x-axis distance that corresponds to one pixel in window distance x_increment = (max_x - min_x) / width turtle.hideturtle() # Draw x axis turtle.pencolor('black') turtle.penup() turtle.setposition(min_x, 0) turtle.setheading(0) turtle.pendown() turtle.forward(max_x - min_x) # Draw a line left to right # Draw y axis turtle.penup() turtle.setposition(0, min_y) turtle.setheading(90) turtle.pendown() turtle.forward(max_y - min_y)
def draw_tree(tree): # ve cay def height(r): return 1 + max(height(r.left), height(r.right)) if r else -1 def jump_to(x, y): t.penup() t.goto(x, y) t.pendown() def draw(node_tree, x, y, dx): if node_tree: view_node = str(node_tree.node.name) \ # + ": " + str(node_tree.node.middleX) \ # + "\n (" + str(node_tree.number_point) + ")" + "\n" t.goto(x, y) jump_to(x, y - 20) t.write(view_node, align='center', font=('Arial', 12, 'normal')) draw(node_tree.left, x - dx, y - 60, dx / 2) jump_to(x, y - 20) draw(node_tree.right, x + dx, y - 60, dx / 2) t = turtle.Turtle() t.speed(0) turtle.delay(0) h = height(tree) jump_to(0, 30 * h) draw(tree, 0, 30 * h, 40 * h) t.hideturtle() turtle.mainloop()
def orbit(): import turtle import math t1 = turtle.Turtle() turtle.speed(0) turtle.delay(0) turtle.dot(80, 'yellow') turtle.color('green') turtle.shape('circle') turtle.penup() turtle.goto(150, 0) turtle.left(90) t1.shape('circle') t1.color('blue') t1.penup() t1.goto(230, 0) x = 0 y = 0 z = 0 while y < 378: t1.goto(150 * math.cos(x), 150 * math.sin(x)) turtle.goto(t1.xcor() + 80 * math.cos(z), t1.ycor() + 80 * math.sin(z)) x = x + 0.05 z = z + 0.2 y = y + 1
def cleanup(): screen.clearscreen() screen.onkeypress(press, "space") screen.onkeypress(cleanup, "a") turtle.delay(0) global t t = Turtle()
def draw_tree(self, node=None) -> None: """ This function can use turtle to draw a binary tree """ def height(head): return 1 + max(height(head.left), height( head.right)) if head else -1 def jump_to(x, y): t.penup() t.goto(x, y) t.pendown() def draw(node, x, y, dx): if node: t.goto(x, y) jump_to(x, y - 20) t.write(node.value, align="center") draw(node.left, x - dx, y - 60, dx / 2) jump_to(x, y - 20) draw(node.right, x + dx, y - 60, dx / 2) node = node if node else self.root t = turtle.Turtle() t.speed(0) turtle.delay(0) h = height(node) jump_to(0, 30 * h) draw(node, 0, 30 * h, 10 * h) t.hideturtle() turtle.mainloop()
def ejes(): #################################### # Ejes Coordenados # # los ejes x e y van de -150 a 150 # #################################### turtle.delay(0) turtle.ht() turtle.speed(0) turtle.pencolor('red') turtle.down() turtle.fd(301) turtle.rt(90) turtle.fd(1) turtle.rt(90) turtle.fd(300) turtle.lt(90) turtle.fd(300) turtle.rt(90) turtle.fd(1) turtle.rt(90) turtle.fd(300) turtle.lt(90) turtle.fd(300) turtle.rt(90) turtle.fd(1) turtle.rt(90) turtle.fd(300) turtle.lt(90) turtle.fd(300) turtle.rt(90) turtle.fd(1) turtle.rt(90) turtle.fd(300) turtle.up() turtle.pencolor('blue')
def main(): # Initial params for drawing turtle.resizemode("auto") turtle.delay(0) wn = turtle.Screen() wn.bgcolor("black") wn.title("Maze") wn.setup(800, 800) regex = re.compile(r'\d+') # maze_name = wn.textinput("", "Arquivo de labirinto:") maze_num = wn.numinput("", "Numero de labirinto:") alg_name = wn.textinput( "", "Algoritmo: \nbusca_largura, busca_profundidade,\nbusca_best_first ou busca_Aestrela" ) # path_name = wn.textinput("", "Arquivo de Solução:") path_name = alg_name + "/caminho" + str(int(maze_num)) dimensions, maze = read_maze(maze_num) # Retrieve the path from the file with open("caminhos/" + path_name + ".txt") as f: path = f.readline() path = literal_eval(path) square_size = 650 / len(maze) pen = Pen(square_size) penpath = PenPath(square_size) setup_maze(maze, pen) print_path(path, penpath, maze) wn.tracer(0) turtle.mainloop()
def flower(): flower_turtle = Turtle() flower_turtle.speed(0) flower_turtle.width(2) delay(0) petals = 3 radius = 100 angle = 90 """ # This function can also draw as many petals as you want petals = abs(inputInt("How many petals would you like the flower to have? ")) radius = abs(inputInt("Enter radius of a circle sector (Enter 0 for default radius): ")) angle = abs(inputInt("Enter angle of a circle sector(Enter 0 for default angle): ") % 181) if radius == 0: radius = 100 if angle == 0: angle = 90 """ stepAngle = 360 / petals for l in range(petals): turtCircle(flower_turtle, radius, angle) flower_turtle.left(180 - angle) turtCircle(flower_turtle, radius, angle) flower_turtle.right(180 + angle) flower_turtle.left(stepAngle) flower_turtle.width(3) flower_turtle.left(230) turtCircle(flower_turtle, 4 * radius, 50)
def spirograph(): turtle.delay(0) turtle.pensize(3) at(0, -200) for iteration in range(1, 100): color(iteration) turtle.circle(400, 80) turtle.circle(50, 175)
def drawpoint(point,color): p=turtle.getturtle() p.hideturtle() turtle.delay(1) for i in point: p.pu() p.color(color) p.goto(i) p.pd() p.dot()
def drawRouter(identification, xLoc, yLoc): turtle.hideturtle() turtle.delay(0) turtle.up() turtle.setposition(xLoc, yLoc - 25) turtle.down() turtle.circle(25) turtle.up() turtle.setposition(xLoc - 10, yLoc) write(identification, font=('Arial', 12, 'normal')) turtle.setposition(xLoc, yLoc) turtle.down()
def pintar(x, y): ################################## # Función para Encender un Pixel # ################################## turtle.delay(0) turtle.speed(0) turtle.ht() turtle.up() turtle.goto(2 * int(x), 2 * int(y)) turtle.down() turtle.fd(0) turtle.up()
def _init(): root = Tk() menubar = Menu(root) menubar.add_command(label="Save", command=save_image) menubar.add_command(label="Clear", command=_clear) root.config(menu=menubar) turtle.speed(0) turtle.delay(0) turtle.setworldcoordinates(-xCoor,-yCoor,xCoor,yCoor) turtle.up() turtle.setpos(0,0) turtle.down()
def runSimulation(path, destination): turtle.up() turtle.delay(0) turtle.setposition(path[0].xloc, path[0].yloc) for node in path: turtle.pencolor("red") turtle.color("green", "orange") turtle.delay(100) turtle.showturtle() turtle.down() turtle.setposition(node.xloc, node.yloc) drawRouter(node.label, node.xloc, node.yloc) turtle.up() turtle.down()
def buildNetwork(graph): for node in graph: drawRouter(node.label, node.xloc, node.yloc) for i in range(len(node.neighbors)): turtle.up() turtle.delay(0) turtle.setposition(node.xloc, node.yloc) turtle.setposition(node.xloc + (node.neighbors[i].xloc - node.xloc) / 2, node.yloc + (node.neighbors[i].yloc - node.yloc) / 2) write(node.distances[i], font=('Arial', 12, 'normal')) turtle.setposition(node.xloc, node.yloc) turtle.down() turtle.setposition(node.neighbors[i].xloc, node.neighbors[i].yloc) turtle.up() turtle.setposition(node.xloc, node.yloc)
def Canvas_init(): scr = turtle.Screen() scr.setup(800,600) scr.bgcolor("white") turtle.delay(0) t = turtle.Turtle() t.reset() t.width(2) t.ht() t.setx(0) t.sety(0) return scr, t
def drawLeaveEnter(list, title): number = 600 if len(list) > number: tempList = [] step = int(len(list) / number) for i in range(1, number): tmp = list[(i - 1) * step : i * step] tempList.append(sum(tmp) / len(tmp)) list = tempList length = 400 / len(list) maximum = 600 / max(list) t = turtle.Turtle() turtle.delay(0) t.speed(0) t.hideturtle() t.pensize(4) t.pu() t.goto(-300, -200) t.pd() t.fd(600) t.pu() t.goto(-300, -200) t.pd() t.goto(-300, +200) t.pu() t.pensize(2) t.pencolor('black') t.goto(-280, +195) t.write("%s: [%d:%d]" % (title, len(list), max(list)), align='left', font=('Times New Roman', 16)) t.goto(-300, -200) t.pencolor('red') t.pd() num = 0 for i in list: t.goto(i * maximum - 300, num * length - 200) num += 1 t.goto(i * maximum - 300, num * length - 200) # t.write(str((i, [i])), align='left', font=('Times New Roman', 10)) turtle.done()
def make_curve(start_pos, gridsize, prog, iters, heading=-90): global size gridsize = (gridsize + 1) ** iters - 1 len = int(size / gridsize) wlen = 2 ** (1 / 2) * len if len < 2: # raise ValueError('Grid is too small') len = 2 size = len * gridsize posx, posy = start_pos turtle.hideturtle() turtle.speed(0) turtle.delay(0) turtle.setup(size + 20, size + 20, 0, None) turtle.penup() turtle.setpos(posx * size / 2, posy * size / 2) turtle.setheading(heading) turtle.pendown() cmds = { "f": lambda p, i: turtle.forward(len), "+": lambda p, i: turtle.left(90), "-": lambda p, i: turtle.right(90), "l": lambda p, i: turtle.left(45), "r": lambda p, i: turtle.right(45), "w": lambda p, i: turtle.forward(wlen), "A": lambda p, i: exec(p, i - 1), "B": lambda p, i: exec(inverse(p), i - 1), } def exec(p, i): if i > 0: for cmd in p: cmds[cmd](p, i) turtle.tracer(0) turtle.tracer(iters * 2) exec(prog, iters) turtle.update() turtle.exitonclick()
def affichage(sudoku): turtle.speed(0) turtle.delay(1) cpt = 0 for y in range(-5,5): if cpt%3 == 0 : turtle.pensize(2) else: turtle.pensize(1) cpt += 1 turtle.up() turtle.goto(-180,(y*40)+20) turtle.down() turtle.goto(180,(y*40)+20) turtle.up() cpt = 0 for x in range(-5,5): if cpt%3 == 0 : turtle.pensize(2) else: turtle.pensize(1) cpt += 1 turtle.up() turtle.goto((x*40)+20,-180) turtle.down() turtle.goto((x*40)+20,180) turtle.up() y = 4 for l in range(0,9): x = -4 for c in range(0,9): turtle.up() turtle.goto(x*40,(y*40)-10) if sudoku[l][c] != 0: turtle.write(sudoku[l][c], True, align="center", font=("Arial", 16, "normal")) x += 1 y -= 1
import turtle import math endVal = 10000 # max value to draw to turtle.speed(0) # fastest=0, slowest=10, init=3 turtle.hideturtle() # speeds it up turtle.delay(0) # time between updates in ms # some constants goldenRatio = 1.618033988 goldenAngle = (math.pi * 2) / (goldenRatio**2) log2 = math.log(2) def point(x,y,c='blue'): turtle.penup() turtle.setpos(x,y) turtle.color(c) turtle.dot(4) def isPrime(n): if n % 1 or n < 2: return False if n == leastFactor(n): return True; return False; def leastFactor(n): if n == 0: return 0 if n % 1 or n * n < 2: return 1 if n % 2 == 0: return 2
from colorsys import hsv_to_rgb #"Import" calls for the library called turtle and hsv_to_rgb so that certain sections of code can be used in this code. wn = turtle.Screen() #.Screen() initialises the screen and opens the window for use. kermanNW = turtle.Turtle() kermanNE = turtle.Turtle() kermanSE = turtle.Turtle() kermanSW = turtle.Turtle() #The above 4 lines of code create four turtles which are labelled for each corner they cover (NESW). kermansquare= turtle.Turtle() #The above turtle will be used to set the background colour later. turtle.delay(0) #This line speeds up the drawing speed in the code. def bgdraw(): #This function draws the square that will be used to set the background black. kermansquare.speed(0) kermansquare.goto(-1000,-1000) kermansquare.begin_fill() kermansquare.goto(1000,-1000) kermansquare.goto(1000,1000) kermansquare.goto(-1000,1000) kermansquare.goto(-1000,-1000) kermansquare.end_fill() bgdraw() #This runs the function. def hue2rgb(hue, saturation=1, value=0.8, rgb_scale = 1): #This function is required in order to make the colour work. Was provided by Dr McIver.
def docking(): cr = turtle.Turtle() cr.hideturtle() cr.color('gray') cr.speed(0) cr.penup() cr.setpos(0,250) cr.seth(270) cr.pendown() cr.forward(500) cr.penup() cr.setpos(450,0) cr.seth(180) cr.pendown() cr.forward(900) def left(): global cenx global x x = x-10 cenx = cenx-10 def right(): global cenx global x x = x+10 cenx = cenx+10 def up(): global y global ceny y = y+10 ceny = ceny+10 def down(): global y global ceny y = y-10 ceny = ceny-10 for i in range(100): global r global x global cens ma.setx(cenx) ma.sety(ceny) al.setx(x) al.sety(y) al.pendown() al.seth(90) al.clear() ma.clear() al.circle(r) ma.dot(cens, 'white') al.penup() r = r+1 x = x+1 if cens <= 10: cens+0.5 turtle.onkey(left, 'Left') turtle.onkey(right, 'Right') turtle.onkey(up, 'Up') turtle.onkey(down, 'Down') turtle.listen() turtle.delay(50)
def drawProbs(list, lastTick, title): my = 0 for i in list: if i[-1] > my: my = i[-1] if my == 0: print("empty probe") return number = 3 * 600 if len(list) > number: tempList = [] step = int(len(list) / number) for i in range(1, number): tmpLst = list[(i - 1) * step : i * step] elem = [0, 0] for i in tmpLst: elem[0] += i[0] if elem[1] < i[1]: elem[1] = i[1] if my < i[1]: my = i[1] elem[0] /= len(tmpLst) * step * 3 tempList.append(elem) lastTick = number list = tempList length = 400 / my maximum = 600 / lastTick t = turtle.Turtle() turtle.delay(0) t.speed(0) t.hideturtle() t.pensize(4) t.pu() t.goto(-300, -200) t.pd() t.fd(600) t.pu() t.goto(-300, -200) t.pd() t.goto(-300, +200) t.pu() t.pensize(2) t.pencolor('black') t.goto(-280, +195) t.write("%s: [%d:%d]" % (title, my, lastTick), align='left', font=('Times New Roman', 16)) t.goto(-300, -200) t.pencolor('red') t.pd() for i in list: t.goto(i[0] * maximum - 300, i[1] * length - 200) # t.write(str((i, [i])), align='left', font=('Times New Roman', 10)) turtle.done()
def initTurtle(self): self.t = turtle.Turtle() turtle.delay(0) self.t.speed(0) self.t.hideturtle() self.t.pu()
def spiral(size): turtle.pensize(1) turtle.delay(20) turtle.circle(size, 90) spiral(size * 1.1)
def hearts(): turtle.delay(0) for iteration in range(1, 50): color(iteration) at(0, iteration * -5) heart(iteration * 10, 45)
def solve(self,num): self.t1.n=[]; self.t2.n=[]; self.t3.n=[]; self.t1.top=0; self.t2.top=0; self.t3.top=0; turtle.reset() turtle.write("TOWER OF HANOI",True,"center",("Arial",40,"normal")) drawtower() self.createtower(num) #print(self.t1.n[0],self.t1.n[1],self.t1.n[2]) drawstack(self.t1,self.t2,self.t3) s=input("enter n") if s=='n': if num%2==0: while self.check(num): chk=0 s=input("enter n") if s=='n': if self.t1.is_empty(): self.move('b','a') else: chk=self.move('a','b') if chk: self.move('b','a') turtle.reset() turtle.write("TOWER OF HANOI",True,"center",("Arial",40,"normal")) drawtower() drawstack(self.t1,self.t2,self.t3) turtle.tracer(1) turtle.delay(5) turtle.tracer(3) chk=0 s=input("enter n") if s=='n': if self.t2.is_empty(): self.move('c','a') else: chk=self.move('a','c') if chk: self.move('c','a') turtle.reset() turtle.write("TOWER OF HANOI",True,"center",("Arial",40,"normal")) drawtower() drawstack(self.t1,self.t2,self.t3) turtle.tracer(1) turtle.delay(5) turtle.tracer(3) chk=0 s=input("enter n") if s=='n': if self.t2.is_empty(): self.move('c','b') else: chk=self.move('b','c') if chk: self.move('c','b') turtle.reset() turtle.write("TOWER OF HANOI",True,"center",("Arial",40,"normal")) drawtower() drawstack(self.t1,self.t2,self.t3) turtle.tracer(1) turtle.delay(5) turtle.tracer(3) else: while self.check(num): chk=0 s=input("enter n") if s=='n': if self.t1.is_empty(): self.move('c','a') else: chk=self.move('a','c') if chk: self.move('c','a') turtle.reset() turtle.write("TOWER OF HANOI",True,"center",("Arial",40,"normal")) drawtower() drawstack(self.t1,self.t2,self.t3) turtle.tracer(0) turtle.delay(5) turtle.tracer(3) chk=0 s=input("enter n") if s=='n': #flag=0 if self.t1.is_empty(): self.move('b','a') else: chk=self.move('a','b') if chk: self.move('b','a') turtle.reset() turtle.write("TOWER OF HANOI",True,"center",("Arial",40,"normal")) drawtower() drawstack(self.t1,self.t2,self.t3) turtle.tracer(0) turtle.delay(5) turtle.tracer(3) chk=0 s=input("enter n:") if s=='n': if self.t3.is_empty(): self.move('b','c') else: chk=self.move('c','b') if chk: self.move('b','c') turtle.reset() turtle.write("TOWER OF HANOI",True,"center",("Arial",40,"normal")) drawtower() drawstack(self.t1,self.t2,self.t3) turtle.tracer(0) turtle.delay(5) turtle.tracer(3)
LINE_LENGTH = 1 DELAY_MS = 0 REPEAT_TIMES = 16 def str_to_heading(str_): if str_ == 'up': return 90 elif str_ == 'left': return 180 elif str_ == 'right': return 0 elif str_ == 'down': return 270 else: raise Exception('Unknown heading {}'.format(str_)) turtle.hideturtle() turtle.speed(0) turtle.delay(DELAY_MS) dragon_iterator = iter(dragon_fractal()) for _ in range(2 ** REPEAT_TIMES): step_direction = next(dragon_iterator) turtle.setheading(str_to_heading(step_direction)) turtle.forward(LINE_LENGTH) turtle.done()
tess = turtle.Turtle() tess.shape("turtle") tess.color("blue") wn.textinput("NIM", "Name of first player:") tid_i_sekunder = wn.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000) tid_i_sekunder = int(tid_i_sekunder) tess.penup() # This is new tess.pendown() print(turtle.turtles()) #turtle.screensize(canvwidth=None, canvheight=None, bg=None) size = 1 turtle.colormode(255) for i in range(tid_i_sekunder): print(i) turtle.delay(100) tess.stamp() # Leave an impression on the canvas tess.pencolor(random.randint(0,255), 160, 80) size = size + 3 # Increase the size on every iteration tess.forward(size) # Move tess along tess.right(24) # ... and turn her tess.shapesize(i*0.1+1,i*0.1+1) tess.color(random.randint(0,255),random.randint(0,255),random.randint(0,255)) #winsound.PlaySound("SystemExit", winsound.SND_ALIAS) #winsound.PlaySound("*", winsound.SND_ALIAS) winsound.PlaySound("Bass_and_asdf.wav", winsound.SND_ALIAS) turtle.turtles() tess.clear() wn.mainloop()
def hangMinGame(): ''' The algorithm of the Game. ''' alphabetList=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',\ 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] correctLetterList=[] incorrectLetterList=[] turtle.screensize(640,480) turtle.title('HangMan Game') man=Man() alphabet=Alphabet(size=15,interval=4) drawAlphabet(alphabet) name=randomName(allNameList) nameList=list(name.replace(' ','')) guessList=initGuess(name) drawGuess(alphabet,''.join(guessList)) errorTime=0 while errorTime<6 and len(correctLetterList)<len(set(nameList)): inputLetter=turtle.textinput("Guess a letter","Guess a letter") if inputLetter in alphabetList: inputLetter=inputLetter.upper()[0] alphabet.draw(inputLetter, color="red") if (inputLetter not in nameList): if (inputLetter not in incorrectLetterList): errorTime=errorTime+1 man.draw(errorTime) incorrectLetterList.append(inputLetter) else: if inputLetter not in correctLetterList: guessList=updateGuess(name,inputLetter,guessList) drawGuess(alphabet,''.join(guessList)) correctLetterList.append(inputLetter) if errorTime<6: alphabet.drawTitle("Congratulations!", center=Point2D(0,150), color="green") else: alphabet.drawTitle("You lost! The answer was:", center=Point2D(0,150), color="red") alphabet.drawTitle(name, center=Point2D(0,120), color="red") turtle.delay(5000) turtle.up() turtle.bye()