def drawWith(self, turtle): self.height = turtle.getscreen().window_height() self.width = turtle.getscreen().window_width() for drawableObject in self.drawableObjects: drawableObject.draw(turtle) turtle.getscreen().update()
def graficarFigura(): t=turtle.Pen() angulo = (180/lados)+180 t.pencolor("red") for x in range(0,lados): t.forward(250) t.right(angulo) turtle.getscreen()._root.mainloop()
def draw_square(x,y): turtle.penup() turtle.goto(x,y) turtle.pendown() turtle.goto(x+50,y) turtle.goto(x+50,y+50) turtle.goto(x,y+50) turtle.goto(x,y) turtle.getscreen().onkeypress(draw_square, "s") turtle.getscreen().listen()
import turtle anms = turtle.Turtle() turtle.getscreen().bgcolor("black") anms.shape("turtle") anms.speed(100) anms.color("white", "white") # for i in range(5): # anms.forward(50) # anms.left(216) def star(turtle, size): if size <= 10: return else: turtle.begin_fill() for i in range(5): turtle.forward(size) star(turtle, size / 3) turtle.left(216) turtle.end_fill() star(anms, 360) turtle.mainloop()
def funcion(numero, diametro): t=turtle.Pen() angulo=360/numero for x in range (1,numero+1): t.forward(diametro) t.left(angulo) turtle.getscreen()._root.mainloop()
def drawcurve(points): myTurtle = turtle.Turtle(shape="turtle") turtle.screensize(500,500) turtle.setworldcoordinates(400,400,500,500) myTurtle.penup() y = points[0] myTurtle.setposition(y[0], y[1]) myTurtle.pendown() for x in points: myTurtle.setposition(x[0], x[1]) turtle.getscreen()._root.mainloop()
def main(): turtle.colormode(1.) turtle.speed(0) for depth in range(9): if 7 > depth > 4: # for faster rendering. turtle.getscreen().tracer(0) global count count = 0 hilbert(0.0, 0.0, 1.0, 0.0, 0.0, 1.0, depth) turtle.getscreen().tracer(1) #time.sleep(2) turtle.Screen().exitonclick()
def draw(x,y,count,isGrant,val): tlist = list() p = list() screen = turtle.getscreen() screen.setup( width = 2000, height = 2000, startx = None, starty = None) for i in range(count): screen.tracer(10) tlist.append(turtle.Turtle()) tlist[i].color("red") tlist[i].speed(1) tlist[i].width(4) angle = math.atan((y[i]-x[i])/300.0) p.append(math.sqrt(90000+(x[i]-y[i])*(x[i]-y[i]))) tlist[i].up() if val == 200: tlist[i].back(val-275) else: tlist[i].back(val) tlist[i].left(90) tlist[i].forward(200-x[i]) if isGrant == 1: tlist[i].right(180-math.degrees(angle)+90) else: tlist[i].right(math.degrees(angle)+90) screen.update() for i in xrange(100): j=0 for t in tlist: t.down() if (i*(i+1))/2 < p[j]: t.forward(i) j=j+1 screen.update()
def initialize_plot(self, positions): self.positions = positions self.minX = minX = min(x for x,y in positions.values()) maxX = max(x for x,y in positions.values()) minY = min(y for x,y in positions.values()) self.maxY = maxY = max(y for x,y in positions.values()) ts = turtle.getscreen() if ts.window_width > ts.window_height: max_size = ts.window_height() else: max_size = ts.window_width() self.width, self.height = max_size, max_size turtle.setworldcoordinates(minX-5,minY-5,maxX+5,maxY+5) turtle.setup(width=self.width, height=self.height) turtle.speed("fastest") # important! turtle is intolerably slow otherwise turtle.tracer(False) # This too: rendering the 'turtle' wastes time turtle.hideturtle() turtle.penup() self.colors = ["#d9684c","#3d658e","#b5c810","#ffb160","#bd42b3","#0eab6c","#1228da","#60f2b7" ] for color in self.colors: s = turtle.Shape("compound") poly1 = ((0,0),(self.cell_size,0),(self.cell_size,-self.cell_size),(0,-self.cell_size)) s.addcomponent(poly1, color, "#000000") turtle.register_shape(color, s) s = turtle.Shape("compound") poly1 = ((0,0),(self.cell_size,0),(self.cell_size,-self.cell_size),(0,-self.cell_size)) s.addcomponent(poly1, "#000000", "#000000") turtle.register_shape("uncolored", s)
def main(): file_name = "go" file_name = raw_input( 'Enter a file name or exit to quit program: ') while (file_name != "exit" and file_name != "Exit" and file_name != "quit" and file_name != "Quit"): f = open( file_name, 'r' ) first_line = f.readline() first_line = first_line.split() distance = float( first_line[0] ) angle = float( first_line[1] ) stack = [] wn = tur.Screen() for line in f: wn.clear() tur.penup() tur.seth(90) tur.setx(0) tur.sety(-200) tur.pendown() interprit_line(tur, line, angle, distance, stack) ts = tur.getscreen() ts.getcanvas().postscript(file=file_name +".eps") wn.exitonclick() file_name = raw_input( 'Enter a file name or exit to quit program: ')
def d(fill=False): '''draws a capital D''' turtle.setheading(0) if fill: bf() fd(20) circle(20, 90) fd(70) circle(20, 90) fd(20) lt(90) fd(110) lt(90) if fill: ef() pu() turtle.goto(turtle.xcor() + 10, turtle.ycor() + 10) pd() cfc = fc() fc(turtle.getscreen().bgcolor()) bf() fd(10) circle(10, 90) fd(70) circle(10, 90) fd(10) lt(90) fd(90) ef() lt(90) pu() turtle.goto(turtle.xcor() + 40, turtle.ycor() - 10) pd() fc(cfc)
def a(fill=False): '''draws a capital A.''' turtle.setheading(0) if fill: bf() fd(10) turtle.goto(turtle.xcor() + 5, turtle.ycor() + 40) fd(10) turtle.goto(turtle.xcor() + 5, turtle.ycor() - 40) fd(10) turtle.goto(turtle.xcor() - 15, turtle.ycor() + 110) turtle.setx(turtle.xcor() - 10) turtle.goto(turtle.xcor() - 15, turtle.ycor() - 110) if fill: ef() pu() turtle.goto(turtle.xcor() + 17, turtle.ycor() + 50) pd() if fill: cfc = fc() fc(turtle.getscreen().bgcolor()) bf() fd(6) turtle.goto(turtle.xcor() - 3, turtle.ycor() + 40) turtle.goto(turtle.xcor() - 3, turtle.ycor() - 40) if fill: ef() fc(cfc) pu() turtle.goto(turtle.xcor() + 33, turtle.ycor() - 50) pd()
def saveImg(): print("Done.") save = input("Would you like to save this tree? Y/N \n") if save.upper() == "Y": t.hideturtle() name = input("What would you like to name it? \n") nameSav = name + ".svg" ts = turtle.getscreen().getcanvas() canvasvg.saveall(nameSav, ts) elif save.upper() == "N": def runChk(): runAgain = input("Would you like to run again? Y/N (N will exit)") if runAgain.upper() == "Y": print("Running") main() elif runAgain.upper() == "N": print("Exiting...") exit() else: print("Invalid response.") runChk() runChk() else: print("Invalid response.") saveImg()
def draw(x,y,count,isGrant,val,acceptCount): List_Of_Turtles = list() p = list() screen = turtle.getscreen() screen.setup( width = 2000, height = 2000, startx = None, starty = None) for i in range(count): screen.tracer(10) List_Of_Turtles.append(turtle.Turtle()) #print "here",i,acceptCount,count List_Of_Turtles[i].color("red") if i >= acceptCount-1 and acceptCount!= 0: List_Of_Turtles[i].shape("square") List_Of_Turtles[i].color("green") List_Of_Turtles[i].speed(1) List_Of_Turtles[i].width(4) angle = math.atan((y[i]-x[i])/300.0) p.append(math.sqrt(90000+(x[i]-y[i])*(x[i]-y[i]))) if val == 200: Position_Set(List_Of_Turtles[i],val-275,200-x[i]) else: Position_Set(List_Of_Turtles[i],val,200-x[i]) if isGrant == 1: List_Of_Turtles[i].right(180-math.degrees(angle)+90) else: List_Of_Turtles[i].right(math.degrees(angle)+90) screen.update() for i in xrange(100): j=0 for t in List_Of_Turtles: t.down() if (i*(i+1))/2 < p[j]: t.forward(i) j=j+1 screen.update()
def drawcicle(noOfInterface,val): tlist = list() screen = turtle.getscreen() screen.tracer(0) for i in range(noOfInterface): tlist.append(turtle.Turtle()) tlist[i].up() tlist[i].back(val) tlist[i].left(90) tlist[i].forward(200-(10+90*i)) tlist[i].begin_fill() tlist[i].down() tlist[i].circle(15) tlist[i].end_fill() tlist[i].hideturtle() for i in range(noOfInterface): turt = turtle.Turtle() turt.up() turt.back(val-300) turt.left(90) turt.forward(200-(10+90*i)) turt.begin_fill() turt.down() turt.circle(15) turt.end_fill() turt.hideturtle() screen.update()
def viewer(dna): '''Display ORFs and GC content for dna.''' dna = dna.upper() # make everything upper case, just in case t = turtle.Turtle() turtle.setup(1440, 240) # make a long, thin window turtle.screensize(len(dna) * 6, 200) # make the canvas big enough to hold the sequence # scale coordinate system so one character fits at each point setworldcoordinates(turtle.getscreen(), 0, 0, len(dna), 6) turtle.hideturtle() t.speed(0) t.tracer(100) t.hideturtle() # Draw the sequence across the bottom of the window. t.up() for i in range(len(dna)): t.goto(i, 0) t.write(dna[i],font=("Helvetica",8,"normal")) # Draw bars for ORFs in forward reading frames 0, 1, 2. # Draw the bar for reading frame i at y = i + 1. t.width(5) # width of the pen for each bar for i in range(3): orf(dna, i, t) t.width(1) # reset the pen width gcFreq(dna, 20, t) # plot GC content over windows of size 20 turtle.exitonclick()
def Paint_Text(text,back,up): screen = turtle.getscreen() Temp_Turtle = turtle.Turtle() screen.tracer(0) Position_Set(Temp_Turtle,back,up) Temp_Turtle.write(text,font=("Arial", 20, "normal")) Temp_Turtle.hideturtle() screen.update()
def draw_sequence(n, speed): window = turtle.Screen() window.bgcolor('white') window.screensize(n**1.2, n**1.2) alpha = turtle.Turtle() alpha.shape('classic') alpha.color('black') alpha.speed(speed) draw_square(alpha, fib(n)) # draw_circle(alpha, fib(n)) #turtle.getscreen().getcanvas().postscript(file='screen.eps') turtle.getscreen().getcanvas().postscript(file='screen.eps') window.exitonclick()
def drawText(text,back,up): screen = turtle.getscreen() turt = turtle.Turtle() screen.tracer(0) setPos(turt,back,up) turt.write(text,font=("Arial", 20, "normal")) turt.hideturtle() screen.update()
def drawImage(paths): myTurtle = turtle.Turtle(shape="turtle") turtle.screensize(2000,2000) myTurtle.pendown() myTurtle.penup() myTurtle.setposition(0, 0) y = 0 for path in paths: myTurtle.penup() temp = path[0] myTurtle.setposition(temp[0], temp[1]) myTurtle.pendown() y = 1 for x in paths: for y in x: myTurtle.setposition(y[0], y[1]) myTurtle.penup() turtle.getscreen()._root.mainloop()
def draw_snowflake(sentiment): from Tkinter import * import turtle import random sentiment +=1 # Create the turtles a = turtle.Turtle() b = turtle.Turtle() c = turtle.Turtle() d = turtle.Turtle() e = turtle.Turtle() f = turtle.Turtle() g = turtle.Turtle() h = turtle.Turtle() turtles = [a, b, c, d, e, f, g, h] for blah in turtles: blah.speed(0) blah.tracer(1000000) blah.pensize(2) # Make all the turtles point in the right directions b.left(45) c.left(90) d.left(135) e.left(180) f.left(225) g.left(270) h.left(315) ts = turtle.getscreen() for i in range(random.randrange(0, 200)): #this should be lower with positive sentiment turn = random.randrange(0, round(360/(sentiment*10))) #this should be lower with positive sentiment length = random.randrange(0, 30) #this should be higher with positive sentiment for blah in turtles: blah.right(turn) blah.forward(length) for i in range(random.randrange(0, 1000)): #this should be lower with positive sentiment turn = -1 * random.randrange(0, round(361/(sentiment*10))) #this should be lower with positive sentiment length = random.randrange(0, 30) #this should be higher with positive sentiment for blah in turtles: blah.right(turn) blah.forward(length) ts.getcanvas().postscript(file="static/duck.eps") turtle.done() turtle.exitonclick()
def save(self, frame=None): from PIL import Image import io screen = tt.getscreen() canvas = screen.getcanvas() postscript = canvas.postscript().encode('utf-8') img = Image.open(io.BytesIO(postscript)) if frame: name = self.name + "0" * (5 - len(str(frame))) + str(frame) img.save('pics/%s.gif' % name) else: img.save('pics/%s.jpg' % self.name)
def koch(t, order, size): if order == 0: t.setup(width=1000, height=1000) t.penup() t.pendown() t.forward(size) ts = t.getscreen() ts.getcanvas().postscript(file="duck.eps") else: for angle in [60, -120, 60, 0]: koch(t, order-1, size/3) t.left(angle)
def saveImg(): save = str(raw_input("Would you like to save this image?(Y/N)\n")) if save.upper() == "Y": turtle.hideturtle() name = str(raw_input("What would you like to name it? \n")) nameSav = name + ".svg" if os.path.isdir("Automaton Drawings") == False: os.mkdir("Automaton Drawings") os.chdir("Automaton Drawings") ts = turtle.getscreen().getcanvas() canvasvg.saveall(nameSav, ts) cairosvg.svg2png(url=nameSav, write_to=name + ".png")
def drawText(text,back,up): screen = turtle.getscreen() screen.tracer(0) turt = turtle.Turtle() turt.up() turt.back(back) turt.left(90) turt.forward(up) turt.down() turt.write(text,font=("Arial", 20, "normal")) turt.hideturtle() screen.update()
def circle(): #added for testing for x in range(0,10): #for x in range(0,72): turtle.left(5) for n in range(0,4): turtle.forward(50) turtle.left(90) else: ts = turtle.getscreen() ts.getcanvas().postscript(file="circle.eps") turtle.exitonclick()
def snail(): #added for testing for x in range(25,50): #for x in range(25,175): turtle.left(5) for n in range(0,4): turtle.forward(x) turtle.left(90) else: ts = turtle.getscreen() ts.getcanvas().postscript(file="snail.eps") turtle.exitonclick()
def make_spiral(): angle = 25 length_start = 2 length_increase = 1 sides = 200 for i in range (0,sides): #draw_spiral(25,2,1,50) turtle.forward(length_start+(i*length_increase)) turtle.right(angle) else: #exit and save ts = turtle.getscreen() ts.getcanvas().postscript(file="spiral.eps") turtle.exitonclick()
def dessin(tab_dist,lights): ltab=len(tab_dist) '''for i in range (0, ltab-1): tab_dist.append(velocity*tab_time[i]) print tab_dist''' for i in range(0,ltab): #if tab_time[i]==5: lam.forward(tab_dist[i]/5) if tab_dist[i]<1250: lam.right(60) if ((lights[0][i] > lights[1][i]) and (lights[0][i]>lights[2][i])): #lam.color("black",Light1Detected) #lam.begin_fill() lam.dot(lights[0][i]*35,Light1Detected) #lam.end_fill() if lights[1][i]>lights[2][i]: lam.dot(lights[1][i]*35,Light2Detected) lam.dot(lights[2][i]*35,Light3Detected) else: lam.dot(lights[2][i]*35,Light3Detected) lam.dot(lights[1][i]*35,Light2Detected) elif (lights[1][i] > lights[0][i]) and (lights[1][i]>lights[2][i]): lam.dot(lights[1][i]*35,Light2Detected) if lights[0][i]>lights[2][i]: lam.dot(lights[0][i]*35,Light1Detected) lam.dot(lights[2][i]*35,Light3Detected) else: lam.dot(lights[2][i]*35,Light3Detected) lam.dot(lights[0][i]*35,Light1Detected) else: lam.dot(lights[2][i]*35,Light3Detected) if lights[0][i]>lights[1][i]: lam.dot(lights[0][i]*35,Light1Detected) lam.dot(lights[1][i]*35,Light2Detected) else: lam.dot(lights[1][i]*35,Light2Detected) lam.dot(lights[0][i]*35,Light1Detected) #turtle.mainloop() ts = turtle.getscreen() ts.getcanvas().postscript(file="dessin.eps")
def save_graph(): import ImageGrab #windows only, for now from tkFileDialog import asksaveasfilename as save canvas = turtle.getscreen().getcanvas() turtle.update() turtle.listen() canvas.update() x0 = canvas.winfo_rootx() y0 = canvas.winfo_rooty() x1 = x0 + canvas.winfo_width() y1 = y0 + canvas.winfo_height() turtle.listen() image = ImageGrab.grab((x0,y0, x1,y1)) filename = save(defaultextension='.png') image.save(filename, "PNG") showinfo("File Saved",("File successfully saved as %s" %filename))
import turtle import time # create a screen screen = turtle.getscreen() # set background color of screen screen.bgcolor("#b3daff") # set tile of screen screen.title("Indian Flag - copyright @Neeraj Singh Bhadouria") # "Yesterday is history, tomorrow is a mystery, # but today is a gift. That is why it is called the present.” # — Oogway to Po, under the peach tree, Kung Fu Panda Movie oogway = turtle.Turtle() # set the cursor/turtle speed. Higher value, faster is the turtle oogway.speed() oogway.penup() # decide the shape of cursor/turtle oogway.shape("turtle") # flag height to width ratio is 2:3 flag_height = 300 flag_width = 450 # starting points # start from the first quardant, half of flag width and half of flag height start_x = -225 start_y = 150 # For saffron, white and green stripes. each strip width will be flag_height/3 = 100 stripe_height = flag_height / 3 stripe_width = flag_width
t.forward(length) a(t, n - 1, angle, length) t.right(angle) def moveto(t, x, y): t.penup() t.goto(x, y) t.pendown() p = t.Pen() p.reset() p.down() p.speed(22) ts = t.getscreen() ts.colormode(255) angle = 90 newlength = 300 a(p, 2, 90, newlength) newlength = newlength / 2 moveto(p, -newlength + newlength / 2, -newlength + newlength / 2) a(p, 3, 90, newlength) newlength = newlength / 2 moveto(p, -newlength + newlength / 2, -newlength + newlength / 2) raw_input() a(p, 4, 90, newlength)
# importiamo il package turtle import turtle import random # inizializzazione s = turtle.getscreen() # mostra la finestra # finish line t = turtle.Turtle() t.color("white") t.setpos(300, 200) t.color("black") t.stamp() t.goto(300, -200) # proprieta' dei giocatori player_one = turtle.Pen() player_one.color("green") player_one.shape("turtle") player_one.penup() player_one.goto(-200, 100) player_two = player_one.clone() player_two.color("blue") player_two.penup() player_two.goto(-200, -100) # comincia il gioco for i in range(20): # controllo se p1 ha vinto if player_one.pos() >= (300, 100): print("Player One Wins!")
def __init__(self): self.screen = turtle.getscreen()
turtle.forward(length/2) get_sierpinski(length/2, level-1) turtle.back(length/2) turtle.left(60) turtle.forward(length/2) turtle.right(60) get_sierpinski(length/2, level-1) turtle.left(60) turtle.back(length/2) turtle.right(60) length = int(input("Enter the base length of the triangle : ")) #User can include the depth of the triangle level = int(input("Enter the depth of the triangle : ")) #User can input the depth of recursion get_sierpinski(length,level) turtle.getscreen().getcanvas().postscript(file='3dprint.ps') #format referred from stack overflow
rgb = [255, 0, 0] def progressrainbow(rgb): new = [] r, g, b = rgb if b == 0 and r > 0: r -= 1 g += 1 elif r == 0 and g > 0: g -= 1 b += 1 elif g == 0 and b > 0: b -= 1 r += 1 return r, g, b def spiral(angle): for x in range(900): global rgb rgb = progressrainbow(rgb) t.pencolor(rgb) t.fd(x) t.left(angle) spiral(89) print "done!" turtle.getscreen().getcanvas().postscript(file="output.eps")
os.makedirs(OUTFOLDER) infile_base = os.path.basename(infile) if '.' in infile_base: infile_base = infile_base[:infile_base.rfind('.')] if direct_draw: outfile_ext = 'png' if python_ver >= 3 else 'svg' else: outfile_ext = 'scm' outfile = os.path.join(OUTFOLDER, '%s.%s' % (infile_base, outfile_ext)) if direct_draw: import turtle import tkinter turtle.title('Turtledraw') turtle.mode('logo') screen = turtle.getscreen() window_width = screen.window_width() window_height = screen.window_height() else: window_width = DEFAULT_WINDOW_WIDTH window_height = DEFAULT_WINDOW_HEIGHT if WINDOW_WIDTH_OVERRIDE is not None: window_width = WINDOW_WIDTH_OVERRIDE if WINDOW_HEIGHT_OVERRIDE is not None: window_height = WINDOW_HEIGHT_OVERRIDE import xml.etree.ElementTree svgroot = xml.etree.ElementTree.parse(infile).getroot() width = float(svgroot.attrib.get('width', None)[:-2])
def collision(ball_a, block_a): if (ball_a.top() >= block_a.bottom() and ball_a.right() >= block_a.left() and ball_a.bottom() <= block_a.top() and ball_a.left() <= block_a.right()): return True else: return False def movearound(event): platform.goto(event.x - SCREEN_WIDTH, -SCREEN_HEIGHT + 20) turtle.getcanvas().bind("<Motion>", movearound) turtle.getscreen().listen() def ball_plat(): if collision(platform, MY_BALL) == True: print("collided") MY_BALL.dy = -(MY_BALL.dy) def check_myball_collision(): global score, score_total for b in BLOCKS: if collission(MY_BALL, b) == True: MY_BALL_RADIUS = MY_BALL.radius b_radius = b.radius if MY_BALL_RADIUS < b_radius:
def draw_star(color, size, board_color, board_size): a.pencolor(board_color) a.pensize(board_size) a.fillcolor(color) a.begin_fill() for x in range(35): a.forward(100) a.left(234) a.end_fill() def draw_random_star_in_position(x, y): a.penup() a.goto(x, y) star_color = random.choice(colors) star_size = random.randint(1, 50) board_color = random.choice(colors) board_size = random.randint(1, 5) a.pendown() draw_star(star_color, star_size, board_color, board_size) turtle.getscreen().onclick(draw_random_star_in_position) turtle.done()
def start(): """Initializes the turtle session with pre-defined presets""" turtle.getscreen() turtle.left(90) turtle.pen(fillcolor='#FFCB05', pencolor='#00274C', speed=5) return None
# keep track of the angular position of the large circle. # we actually need the full angle, not just mod 2pi, # since we are multiplying this by a funky fraction. # (In other words, we can't just as the big turtle what # his angle is.) th += 2 * pi / nsteps # get the wheel's position ax, ay = a.pos() # use that position, # along with the sine/cosine from the assignment # to find the destination bx, by of the _hole_ turtle (b). bx = ax + hole_rad * cos(-th * (ring_rad - disk_rad) / disk_rad) by = ay + hole_rad * sin(-th * (ring_rad - disk_rad) / disk_rad) # CHALLENGE: create a function to make a cool # radius or time-dependent color scheme. # colors are denoted by fractions of R, G, B. # now go to the new position. b.setpos(bx, by) # At least one call -- but get creative!! spirograph() # Leave this here to print your pretty picture. turtle.getscreen().getcanvas().postscript(file="spirograph.eps")
import turtle import os n = int(input("ingrese el numero de puntas impares:\n")) t1 = turtle.Screen() t1.bgcolor("blue") t = turtle.Pen() ang = 180 / n ang1 = 180 - ang t.left(ang) for x in range(1, n + 1): t.color(1, 0, 0) t.begin_fill() t.left(ang1) t.forward(200) t.end_fill() turtle.getscreen()._root.mainloop()
def c2(): ts = turtle.getscreen() ts.getcanvas().postscript(file="duck.ps")
''' Based on Mitul patel code https://youtu.be/JDA4XzsGn4w Can be run throug this app https://repl.it/repls/PlumpColorlessGnudebugger ''' import turtle mitul = turtle.Turtle() mitul.width(8) mitul.color("#00FF00") new = turtle.getscreen() mitul.speed(10) new.bgcolor("lightblue") # Hidden Work(penup) mitul.left(180) mitul.penup() mitul.forward(300) mitul.right(90) mitul.forward(100) mitul.pendown() # Printing H #start to draw mitul.forward(50) mitul.right(90) mitul.forward(50) mitul.left(90)
if collision_with_myball(): new_ball() break def stop_game(): for i in range(120): print(i) time.sleep(i) quit() t1 = Thread(target=stop_game) t1.start() turtle.getscreen().onclick(angle) def ball_on_field(): if len(Balls) < 1: return False else: return True def new_ball(): global MY_BALL Balls.append(MY_BALL) MY_BALL = Ball(0, 0, "black") MY_BALL.goto(0, -250) MY_BALL.penup()
def parse(filename): xmldoc = xml.dom.minidom.parse(filename) graphicsCommandsElement = xmldoc.getElementsByTagName("GraphicsCommands")[0] graphicsCommands = graphicsCommandsElement.getElementsByTagName("Command") for commandElement in graphicsCommands: print(type(commandElement)) command = commandElement.firstChild.data.strip() attr = commandElement.attributes if command == "GoTo": x = float(attr["x"].value) y = float(attr["y"].value) width = float(attr["width"].value) color = attr["color"].value.strip() cmd = GoToCommand(x,y,width, color) elif command == "Circle": radius = float(attr["radius"].value) width = float(attr["width"].value) color = attr["color"].value.strip() cmd = CircleCommand(radius, width, color) elif command == "BeginFill": color = attr["color"].value.strip() cmd = BeginFillCommand(color) elif command == "EndFill": cmd = EndFillCommand() elif command == "PenUp": cmd = PenUpCommand() elif command == "PenDown": cmd = PenDownCommand() else: raise RuntimeError("Unknown command: " + command) self.graphicsCommands.append(cmd) def loadFile(): filename = tkinter.filedialog.askopenfilename(title="Select a graphics file") newWindow() self.graphicsCommands = PyList() parse(filename) for cmd in self.graphicsCommands: cmd.draw(theTurtle) screen.update() fileMenu.add_command(label="Load... ", command=loadFile) def addToFile(): filename = tkinter.filedialog.askopenfilename(title="Select a grapghics file") theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() theTurtle.pencolor("#000000") theTurtle.fillcolor("#000000") cmd = PenUpCommand() self.graphicsCommands.append(cmd) cmd = GoToCommand(0,0,1, "#000000") self.graphicsCommands.append(cmd) cmd = PenDownCommand() self.graphicsCommands.append(cmd) screen.update() parse(filename) for cmd in self.graphicsCommands: cmd.draw(theTurtle) screen.update() fileMenu.add_command(label = "Load into ..." , command = addToFile) def write(filename): file = open(filename, "w") file.write('<?xml version ="1.0" encoding = "UTF-8" standalone="no" ?> \n') file.write('<GraphicsCommands> \n') for cmd in self.graphicsCommands: file.write(' ' + str(cmd)+ "\n") file.write('</GraphicsCommands>\n') file.close() def saveFile(): filename = tkinter.filedialog.asksaveasfilename(title="Save Picture As...") write(filename) fileMenu.add_command(label="Save As... ", command=saveFile) fileMenu.add_command(label="Exit", command=self.master.quit) bar.add_cascade(label="File", menu = fileMenu) self.master.config(menu=bytes_iterator) #Widgets canvas = tkinter.Canvas(self, width = 600 , height = 600) canvas.pack(side=tkinter.LEFT) theTurtle = turtle.RawTurtle(canvas) theTurtle.shape("circle") screen = theTurtle.getscreen() screen.tracer(0) sideBar = tkinter.Frame(self, padx = 5, pady = 5) sideBar.pack(side = tkinter.RIGHT, fill = tkinter.BOTH) widthSize = tkinter.StringVar() widthEntry = tkinter.Entry(sideBar, textvariable = widthSize) widthEntry.pack() widthSize.set(str(1)) radiusLabel = tkinter.Label(sideBar, text ="Radius") radiusLabel.pack() radiusSize = tkinter.StringVar() radiusEntry = tkinter.Entry(sideBar, textvariable = radiusSize) radiusSize.set(str(10)) radiusEntry.pack() def circleHandler(): cmd = CircleCommand(float(radiusSize.get()), float(widthSize.get()), penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) screen.update() screen.listen() circleButton = tkinter.Button(sideBar, text = "Draw Circle", command = circleHandler) circleButton.pack(fill=tkinter.BOTH) screen.colormode(255) penLabel = tkinter.Label(sideBar,text = "Pen Color") penLabel.pack() penColor = tkinter.StringVar() penEntry = tkinter.Entry(sideBar, textvariable=penColor) penEntry.pack() penColor.set("#000000") def getPenColor(): color = tkinter.colorchooser.askcolor() if color != None: penColor.set(str(color)[-9:-2]) penColorButton = tkinter.Button(sideBar, text = "Pick Pen Color", command = getPenColor) penColorButton.pack(fill = tkinter.BOTH) fillLabel = tkinter.Label(sideBar, text ="Fill Color") fillLabel.pack() fillColor = tkinter.StringVar() fillEntry = tkinter.Entry(sideBar, textvariable = fillColor) fillEntry.pack() fillColor.set("#000000") def getFillColor(): color = tkinter.colorchoose.askcolor() if color != None: penColor.set(str(color)[-9:-2]) fillColorButton = \ tkinter.Button(sideBar, text = "Pick Fill Color" , command = getFillColor) fillColorButton.pack(fill=tkinter.BOTH) def beginFillHandler(): cmd = BeginFillCommand(fillColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmnd) beginFillButton = tkinter.Buttton(sideBar, text = "Begin Fill", command =beginFillHandler) beginFillButton.pack(fill = tkinter.BOTH) def endFillHandler(): cmd = EndFillCommand() cmd.draw(theTurtle) self.graphicsCommands.append(cmd) endFillButton = tkinter.Button(sideBar, text = "End Fill", command = endFillHandler) endFillButton.pack(fill=tkinter.BOTH) penLabel = tkinter.Label(sideBar, text = "Pen Is Down") penLabel.pack() def penUpHandler(): cmd = PenUpCommand() cmd.draw(theTurtle) penLabel.configure(text = "Pen Is Up ") self.graphicsCommands.append(cmd) penUpButton = tkinter.Button(sideBar, text = "Pen Up", command = penUpHandler) penUpButton.pack(fill = tkinter.BOTH) def penDownHandler(): cmd = penDownCommand() cmd.draw(theTurtle) penLabel.configure(text="Pen Is Down") self.graphicsCommands.append(cmd)
def draw(op, name): # background, speed and hide pen while draw turtle.bgcolor('black') turtle.speed('fastest') turtle.hideturtle() if op == 1: for x in range(180): turtle.pencolor(colorss[x % 2]) turtle.width(x / 100 + 1) turtle.forward(x) turtle.right(80) elif op == 2: for x in range(100): turtle.pencolor(colorss[x % 2]) turtle.width(x / 100 + 1) turtle.forward(x) turtle.left(170) elif op == 3: for angle in range(0, 360, 2): turtle.penup() turtle.home() turtle.pendown() turtle.setheading(angle) while turtle.distance(0, 0) < MAX_DISTANCE: turtle.pencolor(colorss[angle % 2]) angle = randrange(-MAX_ANGLE, MAX_ANGLE + 1) turtle.right(angle) turtle.forward(50) elif op == 4: for x in range(100): turtle.width(x / 100 + 1) for y in range(20): turtle.pencolor(colorss[x % 2]) turtle.forward(0.5 + 10 + y) turtle.left(77 / 9) turtle.left(77) elif op == 5: for x in range(180): turtle.width(x / 100 + 1) for y in range(6): turtle.pencolor(colorss[x % 2]) turtle.forward(x / 6) turtle.left(40) turtle.left(100) # turtle.dot(6) elif op == 6: for x in range(200): turtle.pencolor(colorss[x % 2]) turtle.forward(x * 2) turtle.right(121) elif op == 7: size = 1 for x in range(50): for y in range(4): turtle.pencolor(colorss[x % 2]) turtle.forward(size + y - 1) turtle.right(90) size += 1 turtle.right(10) elif op == 8: for x in range(360): turtle.pencolor(colorss[x % 2]) turtle.forward(x) turtle.right(91) # convert draw in image img_canvas = turtle.getscreen().getcanvas() save_as_png(img_canvas, name) # wait user close the draw turtle.done()
import turtle as tu # 实例化一张画布。 # 也可以不用实例化,直接用 tu.setup(480,360)。 # 因为turtle会自动初始化一张画布。 scr = tu.Screen() src = tu.getscreen() # 获取当前的屏幕/画布 scr.setup(480, 360) scr.delay(0) # 实例化一支笔 pen1 用来显示坐标。 pen1 = tu.Turtle() pen1.pen(pencolor='blue', pensize=2) pen1.up() pen1.goto(0, 130) # 实例化第二支笔 pen2 用来绑定事件。 pen2 = tu.Turtle(shape='turtle') pen2.pen(pencolor='red', pensize=2, fillcolor='yellow') # 定义一个可以绑定的函数。 def cursor_x_y(event): """要进行坐标转换,因为 event.x, event.y 获取的坐标的原点是在 窗口的左上角,坐标轴是这样的┌ ,而画布中的坐标原点是在画布中心└。""" x = event.x - 240 y = 180 - event.y s = "鼠标坐标为:" + str(x) + "," + str(y) pen1.clear() pen1.write(s, align="center", font=("Arial", 16, "normal"))
# The population is entirely replaced by the offspring pop[:] = offspring # Gather all the fitnesses in one list and print the stats fits = [ind.fitness.values[0] for ind in pop] length = len(pop) mean = sum(fits) / length sum2 = sum(x * x for x in fits) std = abs(sum2 / length - mean**2)**0.5 print(" Min %s" % min(fits)) print(" Max %s" % max(fits)) print(" Avg %s" % mean) print(" Std %s" % std) # Save best individual if np.max(fits) > 0: # print('Best fitness = %s' % (bestFitness)) # if np.max(fits) > bestFitness: # bestFitness = np.max(fits) bestIndividual = pop[np.argmax(fits)] screen.clear() # Reset screen turtle.tracer(0) lSystem = TreeLSystem(bestIndividual, screenSize, display=True) # Make new tree result = lSystem.run() turtle.setpos([0, -.9 * screenSize[1]]) turtle.write('Generation %s' % (g + 1), align="center", font=("Arial", 14, "normal")) turtle.getscreen().getcanvas().postscript(file='%s.ps' % (g))
self.right(146) self.tripolyr(side * .75, scale) def tripolyl(self, side, scale): if side < (4 * scale): return self.forward(side) self.left(111) self.forward(side / 1.78) self.left(111) self.forward(side / 1.3) self.left(146) self.tripolyl(side * .75, scale) def centerpiece(self, s, a, scale): self.forward(s); self.left(a) if s < (7.5 * scale): return self.centerpiece(s - (1.2 * scale), a, scale) turtle.bgcolor("black") turtle.pencolor("White") t = Designer() t.speed(0) t.hideturtle() t.getscreen().delay(0) t.getscreen().tracer(0) t.design(t.position(), 2) turtle.getscreen().getcanvas().postscript(file='input.ps') os.system('gswin64 -o output.png -sDEVICE=pngalpha -r300 input.ps')
def SaveEps(file_name): print('Saving in eps...') screen = turtle.getscreen() screen.getcanvas().postscript(file=file_name + '.eps')
def clearScreen(x, y): print("please clear") turtle.getscreen().clear()
import turtle as t t.getscreen().bgcolor("black") t.setup(650, 350, 200, 200) t.pensize(15) t.pencolor("yellow") t.hideturtle() t.speed(10) #p t.pu() t.goto(-150, 50) t.pd() t.seth(-90) t.forward(110) t.pu() t.goto(-150, 0) t.seth(-30) t.pd() t.forward(15) t.circle(25, 120) t.forward(30) t.seth(110) t.circle(25, 120) #y t.pu() t.goto(-70, 55) t.seth(-90) t.pd() t.forward(40) t.circle(25, 120) t.pu()
#Make the turtle to draw your name import turtle as t #Module imported print " Turtle Name Drawing " #titile print "*" * 70 name = raw_input("Enter your name") namelist = list(name) #characters saved as list namelistlen = len(namelist) alphalist = list("abcdefghijklmnopqrstuvwxyz .") drawnum = [] #charactersdatabase for i in namelist: for j in range(28): if i == alphalist[j]: drawnum.append(j) screen = t.getscreen() t.clear() t.title("Name Drawer") screen.bgcolor("orange") t.speed(1) t.setworldcoordinates(0, 0, 500, 500) t.shape("turtle") t.color("blue", "green") t.pensize(10) def draw(x): if x == 0: y = t.pos() t.seth(70) t.fd(100) y1 = t.pos() t.seth(0)
turtle.getcanvas().bind("<Motion>", movearound) turtle.listen() while RUNNING == True: if (SCREEN_WIDTH != getcanvas().winfo_width() / 2 or SCREEN_HEIGHT != getcanvas().winfo_height() / 2): SCREEN_WIDTH = turtle.getcanvas().winfo_width() / 2 SCREEN_HEIGHT = turtle.getcanvas().winfo_height() / 2 RUNNING = check_myball_collision() my_ball.move(SCREEN_HEIGHT, SCREEN_WIDTH) move_all_balls() check_myball_collision() check_all_balls_collision() turtle.getscreen().update() time.sleep(0.05) if RUNNING == False: penup() turtle.goto(0, 0) turtle.write("TRY AGAIN", move=False, algin="center", font=("Arial", 50, "blod")) hideturtle() turtle.getscreen().update() mainloop()
def setup(col, x, y, w, s, shape): turtle.up() turtle.goto(x,y) turtle.width(w) turtle.turtlesize(s) turtle.color(col) turtle.shape(shape) turtle.bgpic("assets/dancing-banana.gif") turtle.down() wn.listen() turtle.getscreen()._root.bind_all('<Key>', key_pressed) turtle.getscreen()._root.mainloop()