def main(): turtle.setup(1300, 800, 0, 0) # 启动图形窗口 pythonsize = 10 turtle.pensize(pythonsize) turtle.pencolor("blue") turtle.seth(-40) # 启动时运动的方向(角度) drawSnake(40, 80, 5, pythonsize/2)
def dessine(liste): """ Fonction qui ce charge de dessiner les courbes. """ # Si la liste reçu n'est pas vide. if liste != []: # Création de la fenètre turtle. t = turtle.Turtle() # On cache la tortue. t.hideturtle() # On met la vitesse max. t.speed(0) # On configure la taille de la fenètre. turtle.setup(width=650,height=650) # Création du repère. repère(t) # On compte le nombre de tour à faire. nb_tour = len(liste) # Boucle qui permet d'afficher les courbes. for n in range(nb_tour): e = liste[n] f = e[0] c = e[1] fonction(t,f,c) # Mainloop pour que la fenètre reste. turtle.mainloop()
def __init__(self, mazeFileName): rowsInMaze = 0 columnsInMaze = 0 self.mazelist = [] mazeFile = open(mazeFileName, 'r') for line in mazeFile: rowList = [] col = 0 for ch in line[:-1]: rowList.append(ch) if ch == 'S': self.startRow = rowsInMaze self.startCol = col col = col + 1 rowsInMaze = rowsInMaze + 1 self.mazelist.append(rowList) columnsInMaze = len(rowList) self.rowsInMaze = rowsInMaze self.columnsInMaze = columnsInMaze self.xTranslate = -columnsInMaze / 2 self.yTranslate = rowsInMaze / 2 self.t = turtle.Turtle() self.t.shape('turtle') self.wn = turtle.Screen() turtle.setup(width = 600, height = 600) turtle.setworldcoordinates(-(columnsInMaze - 1)/2 - .5, -(rowsInMaze - 1) / 2 - .5, (columnsInMaze - 1)/ 2 + .5, (rowsInMaze - 1) / 2 + .5 )
def plot(self, node1, node2, debug=False): """Plots wires and intersection points with python turtle""" tu.setup(width=800, height=800, startx=0, starty=0) tu.setworldcoordinates(-self.lav, -self.lav, self.sample_dimension+self.lav, self.sample_dimension+self.lav) tu.speed(0) tu.hideturtle() for i in self.index: if debug: time.sleep(2) # Debug only tu.penup() tu.goto(self.startcoords[i][0], self.startcoords[i][1]) tu.pendown() tu.goto(self.endcoords[i][0], self.endcoords[i][1]) tu.penup() if self.list_of_nodes is None: intersect = self.intersections(noprint=True) else: intersect = self.list_of_nodes tu.goto(intersect[node1][0], intersect[node1][1]) tu.dot(10, "blue") tu.goto(intersect[node2][0], intersect[node2][1]) tu.dot(10, "blue") for i in intersect: tu.goto(i[0], i[1]) tu.dot(4, "red") tu.done() return "Plot complete"
def initBannerCanvas( numChars , numLines, scale ): """ Set up the drawing canvas to draw a banner numChars wide and numLines high. The coordinate system used assumes all characters are 20x20 and there are 10-point spaces between them. Precondition: The initial canvas is default size, then input by the first two user inputs, every input after that defines each letter's scale, probably between 1 and 3 for the scale values to have the window visible on the screen. Postcondition: The turtle's starting position is at the bottom left corner of where the first character should be displayed, the letters are printed. """ scale = int(input("scale, integer please")) # This setup function uses pixels for dimensions. # It creates the visible size of the canvas. canvas_height = 80 * numLines *scale canvas_width = 80 * numChars *scale turtle.setup( canvas_width *scale, canvas_height *scale) # This setup function establishes the coordinate system the # program perceives. It is set to match the planned number # of characters. height = 30 *scale width = 30 * numChars *scale margin = 5 # Add a bit to remove the problem with window decorations. turtle.setworldcoordinates( -margin+1 * scale, -margin+1 * scale, width + margin* scale, numLines*height + margin * scale) turtle.reset() turtle.up() turtle.setheading( 90 ) turtle.forward( ( numLines - 1 ) * 30 ) turtle.right( 90 ) turtle.pensize( 1 *scale)
def drawQuilt( r, g, b, row_num, col_num, sq_size, margin, t): # Setup window size turtle.setup( sq_size * col_num + margin + sq_size*.2, sq_size * row_num + margin + sq_size*.2) # Move turtle to top left corner posX = -(sq_size * col_num ) /2.0 + sq_size/2.0 posY = (sq_size * row_num ) /2.0 - sq_size/2.0 # Calls function to draw the quilt border quiltBorders(r, g, b, col_num, row_num, sq_size, t) # Matrix for quilt for rows in range ( row_num ): for cols in range( col_num ): t.pu() # Move turtle over for next row/column position patPosX = posX + cols * sq_size patPosY = posY + rows * - sq_size t.setpos(patPosX, patPosY) t.pd() if (4-rows + cols) % 5 == 4: patternA( patPosX, patPosY, sq_size, t ) elif (4-rows + cols) % 5 == 3: patternB( patPosX, patPosY, sq_size, t ) elif(4-rows + cols) % 5 == 2: patternC( patPosX, patPosY, sq_size, t ) elif (4-rows + cols) % 5 == 1: patternD( patPosX, patPosY, sq_size, t ) else: patternE(patPosX, patPosY, sq_size, t )
def draw_circle(radius): turtle.setup(0.75, 0.75, None, None) racer_turtle = turtle.Turtle() # set up the turtle racer_turtle.speed("medium") racer_turtle.pensize(5) racer_turtle.penup() # change starting position of the turtle racer_turtle.goto(-100, -100) racer_turtle.pendown() # calculate the chord of the circle with the radius line = (radius * 2.0) * math.sin(math.radians(45.5)) while True: # infinitly draw a circle with changing color red = random.random() # generates a random color green = random.random() blue = random.random() racer_turtle.color(red, green, blue) racer_turtle.forward(line) # move the turtle racer_turtle.left(91) window = turtle.Screen() # create a graphic window window.exitonclick()
def main(): turtle.setup(1300, 800, 0, 0) pythonsize = 30 turtle.pensize(pythonsize) turtle.pencolor("blue") turtle.seth(-40) drawSnake(40, 80, 5, pythonsize / 2)
def main(): turtle.setup(1300,800,0,0) pythonsize=1 turtle.pensize(pythonsize) turtle.pencolor("black") turtle.seth(-40) drawSnack(40,80,5,pythonsize/2)
def main(): #用户输入一个文件名 filename = input("enter a filename: ").strip() infile = open(filename, 'r') #建立用于计算词频的空字典 wordCounts = {} for line in infile: processLine(line.lower(), wordCounts) #从字典中获取数据对 pairs = list(wordCounts.items()) #列表中的数据对交换位置,数据对排序 items = [[x,y] for (y,x) in pairs] items.sort() #输出count个数词频结果 for i in range(len(items)-1, len(items)-count-1, -1): print(items[i][1]+'\t'+str(items[i][0])) data.append(items[i][0]) words.append(items[i][1]) infile.close() #根据词频结果绘制柱状图 turtle.title('词频结果柱状图') turtle.setup(900, 750, 0, 0) t = turtle.Turtle() t.hideturtle() t.width(3) drawGraph(t)
def main(): turtle.title('数据驱动的动态路径绘制') turtle.setup(800,600,0,0) #设置画笔 pen = turtle.Turtle() pen.color("red") pen.width(5) pen.shape("turtle") pen.speed(5) #读取文件 result = [] file = open("C:\Users\30908\Desktop\wode.txt","r") for line in file: result.append(list(map(float,line.split(",")))) print result #动态绘制 for i in range(len(result)): pen.color((result[i][3],result[i][4],result[i][5])) pen.fd(result[i][0]) if result[i][1]: pen.rt(result[i][2]) else: pen.lt(result[i][2]) pen.goto(0,0) file.close()
def main(): fileName = input('input a file name:').strip() infile = open(fileName, 'r') wordCounts = {} for line in infile: processline(line.lower(), wordCounts) pairs = list(wordCounts.items()) items = [[x, y] for (y, x) in pairs] items.sort() for i in range(len(items)): if items[i][1] == ' ': items.pop(i) for i in range(len(items)-1, len(items)-count-1, -1): print(items[i][1]+'\t'+str(items[i][0])) data.append(items[i][0]) words.append(items[i][1]) infile.close() turtle.title('wordCounts chart') turtle.setup(900, 750, 0, 0) t = turtle.Turtle() t.hideturtle() t.width(3) drawGraph(t)
def SCREEN( self, mode ): """ SCREEN 0 ● Text mode only SCREEN 1 ● 320 × 200 pixel medium-resolution graphics ● 80 x 25 text SCREEN 2 ● 640 × 200 pixel high-resolution graphics ● 40 × 25 text SCREEN 7 ● 320 × 200 pixel medium-resolution graphics ● 40 × 25 text SCREEN 8 ● 640 × 200 pixel high-resolution graphics ● 80 × 25 text SCREEN 9 ● 640 × 350 pixel enhanced-resolution graphics ● 80 × 25 text SCREEN 10 ● 640 × 350 enhanced-resolution graphics ● 80 × 25 text """ if mode == 8: # Officially 640x200 with rectangular pixels, appears as 640x480. turtle.setup( width=640, height=480 ) turtle.setworldcoordinates(0,0,640,480) self.aspect_v = (200/640)*(4/3) elif mode == 9: # Official 640x350 with rectangular pixels, appears 640x480. turtle.setup( width=640, height=480 ) turtle.setworldcoordinates(0,0,640,480) self.aspect_v = (350/640)*(4/3)
def main(): turtle.setup(800, 350, 200, 200) turtle.penup() turtle.fd(-300) turtle.pensize(5) drawDate(datetime.datetime.now().strftime('%Y%m%d')) turtle.hideturtle()
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 drawBoard(b): #set up window t.setup(600,600) t.bgcolor("dark green") #turtle settings t.hideturtle() t.speed(0) num=len(b) side=600/num xcod=-300 ycod=-300 for x in b: for y in x: if(y> 0): drawsquare(xcod,ycod,side,'black') if(y< 0): drawsquare(xcod,ycod,side,'white') if(y==0): drawsquare(xcod,ycod,side,'dark green') xcod=xcod+side xcod=-300 ycod=ycod+side
def startGame(): '''Draws the grid ready to play the game Clears the grid to make sure it is empty before starting a new game Displays the rules/how to play to the user Asks the user which game mode to play by calling gameModeSelection()''' turtle.setup(650,600) turtle.title("Noughts and Crosses by Genaro Bedenko") drawGrid() # Reset the gridSquares to be empty # This is needed for when a game has already been played and the player chose # to play again, they need to play from a new grid for i in range(1,10): gridSquares[i] = 0 displayRules() playSavedGame = messagebox.askquestion(title="Play Previous Game?", message="Do you want to play a previously saved game?") if(playSavedGame=="yes"): try: loadGame(gridSquares) # If the user clicks yes to play a saved game but their isn't one saved in the directory. Display a message to tell them # this and move on to starting a new game except FileNotFoundError: messagebox.showinfo(title="No Saved Game Available", message="There isn't a currently saved game available to play") gameModeSelection() else: gameModeSelection()
def main(): #设置窗口信息 turtle.title('数据驱动的动态路径绘制') turtle.setup(800, 600, 0, 0) #设置画笔 pen = turtle.Turtle() pen.color("red") pen.width(5) pen.shape("turtle") pen.speed(5) #读取文件 result=[] file = open("data.txt","r") for line in file: result.append(list(map(float, line.split(',')))) print(result) #动态绘制 for i in range(len(result)): pen.color((result[i][3],result[i][4],result[i][5])) pen.forward(result[i][0]) if result[i][1]: pen.rt(result[i][2]) else: pen.lt(result[i][2]) pen.goto(0,0)
def main(): # to display the degree sign when printing results deg = u'\N{DEGREE SIGN}' turtle.setup(500, 500) # make window set size win = turtle.Screen() # refer to the screen as win win.title( "Triangles and Angles!") # change the window title win.bgcolor( "#D3D3D3") # change background color # get 3 X,Y coords from the user using eval( input()) x1, y1, x2, y2, x3, y3 = eval( input( "Give 3 points: [e.g. 20, 20, 100, 200, 20, 200] ")) # compute the distances of all points a = distance( x1, y1, x2, y2) b = distance( x2, y2, x3, y3) c = distance( x1, y1, x3, y3) # round off d1 = round( a * 100) / 100.0 d2 = round( b * 100) / 100.0 d3 = round( c * 100) / 100.0 # make 3 seperate calls to determine_angle to find all angles opposite their sides angle_x = determine_angle( a,b,c) angle_y = determine_angle( b,c,a) angle_z = determine_angle( c,b,a) print( "The angles of the triangle are:") print( "\tAngle A: {:.2f}{} \n\tAngle B: {:.2f}{} \n\tAngle C: {:.2f}{}".format( angle_x,deg,angle_y,deg,angle_z,deg),end='\n\n') # draw the grid for the layout and referencing of plots draw_grid() draw_line( x1, y1, x2, y2, x3, y3, angle_x, angle_y, angle_z) turtle.done()
def make_turtle_gif(user_program, output_file, snapshot_delay, frame_delay): def tick(): #print("snip") counter.take_picture(root_prefix) root.after(snapshot_delay, tick) def exitonclick(): turtle.exitonclick = lambda *a, **kw: None counter.take_picture(root_prefix) # prefix for temporary files root_prefix = ".temp_shot-%s-%03d-" % \ (time.strftime("%Y%m%d%H%M%S"), random.randrange(1000)) # do a last picture when we're done counter = Counter() turtle.exitonclick = exitonclick turtle.setup(1920, 1080) root = turtle.getcanvas()._root() root.after(snapshot_delay, tick) # start the users program execute_file(user_program) counter.take_picture(root_prefix) print("Creating gif", output_file, repr(root_prefix)) subprocess.call( [CREATE_GIF_SH, root_prefix, output_file, str(frame_delay)])
def main(): print (":: Chaos Game Programs ::\nThe first [1] one runs a Sierpinski's triangle based on vertices that are all click-based. The second [2] is the"+'"truer" version that has vertices based on a regular polygon.') choice = int(input("Input the integer of your choice: ")) # e = extent, as in how many points to plot after however many vertices and then the one random point if choice == 1: s1 = float(input("What do you want the first side length to be?")) s2 = float(input("What do you want the first side length to be?")) s3 = float(input("What do you want the first side length to be?")) length = [s1,s2,s3] length = length.sort() if (length[0] + length[1]) >= length[2]: sierpinskitriangle(s,t,e,length) turtle.setup(900,700) s = turtle.Screen() t = turtle.Turtle() e = 1000 t.speed(0) s.mainloop() else: print ("Please enter a valid triangle.") choice = 1 main() elif choice == 2: print ("Enter an integer value for the number of sides of the regular polygon. ") n = int(input()) turtle.setup(900,700) s = turtle.Screen() t = turtle.Turtle() e = 1000 t.speed(0) regularchaos(s,t,n,e) s.mainloop()
def __init__(self): # Janela sobre self.janSobre = None # Cor de fundo self.corFundo = "gray" turtle.screensize(1000, 700, self.corFundo) turtle.setup(width=1000, height=700) turtle.title("cidadeBela - Janela de desenho") turtle.speed(0) turtle.tracer(4) # Definindo variáveis globais self._tamPadrao = "" # Listas de prédios self.predios = ['Casa', 'Hotel'] self.prediosProc = [ 'hotel', 'hotelInv', 'casa', 'casaInv' ] # Sorteando elementos self.sorteioPredios = [["casa", 1], ["hotel", 1]] self.sorteioPrediosInv = [["casaInv", 1], ["hotelInv", 1]] # Cores dos prédios self.coresHotel = ["076080190", "255255255", "167064057", "153204255", "000090245", "201232098", "255058123", "010056150", "130255255", "255255000", "255000000", "255127042", "000255000", "255170255", "000255170", "212000255", "170255127", "127212255", "255127127", "255212085", "212212255", "255255127", "222202144" ] self.coresCasa = ['209187103', '115155225', '130047006', '255137111', '203229057', '017130100', '025195159', '204057065', '194082255', '092221159', '167045055', '238243030', '069241248', '000156228', '159094040', '048033253', '040209239', '138164253', '190042177', '000122159', '255255255', '253208201', '245228133'] self.coresLoja = ['255255255', '253208201', '245228133' ] # Janelas dos prédios self.janelasHotel = janelas.janelasHotel self.janelasCasa = janelas.janelasCasa self.janelasLoja = janelas.janelasLoja self.janelasTodas = janelas.janelasTodas # Tetos dos prédios self.tetosHotel = tetos.tetosHotel self.tetosCasa = tetos.tetosCasa self.tetosLoja = tetos.tetosLoja self.tetosTodas = tetos.tetosTodas # Portas dos prédios self.portasHotel = portas.portasHotel self.portasCasa = portas.portasCasa self.portasLoja = portas.portasLoja self.portasTodas = portas.portasTodas
def draw(self, x, y, width, height, max_length=None, force_fields=None): """Draw the string. The grammar-system axiom is extended to the specified depth""" self.reset() turtle.setup(width,height,None,None) turtle.tracer(200,0) self.penup() self.setposition(x,y) self.origin = x, y self.max_length = max_length while not self.grammar_system.done and \ self.grammar_system.generation < self.depth: self.grammar_system.step() if (self.max_length is not None and len(self.grammar_system.string) > self.max_length): self.hideturtle() print("Drawing exceeded maximum length") return False print(self.grammar_system.string) if force_fields: for force_field in force_fields: self.force_fields.append(Attractor(force_field['type'], force_field['effect'], force_field['x'], force_field['y'], force_field['size'])) non_null = self._draw(self.grammar_system.string, self._rules) self.hideturtle() turtle.update() return non_null
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 initBannerCanvas( numChars, numLines ): """ Set up the drawing canvas to draw a banner numChars wide and numLines high. The coordinate system used assumes all characters are 20x20 and there are 10-point spaces between them. Postcondition: The turtle's starting position is at the bottom left corner of where the first character should be displayed. """ # This setup function uses pixels for dimensions. # It creates the visible size of the canvas. canvas_height = 80 * numLines canvas_width = 80 * numChars turtle.setup( canvas_width, canvas_height ) # This setup function establishes the coordinate system the # program perceives. It is set to match the planned number # of characters. height = 30 width = 30 * numChars margin = 5 # Add a bit to remove the problem with window decorations. turtle.setworldcoordinates( -margin+1, -margin+1, width + margin, numLines*height + margin ) turtle.reset() turtle.up() turtle.setheading( 90 ) turtle.forward( ( numLines - 1 ) * 30 ) turtle.right( 90 ) turtle.pensize( 2 * scale)
def __init__(self, length, width, roomba_step, obstacles=None): ''' ###initialization ''' self.obstacles = obstacles self.orient = 0 self.length = length #assume length in m self.width = width #assume width in m self.roomba_step = roomba_step#assume in m self.multiply_factor = 50 #screenstep = multiply_factor * length/width self.step_l = self.length*self.multiply_factor self.step_w = self.width*self.multiply_factor self.roomba_l = self.roomba_step*self.multiply_factor self.t = turtle.Turtle() self.t.shape("classic") turtle.setup(self.step_l+100,self.step_w+100) turtle.screensize(self.step_l+10, self.step_w+10) #turtle.bgcolor("orange") self.t.penup() self.t.bk(self.step_l/2) # backward() self.t.lt(90) # left() self.t.fd(self.step_w/2) # forward() self.t.rt(90) # right() self.draw_boundary(self.step_l, self.step_w, self.roomba_l, self.t) ###set pen width self.t.pendown() self.t.pencolor("green") self.t.pensize(self.roomba_l-1) self.t.fd(self.roomba_l)
def main(): # set up the name of the window turtle.title("Polygonville") # setup the screen size through (1000, 650) # setup the initial location through (0,0) turtle.setup(1000,650,0,0) print("Welcome to Polygonville!") totalSides = input("Input number of sides in the polygon: ") while totalSides != 0: if totalSides < 3: print("Sorry, " + str(totalSides) + " is not " + "valid, try again or press 0 to exit") elif totalSides == 3: totalAngles = 180 * (totalSides - 2) sideLength = input("Put polygon sidelength: ") angle = totalAngles/totalSides func1(totalSides, sideLength, angle, totalAngles) else: totalAngles = 180 * (totalSides - 2) sideLength = input("Put polygon side length: ") angle = totalAngles/totalSides func2(totalSides, sideLength, angle, totalAngles) if totalSides > 3: print("Polygon Summary: \n" + "Sides: " + str(totalSides) + "| Anterior Angle: " + str(angle) + "| Sum of Angles: " + str(totalAngles)) totalSides = input("\nInput number of sides in the polygon: ") if totalSides == 0: print("Thank you for using Polygonville!")
def main(): bob = turtle.Turtle() turtle.title('Sun Figure') turtle.setup(800, 800, 0, 0) bob.speed(0) bobMakesASun(bob, 1, 'purple') turtle.done()
def main(): turtle.setup(1300, 800, 0, 0) pythonsize = 30 turtle.pensize(pythonsize) turtle.pencolor('blue') turtle.seth(-40) drawSnake(rad = 40, angle = 80, len = 5, neckrad = pythonsize/2 )
def draw(self): super(DragonLSystem, self).draw() turtle.setup(800,600) wn = turtle.Screen() wn.bgcolor('lightblue') wn.title("Wingled Dragon") self.turtle = turtle.Turtle() self.turtle.shape('blank') turtle.tracer(int(sys.argv[2]),25) t = self.turtle t.reset() t.penup() t.setpos(-200,0) t.pendown() i = 200.0 for c in self.state: if c == "F": t.forward(math.ceil(i)) elif c == "+": t.right(90) elif c == "-": t.left(90) elif c == "C": i = i/math.sqrt(2) t.left(45) wn.exitonclick()
import turtle import random from tkinter.simpledialog import * instr = '' swidth, sheight = 300, 300 tx, ty, txtsize = [0] * 3 turtle.title('임의의 위치에 글자를 쓰는 거북이') turtle.shape('turtle') turtle.setup(width=swidth + 50, height=sheight + 50) turtle.screensize(swidth, sheight) turtle.penup() instr = askstring('문자열 입력', '거북이로 쓸 문자열 입력') for ch in instr: tx = random.randrange(-swidth / 2, swidth / 2) ty = random.randrange(-sheight / 2, sheight / 2) r = random.random() g = random.random() b = random.random() txtsize = random.randrange(10, 50) turtle.goto(tx, ty) turtle.pencolor((r, g, b)) turtle.write(ch, font=('맑은 고딕', txtsize, 'bold')) turtle.done()
import turtle turtle.setup(650, 350, 200, 200) turtle.penup() turtle.fd(-60) turtle.pendown() turtle.pensize(6) turtle.pencolor("red") turtle.seth(60) turtle.fd(120) turtle.seth(-60) turtle.fd(120) turtle.seth(-180) turtle.fd(120)
""" Нарисуйте, используя модуль turtle число: 3549 """ import turtle as t t.setup(800, 800) t.width(5) t.color('#ff0004') t.speed(2) for three in range(1): t.down() t.fd(50) t.left(60) t.bk(60) t.right(60) t.fd(30) t.left(90) t.bk(50) t.right(90) t.bk(50) t.up() for five in range(1): t.goto(70, 0) t.down() t.fd(50) t.bk(50) t.right(90) t.fd(50) t.left(90)
# coding:utf-8 import turtle as t t.pensize(4) # 设置画笔的大小 t.colormode(255) # 设置GBK颜色范围为0-255 t.color((255,155,192),"pink") # 设置画笔颜色和填充颜色(pink) t.setup(840,500) # 设置主窗口的大小为840*500 t.speed(10) # 设置画笔速度为10 #鼻子 t.pu() # 提笔 t.goto(-100,100) # 画笔前往坐标(-100,100) t.pd() # 下笔 t.seth(-30) # 笔的角度为-30° t.begin_fill() # 外形填充的开始标志 a=0.4 for i in range(120): if 0<=i<30 or 60<=i<90: a=a+0.08 t.lt(3) #向左转3度 t.fd(a) #向前走a的步长 else: a=a-0.08 t.lt(3) t.fd(a) t.end_fill() # 依据轮廓填充 t.pu() # 提笔 t.seth(90) # 笔的角度为90度 t.fd(25) # 向前移动25 t.seth(0) # 转换画笔的角度为0 t.fd(10) t.pd() t.pencolor(255,155,192) # 设置画笔颜色
# exercise 10.2 import turtle turtle.setup(400, 500) wn = turtle.Screen() wn.title("Tess becomes a traffic light!") wn.bgcolor("lightgreen") tess = turtle.Turtle() def draw_housing(): """ Draw a nice housing to hold the traffic lights """ tess.pensize(3) tess.color("black", "darkgrey") tess.begin_fill() tess.forward(80) tess.left(90) tess.forward(200) tess.circle(40, 180) tess.forward(200) tess.left(90) tess.end_fill() draw_housing() tess.penup() # Position tess onto the place where the green light should be tess.forward(40) tess.left(90) tess.forward(50)
def get_new_win(): # function for getting a new window NewWin = tk.Toplevel(root) # creates new window NewWin.title('Planetary Orbit Simulator') NewWin.geometry('500x650') im2 = Image.open('Background2.png') tkimage1 = ImageTk.PhotoImage(im2) im3 = tk.Label(NewWin, image=tkimage1) im3.place(x=0, y=0, relwidth=1, relheight=1) def quit_win(): # function for quitting the program NewWin.destroy() turtle.bye() QuitButton = tk.Button(NewWin, text='Quit', command=quit_win, height=2, width=10, bg='gray7', fg='white') # creates a quit button QuitButton.place(relx=.5, rely=.85, anchor="c") # places button on window NewWin.protocol("WM_DELETE_WINDOW", quit_win) def plot_mercury(): # function for plotting velocity graph for Mercury x = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) y = np.array([ 35701, 45890, 56785, 39190, 36630, 50913, 52074, 36976, 38609, 55892 ]) plt.plot(x, y, color='k') plt.title('Velocity of Mercury', fontsize=16) plt.xlabel('Steps (weeks)', fontsize=12) plt.ylabel('Velocity $(m/s)$', fontsize=12) plt.show() plot1 = tk.Button(NewWin, text='Mercury', command=plot_mercury, height=1, width=11, bg='black', fg='white') # creates button which plots graph plot1.place(relx=.2, rely=.7, anchor="c") # places the button on window def plot_venus(): x = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) y = np.array([ 38006, 32402, 32866, 38234, 33731, 31858, 37352, 35415, 31466, 35769 ]) # data found from animation plt.plot(x, y, color='y') plt.title('Velocity of Venus', fontsize=16) plt.xlabel('Steps (weeks)', fontsize=12) plt.ylabel('Velocity $(m/s)$', fontsize=12) plt.show() plot2 = tk.Button(NewWin, text='Venus', command=plot_venus, height=1, width=11, bg='black', fg='white') plot2.place(relx=.4, rely=.7, anchor="c") def plot_earth(): x = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) y = np.array([ 31374, 30861, 28837, 27948, 29058, 31059, 31244, 29321, 27984, 28615 ]) plt.plot(x, y, color='b') plt.title('Velocity of Earth', fontsize=16) plt.xlabel('Steps (weeks)', fontsize=12) plt.ylabel('Velocity $(m/s)$', fontsize=12) plt.show() plot3 = tk.Button(NewWin, text='Earth', command=plot_earth, height=1, width=11, bg='black', fg='white') plot3.place(relx=.6, rely=.7, anchor="c") def plot_mars(): x = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) y = np.array([ 24516, 24868, 24918, 24612, 24172, 23712, 23431, 23422, 23686, 24139 ]) plt.plot(x, y, color='r') plt.title('Velocity of Mars', fontsize=16) plt.xlabel('Steps (weeks)', fontsize=12) plt.ylabel('Velocity $(m/s)$', fontsize=12) plt.show() plot4 = tk.Button(NewWin, text='Mars', command=plot_mars, height=1, width=11, bg='black', fg='white') plot4.place(relx=.8, rely=.7, anchor="c") class Simulator(turtle.Turtle): # class for creating turtle animation name = 'Simulator' mass = None vx = vy = 0.000 # intial value px = py = 0.000 def gravity(self, other): # function for calculation of force sx, sy = self.px, self.py ox, oy = other.px, other.py dx = (ox - sx) dy = (oy - sy) d = math.sqrt(dx**2 + dy**2) # infinitesimally small distance f = G * self.mass * other.mass / (d**2 ) # from Newton's Gravity Law theta = math.atan2(dy, dx) fx = math.cos(theta) * f # x-component of force fy = math.sin(theta) * f # y-component of force return fx, fy def data(step, planets): # function for printing data print('Step #{}'.format(step)) for planet in planets: s = '{:<8} Pos.={:>6.2f} {:>6.2f} Vel.={:>10.3f} {:>10.3f}'.format( planet.name, planet.px / AU, planet.py / AU, planet.vx, planet.vy) print(s) print() def loop(planets): # function for drawing orbits timestep = 24 * 3600 * 7 # 7 days for planet in planets: planet.penup() planet.hideturtle() step = 1 while True: data(step, planets) step += 1 # adds 1 after each step force = {} # creates array for force for planet in planets: total_fx = total_fy = 0.0 for other in planets: if planet is other: continue fx, fy = planet.gravity(other) total_fx += fx total_fy += fy force[planet] = (total_fx, total_fy) # total force on planet for planet in planets: fx, fy = force[planet] planet.vx += fx / planet.mass * timestep # calculates vx after timestep planet.vy += fy / planet.mass * timestep planet.px += planet.vx * timestep # calculates vx after timestep planet.py += planet.vy * timestep planet.goto(planet.px * scale, planet.py * scale) # calculates position according to scale planet.dot(6) # prints dot at positon def main(): # function for adding objects to turtle animation '''Data taken from NASA website: http://nssdc.gsfc.nasa.gov/planetary/factsheet/''' sun = Simulator() sun.name = 'Sun' sun.mass = 1.98855 * 10**30 sun.pencolor('yellow') mercury = Simulator() mercury.name = 'Mercury' mercury.mass = 0.33011 * 10**24 mercury.px = 0.3870 * AU mercury.vy = 47.362 * 1000 mercury.pencolor('brown') venus = Simulator() venus.name = 'Venus' venus.mass = 4.8675 * 10**24 venus.px = 0.7230 * AU venus.vy = -35.020 * 1000 venus.pencolor('orange') earth = Simulator() earth.name = 'Earth' earth.mass = 5.9724 * 10**24 earth.px = 1.000 * AU earth.vy = 29.783 * 1000 earth.pencolor('blue') mars = Simulator() mars.name = 'Mars' mars.mass = 0.64171 * 10**24 mars.px = 1.524 * AU mars.vy = 24.077 * 1000 mars.pencolor('red') loop([sun, mercury, venus, earth, mars]) # creates a loop for objects turtle.bgcolor("black") # sets background for turtle window turtle.setup(800, 800) # sets screen size for turtle window app = main() app.mainloop() # starts animation
# -*- coding: utf-8 -*- """ Created on Tue Nov 7 19:54:15 2017 @author: park """ import turtle turtle.title("数据驱动的动态路径绘制") turtle.setup(800,600,0,0) pen=turtle.Turtle() pen.color("red") pen.width(5) pen.shape("turtle") pen.speed(5) result=[]#列表 file=open("data.txt","r") for line in file: result.append(list(map(float,line.split(",")))) #map()是python内置的高阶函数,它接收一个函数f和一个list, #并通过把函数f依次作用在list的每个元素上,得到一个新的list并返回 for i in range(len(result)): pen.color((result[i][3],result[i][4],result[i][5])) pen.fd(result[i][0]) if result[i][1]: pen.rt(result[i][2]) else: pen.lt(result[i][2]) pen.goto(0,0)
import turtle as t t.setup(800, 600) win = t.Screen() win.title("Random crow fly . . . ") tt = t.getturtle() tt.penup() tt.setheading(270) tt.forward(200) tt.pendown() tt.left(90) tt.forward(200) tt.left(90) tt.forward(200) tt.left(90) tt.forward(200) tt.left(90) tt.forward(200) ##tt.setposition(-300,200) ##tt.setposition(300,200) ##tt.setposition(300,-200) ##tt.setposition(-300,-200) t.exitonclick()
def key_8(): disp_num(8) def key_9(): disp_num(9) def key_10(): t.clearstamps() disp_num(10) t.setup(400, 400) s = t.Screen() t.hideturtle() t.speed(0) s.onkeypress(key_0, "0") s.onkeypress(key_1, "1") s.onkeypress(key_2, "2") s.onkeypress(key_3, "3") s.onkeypress(key_4, "4") s.onkeypress(key_5, "5") s.onkeypress(key_6, "6") s.onkeypress(key_7, "7") s.onkeypress(key_8, "8") s.onkeypress(key_9, "9")
import turtle SCREEN_WIDTH = 600 SCREEN_HEIGHT = 600 TARGET_LLEFT_X = 100 TARGET_LLEFT_Y = 250 TARGET_WIDTH = 25 FORCE_FACTOR = 30 PROJECTILE_SPEED = 1 NORTH = 90 SOUTH = 270 EAST = 0 WEST = 180 turtle.setup(SCREEN_WIDTH, SCREEN_HEIGHT) turtle.hideturtle() turtle.speed(0) turtle.penup() turtle.goto(TARGET_LLEFT_X, TARGET_LLEFT_Y) turtle.pendown() turtle.setheading(EAST) turtle.forward(TARGET_WIDTH) turtle.setheading(NORTH) turtle.forward(TARGET_WIDTH) turtle.setheading(WEST) turtle.forward(TARGET_WIDTH) turtle.setheading(SOUTH) turtle.forward(TARGET_WIDTH) turtle.penup() turtle.goto(0, 0) turtle.setheading(EAST) turtle.showturtle() turtle.speed(PROJECTILE_SPEED)
food.y = randrange(-15,15)*10 else: snake.pop(0) tt.clear() for body in snake: print(body.x,body.y) square(body.x,body.y,9,'black') print('--------------------------------------') square(food.x,food.y,9,'green') tt.update() tt.ontimer(move,1000) tt.setup(420,420,370,0) tt.hideturtle() tt.tracer(False) tt.listen() tt.onkey(lambda :change(10,0),'Right') tt.onkey(lambda :change(-10,0),'Left') tt.onkey(lambda :change(0,10),'Up') tt.onkey(lambda :change(0,-10),'Down') move() tt.done()
def turn_down(): # 아래로 방향을 바꿉니다. t.setheading(270) def play(): # 게임을 실제로 플레이하는 함수입니다. t.forward(10) # 주인공 거북이 10만큼 앞으로 이동합니다. ang = te.towards(t.pos()) te.setheading(ang) # 악당 거북이의 방향을 주인공 거북이를 향하도록 맞춥니다. te.forward(9) # 악당 거북이 9만큼 앞으로 이동합니다. if t.distance(ts) < 12: # 주인공과 먹이와의 거리가 12보다 작을 때(가깝게 있으면) star_x = random.randint(-230, 230) star_y = random.randint(-230, 230) ts.goto(star_x, star_y) # 먹이를 다른 곳으로 옮깁니다. if t.distance(te) >= 12: # 주인공과 악당의 거리가 12이상이면 (멀리 있으면) t.ontimer(play, 100) # 0.1초후 play 함수를 실행합니다(게임을 계속 합니다). t.setup(500, 500) t.bgcolor("orange") t.shape("turtle") # ‘거북이 모양’의 커서를 사용합니다. t.speed(0) # 거북이 속도를 가장 빠르게로 지정합니다. t.up() t.color("white") t.onkeypress(turn_right, "Right") # [→]를 누르면 turn_right 함수를 실행하도록 합니다. t.onkeypress(turn_up, "Up") t.onkeypress(turn_left, "Left") t.onkeypress(turn_down, "Down") t.listen() # 거북이 그래픽 창이 키보드 입력을 받도록 합니다. play() # play 함수를 호출해서 게임을 시작합니다.
#t.end_fill() #end of sequence #--------------------------------------------------------- def main(screenx, screeny, t): draw_default(screenx,screeny,t) rocks(screenx,screeny,t) if __name__=='__main__': screeny = 700 screenx = 1000 t = turtle.Turtle() screen = turtle.Screen() t.speed(0) turtle.setup(screenx, screeny) main(screenx,screeny,t) turtle.exitonclick()
import turtle turtle.setup(650, 350, 200, 200) #(width,hight,startx,starty) turtle.penup() turtle.fd(-250) turtle.pendown() turtle.pensize(25) turtle.pencolor("purple") turtle.seth(-40) for i in range(4): turtle.circle(40, 80) turtle.circle(-40, 80) turtle.circle(40, 80 / 2) turtle.fd(40) turtle.circle(16, 180) turtle.fd(40 * 2 / 3) turtle.done()
import turtle turtle.setup(400, 500) # Determine the window size wn = turtle.Screen() # Get a reference to the window wn.title("Handling keypresses!") # Change the window title wn.bgcolor("lightgreen") # Set the background color tess = turtle.Turtle() # Create our favorite turtle # The next four functions are our "event handlers". def h1(): tess.forward(30) def h2(): tess.left(45) def h3(): tess.right(45) def h4(): wn.bye() # Close down the turtle window # These lines "wire up" keypresses to the handlers we've defined. wn.onkey(h1, "Up") wn.onkey(h2, "Left") wn.onkey(h3, "Right") wn.onkey(h4, "q")
#turtle Graphics in Pygame #init import turtle turtle.setup(1024, 1024) t = turtle.Turtle() t.color('black', 'black') t.pensize(1) t.shape('arrow') t.speed(0) t.hideturtle() #setting up window l = 256 a = l / 2 turtle.setup(6 * a, 6 * a) t.penup() t.left(180) t.forward(a) t.left(90) t.forward(a) t.pendown() #fractal def fractal2(size, min): if size > min: t.right(90) for i in [1, 2, 3]: fractal2(size / 2, min)
import turtle turtle.setup(950, 600) prozor = turtle.Screen() prozor.title("Hangman.") turtle.bgpic("slika.gif") strelica = turtle.getturtle() strelica.penup() turtle.hideturtle() turtle.setposition(-50, 300) turtle.write("Hangman", align="left", font=("Arial", 30)) turtle.setposition(100, 200) turtle.write("Dobrodošli!", align="left", font=("Arial", 15)) turtle.setposition(100, 180) turtle.write("Ovo je igrica Hangman.Odaberi slovo i pogodi riječ.", font=("Arial", 15)) turtle.setposition(100, 160) turtle.write("Sretno! :)", font=("Arial", 15)) import random rijec_iz_liste = "false" Rijeci = [ "telefon", "majmun", "tigar", "medvjed", "vjeverica", "gepard", "laptop", "torba", "slika", "farmaceut", "cvijet", "zeko", "kalendar", "radijator", "zgrada", "priroda", "odmor", "planina", "dukserica", "garderoba", "klavir", "orkestar", "doktor", "fakultet", "automobil", "helikopter", "diploma" ] duzinaRijeci = len(Rijeci) pozicija_rijeci = random.randint(0, duzinaRijeci)
''' 自动轨迹绘制 1、定义数据文件格式(接口) 2、编写程序,根据文件接口解析参数绘制图形 3、编制数据文件 ''' #autotracedraw.py import turtle as t t.title('自动绘制') t.setup(800, 600, 0, 0) #绘制窗口的大小 t.pencolor("red") #画笔的初始颜色 t.pensize(5) #画笔的大小 #数据文件的读取 datals = [] f = open("data.txt") for line in f: line = line.replace("\n", "") datals.append(list(map(eval, line.split(",")))) #list map eval 作用是去掉字符串中的引号 #f.close() #自动绘制 for i in range(len(datals)): t.pencolor(datals[i][3], datals[i][4], datals[i][5]) t.fd(datals[i][0]) #表示一行的第一个元素表示行进距离 if datals[i][1]: t.right(datals[i][2]) else: t.left(datals[i][2]) f.close()
import turtle # 引入海龟库 from typing import List screenLocation: List[int] = [1000, 550, 480, 300] #定义海归画布参数 penColor: List[int] = [212, 222, 2] #定义画笔颜色 turtle.setup(screenLocation[0], screenLocation[1], screenLocation[2], screenLocation[3]) # 宽度、高度、相对屏幕左上角X坐标,相对屏幕左上角Y坐标 turtle.penup() # 画笔抬起 turtle.forward(-450) turtle.pendown() # 落笔,开始绘制 turtle.pensize(15) # 设置画笔宽度 别名width turtle.colormode(255) # 改变GRB模式为255制 turtle.pencolor(penColor) # 颜色名称,或者RGB数值 turtle.setheading(-40) # 改变爬行角度 为绝对角度别名seth for i in range(5): #循环4次 如果是M,N则是从产生从M,到N-1个数值 turtle.circle( 50, 90 ) #根据半径r绘制extent角度的弧形 正数为海龟左侧半径r处为原点,负数为海龟右侧半径r为原点;如果有角度参数则右转参数角度,默认360度。 turtle.circle(-40, 90) turtle.circle(40, 80 / 2) turtle.forward(40) # 前进 别名fd 如果是负数,则为倒退 turtle.circle(16, 180) turtle.forward(40 * 2 / 3) turtle.done() #完成后窗体不退出
import turtle as t t.setup(1000, 1000) t.shape("turtle") t.pencolor("black") t.pensize(5) def drawRectangle(width, height, color): t.fillcolor(color) t.begin_fill() t.fd(width) t.lt(90) t.fd(height) t.lt(90) t.fd(width) t.lt(90) t.fd(height) t.lt(90) t.end_fill() drawRectangle(300, 100, "red") drawRectangle(200, 50, "yellow") drawRectangle(100, 25, "blue")
import turtle as t t.setup(800,600,150,150) t.circle(10) t.circle(20) t.circle(30) t.circle(40) t.down
import turtle from characters import * from turtle import Turtle import random import math tracer(0.7) screen_width = turtle.getcanvas().winfo_width() / 2 screen_height = turtle.getcanvas().winfo_height() / 2 #game over pic running = True bg = turtle.clone() turtle.setup(width=762, height=762) NUMBER_OF_STREETS = 10 STREET_WIDTH = screen_height / NUMBER_OF_STREETS MINIMUM_CARS = 1 MAXIMUM_CARS = 3 CARS = [] print(turtle.pos()) class Car(Turtle): def __init__(self, speed, color, pos, width, level): Turtle.__init__(self) self.penup() self.speed(speed) self.car_speed = speed self.color(color)
import turtle import random #전역 변수 선언 부분 swidth, sheight, pSize, exitCount = 300, 300, 3, 0 r,g,b,angle, dist, curX, curY = [0]*7 #메인 코드 부분 turtle.title('거북이가 맘대로 다니기') turtle.shape('turtle') turtle.pensize(pSize) turtle.setup(width=swidth + 30, height=sheight + 30) turtle.screensize(swidth, sheight) while True : r=random.random() g=random.random() b=random.random() turtle.pencolor((r,g,b)) angle = random.randrange(0,360) dist = random.randrange(1,100) turtle.left(angle) turtle.forward(dist) curX=turtle.xcor() curY=turtle.ycor() if(-swidth/2<=curX and curX <= swidth/2) and (-sheight/2 <= curY and curY<=sheight/2): pass else: turtle.penup()
return hilbert_curve(order - 1, 'u') + [np.array([1, 0])] + \ hilbert_curve(order - 1, 'r') + [np.array([0, 1])] + \ hilbert_curve(order - 1, 'r') + [np.array([-1, 0])] + \ hilbert_curve(order - 1, 'd') else: return hilbert_curve(order - 1, 'd') + [np.array([-1, 0])] + \ hilbert_curve(order - 1, 'l') + [np.array([0, -1])] + \ hilbert_curve(order - 1, 'l') + [np.array([1, 0])] + \ hilbert_curve(order - 1, 'u') else: return base_shape[orientation] # test the functions if __name__ == '__main__': order = 6 curve = hilbert_curve(order, 'u') curve = np.array(curve) * 4 cumulative_curve = np.array( [np.sum(curve[:i], 0) for i in range(len(curve) + 1)]) # plot curve using plt plt.plot(cumulative_curve[:, 0], cumulative_curve[:, 1]) # draw curve using turtle graphics tt.setup(1920 / 4, 1000 / 4) tt.pu() tt.goto(-950 / 4, -490 / 4) tt.pd() tt.speed(0) for item in curve: tt.goto(tt.pos()[0] + item[0], tt.pos()[1] + item[1]) tt.done()
t.forward(h) t.left(90) def draw_square(tx,sz): """Make turtle t draw a square of sz.""" draw_rectangle(tx,sz,sz) def move_me(tx): tx.penup() tx.right(135) tx.forward(anglmv) tx.pendown() tx.left(135) turtle.setup(600,400) # Set the size of the window to 600x400 wn = turtle.Screen() # Set up the window and its attributes wn.bgcolor("lightgreen") wn.title("Alex meets function") alex=turtle.Turtle() alex.pensize(3) size=10 anglmv=math.hypot(size,size) step=1 for i in range(10): draw_square(alex,size*step) move_me(alex) step+=2
# Ashley Kang / Turtle Gradient Star import turtle turtle.setup(800, 800) wn = turtle.Screen() wn.colormode(1.0) ike = turtle.Turtle() UNIT = 200 START_COLOR = 0.0 # Blue: (0, 0, 1) END_COLOR = 1.0 # Purple: (1, 0, 1) COUNT = 72 INCREASE = float(END_COLOR / COUNT) def drawStar(turtle, UNIT): # Initialize gradient color gradient = 0 # Loop for drawing strokes # Starts at 0 degrees and increments counterclockwise by 5 degrees # until it reaches 360 degrees for i in range(0, 360, 5): # Increase gradient color by 1 / 72 gradient += INCREASE # Make color and set it to pencolor color = (gradient, 0, 1)
import turtle, math, random turtle.setup(1000, 400) wn = turtle.Screen() bird = turtle.Turtle() def setbird(): bird.setpos(-400, 0) bird.dy = 0 def flyingturtlemove(): fall = bird.ycor() + bird.dy bird.goto(bird.xcor(), fall) if bird.dy > -4: bird.dy -= .1 #gravity if bird.ycor() > 190: bird.dy = -1 # how the flying turtle moves def fn_up(): if bird.dy < 3: if bird.dy < -2: bird.dy += 5 #amount the bird jumps if bird.dy > -2: bird.dy += 4
# -*- coding: utf-8 -*- """ Created on Sun Jul 1 23:58:42 2018 Snake Mini project Starter Code Name: Date: """ import turtle import random #We'll need this later in the lab turtle.tracer(1,0) #This helps the turtle move more smoothly SIZE_X=1000 SIZE_Y=1000 turtle.setup(SIZE_X, SIZE_Y) #Curious? It's the turtle window #size. border = turtle.clone() turtle.hideturtle() turtle.goto(-500,-500) turtle.pendown() turtle.goto(-500, 500) turtle.goto(500,500) turtle.goto(500,-500) turtle.penup() food = turtle.clone () SQUARE_SIZE = 20 START_LENGTH = 8 #Initialize lists
# coding: utf-8 # In[1]: import turtle turtle.setup(1000, 600, 100, 100) turtle.penup() turtle.fd(-300) turtle.pendown() turtle.pensize(28) turtle.pencolor("silver") turtle.seth(-50) for i in range(6): turtle.circle(50, 60) turtle.pencolor("azure") turtle.circle(-50, 60) turtle.pencolor("pink") turtle.circle(50, 60 / 2) turtle.fd(50) turtle.circle(25, 180) turtle.pencolor("rubine") turtle.fd(50 * 2 / 3)
for i in range(200): turtle.right(1) turtle.forward(2) # 输入表白的语句,默认I Love you love = raw_input( 'Please enter a sentence of love, otherwise the default is "I Love you": ') # 输入署名或者赠谁,没有不执行 me = raw_input('Please enter pen name, otherwise the default do not execute: ') if love == '': love = 'I Love you' # 窗口大小 turtle.setup(width=900, height=500) # 颜色 turtle.color('red', 'pink') # 笔粗细 turtle.pensize(3) # 速度 turtle.speed(1) # 提笔 turtle.up() # 隐藏笔 turtle.hideturtle() # 去到的坐标,窗口中心为0,0 turtle.goto(0, -180) turtle.showturtle() # 画上线