def rysuj(): turtle.tracer(0, 0) # wylaczenie animacji co KROK, w celu przyspieszenia turtle.hideturtle() # ukrycie glowki zolwika turtle.penup() # podnosimy zolwia, zeby nie mazal nam linii podczas ruchu ostatnie_rysowanie = 0 # ile kropek temu zostal odrysowany rysunek for i in xrange(ILE_KROPEK): # losujemy wierzcholek do ktorego bedziemy zmierzac do = random.choice(WIERZCHOLKI) # bierzemy nasza aktualna pozycje teraz = turtle.position() # ustawiamy sie w polowie drogi do wierzcholka, ktorego wczesniej obralismy turtle.setpos(w_polowie_drogi(teraz, do)) # stawiamy kropke w nowym miejscu turtle.dot(1) ostatnie_rysowanie += 1 if ostatnie_rysowanie == OKRES_ODSWIEZENIA: # postawilismy na tyle duzo kropek, zeby odswiezyc rysunek turtle.update() ostatnie_rysowanie = 0 pozdrowienia() turtle.update()
def set(): #set of parameters turtle.hideturtle() turtle.tracer(1e3,1) turtle.left(95) turtle.penup() turtle.goto(0,-turtle.window_height()/2) turtle.pendown()
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()
def setup(): turtle.hideturtle() turtle.tracer(1e3,0) turtle.left(90) turtle.penup() turtle.goto(-100,-100) turtle.pendown()
def skyobjects( x, y, scale ): '''puts all of the objects in sky functions togehter''' t.tracer(False) star(x-300*scale, y+225*scale, 1*scale, 'True', 'orange') cloud(x+250*scale, y+200*scale, 1*scale, 'gray') cloud(x+175*scale, y+125*scale, 0.5*scale, 'gray') cloud(x+125*scale, y+215*scale, 0.25*scale, 'gray')
def drawSetup(title,xlimits,xscale,ylimits,yscale,axisThickness=None): turtle.title(title) xmin, xmax = xlimits ymin, ymax = ylimits #turtle.setup(xmax-xmin,ymax-ymin,0,0) #window-size globals()['xmin'] = xmin globals()['xmax'] = xmax globals()['ymin'] = ymin globals()['ymax'] = ymax globals()['xscale'] = xscale globals()['yscale'] = yscale turtle.setworldcoordinates(xmin,ymin,xmax,ymax) #turtle.speed(0) #turtle.speed() does nothing w/ turtle.tracer(0,0) turtle.tracer(0,0) drawGrid() #drawGridBorder() turtle.pensize(axisThickness) drawXaxis() drawXtickers() numberXtickers() drawYaxis() drawYtickers() numberYtickers() turtle.pensize(1)
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 setTurtle(self): """Initializes the turtle object and screen object, while also setting the speed to the maximum""" self.t = turtle.Turtle() self.s = turtle.Screen() self.t.speed(0) turtle.tracer(0,0)
def tree1(argv, x, y): lsys_filename1 = argv[1] lsys1 = ls.createLsystemFromFile( lsys_filename1 ) print lsys1 num_iter1 = int( 3 ) dist = float( 5 ) angle1 = float( 22 ) s1 = ls.buildString( lsys1, num_iter1 ) #draw lsystem1 '''this is my first lsystem with filename mysystem1.txt with 3 iterations and with angle = 45 dist = 10''' turtle.tracer(False) turtle.speed(50000000) turtle.up() turtle.goto(0,0) turtle.goto(x, y) turtle.down() turtle.pencolor('White') it.drawString( s1, dist, angle1 ) # wait and update turtle.update()
def foliageRight( x, y, scale): ''' foliage scenery right side of image use tree() and leaf() functions defined earlier to make a variety of size and color foliage using for loops to make multiple''' t.tracer(False) for i in range(5): tree( x+random.randint( 100, 350 )*scale, y+random.randint( -300, -100 )*scale, random.randint( 1, 2 )*scale) for i in range(10): leaf( x+random.randint( 100, 300 )*scale, y+random.randint( -300, -100 )*scale, random.random()*scale, 'red' ) for i in range(10): leaf( x+random.randint( 100, 300 ), y+random.randint( -300, -100 ), random.random()*scale, 'orange' ) for i in range(10): leaf( x+random.randint( 100, 300 )*scale, y+random.randint( -300, -100 )*scale, random.random()*scale, 'yellow' )
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 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 draw_maze(): t.speed(0) turtle.tracer(10, 25) t.pensize(3) t.penup() t.goto(0, 0) t.pendown() t.goto(20 * NC, 0) t.goto(20 * NC, 20 * NR) t.goto(0, 20 * NR) t.goto(0, 0) for i, ns in enumerate(nodes): y1, x1 = points[i] for n in (n for n in ns if n > i): y2, x2 = points[n] t.penup() if n == i + 1: t.goto(20 * x2, 20 * y1) t.pendown() t.goto(20 * x2, 20 * (y1 + 1)) else: t.goto(20 * x1, 20 * y2) t.pendown() t.goto(20 * (x1 + 1), 20 * y2)
def foliageLeft(): ''' foliage scenery left side of image use tree() and leaf() functions defined earlier to make a variety of size and color foliage using for loops to make multiple''' turtle.tracer(False) for i in range(5): tree( random.randint( -300, -100 ), random.randint( -300, -100 ), random.randint( 1, 2 )) for i in range(10): leaf( random.randint( -300, -100 ), random.randint( -300, -100 ), random.random(), 'red' ) for i in range(10): leaf( random.randint( -300, -100 ), random.randint( -300, -100 ), random.random(), 'orange' ) for i in range(10): leaf( random.randint( -300, -100 ), random.randint( -300, -100 ), random.random(), 'yellow' )
def floor( x, y, scale ): t.tracer(False) position1 = [-600, -500, -400, -300, -200, -100, 0, 100, 200, 300, 400, 500] position2 = [-550, -450, -350, -250, -150, -50, 50, 150, 250, 350, 450, 550] for i in range(len(position1)): t.begin_fill() t.color('Black') bsl.buildingblock(x+position1[i]*scale, y-300*scale, 50*scale, 50*scale) t.end_fill() for i in range(len(position1)): t.begin_fill() t.color('Gold') bsl.buildingblock(x+position2[i]*scale, y-300*scale, 50*scale, 50*scale) t.end_fill() for i in range(len(position1)): t.begin_fill() t.color('Gold') bsl.buildingblock(x+position1[i]*scale, y-250*scale, 50*scale, 50*scale) t.end_fill() for i in range(len(position1)): t.begin_fill() t.color('Black') bsl.buildingblock(x+position2[i]*scale, y-250*scale, 50*scale, 50*scale) t.end_fill() for i in range(len(position1)): t.begin_fill() t.color('Black') bsl.buildingblock(x+position1[i]*scale, y-200*scale, 50*scale, 50*scale) t.end_fill() for i in range(len(position1)): t.begin_fill() t.color('Gold') bsl.buildingblock(x+position2[i]*scale, y-200*scale, 50*scale, 50*scale) t.end_fill()
def drawPattern(turt, offx, offy, radius, step): # Points is the number of points per side, NOT including the corner points # Draw lines between the points around teh box in the given pattern # drawRect(turt, offx, offy, sizex, sizey) # Basic rectangle to outline the shape pointsl = drawCricle(turt, offx, offy, radius, step) turtle.tracer(1) for p in range(len(pointsl)): turt.color(getRandColor(cols)) for p2 in range(len(pointsl)-3): if not p+p2+2 > len(pointsl)-1: drawLine(turt, pointsl[p][0], pointsl[p][1], pointsl[p+p2+2][0], pointsl[p+p2+2][1]) else: drawLine(turt, pointsl[p][0], pointsl[p][1], pointsl[p+p2+2 - len(pointsl)][0], pointsl[p+p2+2 - len(pointsl)][1]) turtle.update() # Draw a nice looking border around the rectangle # turt.pensize(10) # Make it thick # drawRect(turt, offx, offy, sizex, sizey) # turt.pensize(1) # Reset pen size turt.penup() turt.setpos(offx, offy) #Sit in the centre of the circle at the end turtle.update()
def sky( x, y, scale ): '''draws a huge blue square given location and scale''' t.tracer(False) t.begin_fill() t.color('light blue') buildingblock(x-1000*scale, y+0*scale, 2000*scale, 1075*scale) t.end_fill()
def grass( x, y, scale ): '''draws a huge blue square given location and scale''' t.tracer(False) t.begin_fill() t.color('green') buildingblock(x-1000*scale, y-1000*scale, 2000*scale, 1075*scale) t.end_fill()
def Run(): #bounds nearRange = [0, 50] farRange = [50, 200] frusHL = 100 #Logic nearDist = random.uniform(nearRange[0], nearRange[1]) farDist = random.uniform(farRange[0], farRange[1]) d = frusHL * 2 an = nearDist af = farDist b = (d*d + af*af - an*an) / (2 * d) radius = math.sqrt(b*b + an*an) originY = -frusHL + b #text.insert('end', 'Origin: %d\n' % originY) #Render turtle.clear() turtle.hideturtle() turtle.tracer(0, 0) turtle.penup() turtle.goto(-farDist, frusHL) turtle.pendown() turtle.goto(-nearDist, -frusHL) turtle.goto(nearDist, -frusHL) turtle.goto(farDist, frusHL) turtle.goto(-farDist, frusHL) turtle.penup() DrawCircle(0, originY, radius); turtle.update()
def extension1(): turtle.tracer(False) for i in range(50): turtle.setheading( random.randint(0,360)) shapelib.parallelogram( random.randint(-350,-250), random.randint(-300, 300), random.random(), 'red') for i in range(50): turtle.setheading( random.randint(0,360)) shapelib.cross( random.randint(-200, -100), random.randint(-300, 300), random.random(), 'yellow') for i in range(50): turtle.setheading( random.randint(0,360)) shapelib.star( random.randint(-50, 50), random.randint(-300, 300), random.random(), 'pink') for i in range(50): turtle.setheading( random.randint(0,360)) shapelib.star( random.randint(100, 200), random.randint(-300, 300), random.random(), 'orange') for i in range(50): turtle.setheading( random.randint(0,360)) shapelib.cross( random.randint(250, 350), random.randint(-300, 300), random.random(), 'green') for i in range(50): turtle.setheading( random.randint(0,360)) shapelib.parallelogram( random.randint(400, 500), random.randint(-300, 300), random.random(), 'blue')
def draw(self, w, h, dot = False): norm = CoordinateNormalizer(self, w, h) window = turtle.Screen() cursor = turtle.Turtle() window.setup(w, h) window.setworldcoordinates(0, 0, w, h) window.delay(0) cursor.ht() turtle.tracer(0) cursor.up() for way in self.getWays(): tags = self.ways[way].tags line = self.getPolyline(way) for (x, y) in line: cursor.pencolor('black') x, y = norm(x, y) cursor.setpos(x, y) if dot: cursor.dot() if not cursor.isdown(): cursor.down() cursor.up() turtle.update() window.exitonclick()
def __init__(self, length=10, angle=90, colors=None, lsystem=None): import turtle self.length = length self.angle = angle if colors is None: self.colors = ['red', 'green', 'blue', 'orange', 'yellow', 'brown'] if lsystem is not None: self.lsystem(lsystem) # draw number self.ith_draw = 0 # origin of next draw self.origin = [0, 0] # bounding_box self._box = 0, 0, 0, 0 # turtle head north and positive angles is clockwise turtle.mode('world') turtle.setheading(90) turtle.speed(0) # fastest turtle.hideturtle() turtle.tracer(0, 1) # set pencolor self.pencolor()
def setup(): turtle.hideturtle() turtle.tracer(1e3,0) turtle.left(90) turtle.penup() turtle.goto(0,-turtle.window_height()/2) turtle.pendown()
def __init__(self, model): """Initialize the view at the starting of the application.""" self.model = model self.cellWidth = self.CELL_WIDTH self.model = model self.gridSize = model.GRID_SIZE self.player = self.model.player1 self.screen = turtle.Screen() self.gridWidth = self.CELL_WIDTH * self.gridSize self.playerGrid = self.player.getGrid(self.player.PLAYER_GRID) self.enemyGrid = self.player.getGrid(self.player.OPPONENT_GRID) self.iconsToDraw = [] turtle.title('BATTLESHIP : {} vs {}'.format( self.model.player1.playerName, self.model.player2.playerName)) self.__setScreen() self.__setColor() turtle.tracer(0, 0) gridWidth = self.gridWidth gridAnchorPoints = [] gridAnchorPoints.append(( -self.width/2 + self.GRID_MARGINLEFT, self.height/2 - self.GRID_MARGINTOP - gridWidth)) gridAnchorPoints.append(( self.width/2 - gridWidth - self.GRID_MARGINRIGHT, self.height/2 - self.GRID_MARGINTOP - gridWidth )) self.__drawGrid(gridAnchorPoints[0], gridWidth) self.__drawGrid(gridAnchorPoints[1], gridWidth) self.gridAnchorPoints = gridAnchorPoints
def __init__(self): self.turtle = turtle.Turtle() self.turtle.hideturtle() self.struct_header = '>III' self.size = 40 self.mh = None self.reset() turtle.tracer(__DEBUG__)
def main(): # 打开/关闭龟动画,并为更新图纸设置延迟。 turtle.tracer(False) Init() SetupClock(160) turtle.tracer(True) Tick() turtle.mainloop()
def drawRect(t, x1, y1, sizex, sizey): # Simply draws a rectangle turtle.tracer(0) # If this is 0, the rectangle is drawn instantly drawLine(t, x1 - sizex/2, y1 - sizey/2, x1 + sizex/2, y1 - sizey/2) # Up drawLine(t, x1 - sizex/2, y1 + sizey/2, x1 + sizex/2, y1 + sizey/2) # Down drawLine(t, x1 - sizex/2, y1 - sizey/2, x1 - sizex/2, y1 + sizey/2) # Left drawLine(t, x1 + sizex/2, y1 - sizey/2, x1 + sizex/2, y1 + sizey/2) # Right turtle.update()
def painting( x, y, scale ): t.tracer(False) t.begin_fill() t.color('Brown') bsl.buildingblock(x-400*scale, y-75*scale, 250*scale, 250*scale) t.end_fill() bsl.myscene2(-275, 50,.10) t.setheading(0)
def main(i): t.speed('fastest'); t.tracer(1,0); t.colormode(255) t.lt(90) while (i >= 1): drawLineOfSqrs(i) i -= 1 raw_input()
def drawleaf(self): turtle.tracer(0) self.turt.color("green") self.turt.pensize(random.randint(5, 10)) self.turt.penup() self.turt.right(random.randint(-20, 20)) self.turt.pendown() self.turt.forward(10)
import lampe import turtle import collections import copy window = turtle.Screen() lines = [] currentLine = [0] colors = ["nothing", "red", "blue", "green", "pink", "yellow", "brown"] code = ["red", "blue", "red", "red"] currentColorSelection = ["", "", "", ""] turtle.tracer(False, 0) for i in range(10): line = [] for j in range(4): l = lampe.Lampe(50 * j - 20, 40 * i - 200, 20, "gray") l.anschalten() line.append([l, 0]) turtle.update() for j in range(2): for k in range(2): l = lampe.Lampe(10 * k - 65, 40 * i + 10 * j - 200, 5, "red") l.anschalten() line.append([l, 0]) turtle.update() lines.append(line) l = lampe.Lampe(250, -180, 40, "blue") l.anschalten()
import turtle as t import string def write(char): def _write(): t.clear() t.write(char, align="center", font=f"Arial {s}") t.update() return _write s = 300 t.hideturtle() t.tracer(False) t.color("red") t.up() t.right(90) t.forward(2 * s // 3) t.down() chars = string.ascii_letters + string.digits for i in range(len(chars)): t.onkey(write(chars[i]), chars[i]) t.listen() t.exitonclick()
import turtle from turtle import * import random import math import time from platform import Platform from player import * import tkinter as tk turtle.setup(900, 800) turtle.tracer(100, 1) turtle.hideturtle() running = True sleep = 0.0077 turtle.pu() screen_width = turtle.getcanvas().winfo_width() // 2 screen_height = turtle.getcanvas().winfo_height() // 2 turtle.register_shape("galaxy.gif") turtle.register_shape("clouds(1).gif") turtle.register_shape("abed.gif") turtle.register_shape("ahmad.gif") turtle.register_shape("kidjumping(1).gif") turtle.register_shape("gal.gif") turtle.register_shape("sadek.gif") turtle.register_shape("background(1).gif") turtle.register_shape("uriel.gif") turtle.register_shape("mahed.gif") turtle.bgpic("background(1).gif") number_of_platforms = 5
"""Sierpinkski's Game, by Al Sweigart [email protected] Sierpinkski's "game" is an algorithm that draws Sierpinski's Triangle with turtle graphics. More info at https://en.wikipedia.org/wiki/Chaos_game""" __version__ = 0 import turtle import random, time turtle.tracer(60, 0) # Make the turtle draw faster. turtle.setworldcoordinates(0, 0, 960, 810) DOT_SIZE = 3 NUMBER_OF_DOTS = 1500 def main(): turtle.bgcolor(0.1, 0.1, 0.1) turtle.penup() while True: # Pick a random color to draw with: redAmount = random.randint(50, 100) / 100.0 greenAmount = random.randint(50, 100) / 100.0 blueAmount = random.randint(50, 100) / 100.0 turtle.pencolor(redAmount, greenAmount, blueAmount) # Pick three random points for the triangle: ax = random.randint(0, 960) ay = random.randint(0, 810) bx = random.randint(0, 960) by = random.randint(0, 810)
import turtle import random turtle.tracer(1, 0) enemy = turtle.clone() enemy.penup() enemy.goto(200, 0) turtle.register_shape("ghost_F.gif") enemy.shape("ghost_F.gif") #enemy.shape("circle") #screan size SIZE_X = 1028 SIZE_Y = 800 turtle.setup(SIZE_X, SIZE_Y) #square size SQUARE_SIZE = 20 #installing arrows UP_ARROW = "Up" DOWN_ARROW = "Down" RIGHT_ARROW = "Right" LEFT_ARROW = "LEFT" TIME_STEP = 100 #lists pos_list = [] enemy_pos_list = [] turtle.penup() UP = 0 DOWN = 1 RIGHT = 2
import turtle import time import random import math from ball import Ball #part 1 create a ball turtle.tracer(0) turtle.hideturtle() turtle_gameover = turtle.clone() runinng = True screen_width = turtle.getcanvas().winfo_width()/2 screen_hight = turtle.getcanvas().winfo_height()/2 turtle.colormode(255) def random_color(): r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) return (r,g,b) my_ball = Ball(100,35,21,23,50,random_color()) number_of_balls = 5 minimum_ball_radius = 10 maximum_ball_radius = 100 minimum_ball_dx = -5 maximum_ball_dx = 5 minimum_ball_dy = -5
import turtle import random turtle.tracer(5) wn = turtle.Screen() wn.bgcolor('blue') #turtle.tracer(5) t = turtle.Turtle('turtle') #t.hideturtle() t.pensize(2) #t.up() clr = [ 'red', 'brown', 'blue', 'pink', 'gold', 'violet', 'navy', 'green', 'firebrick' ] def draw_star(points, size, x, y): t.up() t.goto(x, y) t.down() angle = 180 - (180 / points) t.color(random.choice(clr)) t.begin_fill() for m in range(points): t.fd(size) t.rt(angle) t.end_fill() draw_star(12, 100, 200, -100)
import turtle import random #We'll need this later in the lab turtle.register_shape("Smiley.gif") turtle.bgcolor("black") turtle.tracer(1, 0) #This helps the turtle move more smoothly score_turtle = turtle.clone() score_turtle.hideturtle() score = 0 SIZE_X = 1500 SIZE_Y = 1000 turtle.setup(1500, 1000) #Curious? It's the turtle window #size. turtle.penup() SQUARE_SIZE = 20 START_LENGTH = 6 #Initialize lists pos_list = [] stamp_list = [] food_pos = [] food_stamps = [] UP_EDGE = 500 DOWN_EDGE = -500 RIGHT_EDGE = 750 LEFT_EDGE = -750 #Set up positions (x,y) of boxes that make up the snake snake = turtle.clone() snake.shape("Smiley.gif")
# def draw_circle(ttl): # x = random.randint(-200, 200) #получаем случайные координаты # y = random.randint(-200, 200) # ttl.color('violet') #устанавливаем цвет линии # ttl.penup() # убираем "ручку" от холста, чтобы переместить в нужное место # ttl.setpos(x, y) # перемещаем в "основание" - это будет самая низкая точка # ttl.pendown() #опускаем ручку обратно # ttl.circle(25) #рисуем круг радиуса 25 # def main(): turtle.tracer(0, 0) #устанавливаем все задержки в 0, чтобы рисовалось мгновенно turtle.hideturtle() #убираем точку посередине ttl = turtle.Turtle() #создаём объект черепашки для рисования ttl.hideturtle() #делаем её невидимой while True: time.sleep(0.2) #засыпаем на полсекунды, чтобы увидеть что нарисовали ttl.clear() #очищаем всё нарисованое ранее rectangle.draw() rectangle.random_move(100) triangle.draw() triangle.random_move(100) circle.draw() circle.random_move(20) quadrangle.draw()
import turtle import random import town from town import * turtle.speed( 'fastest' ) turtle.tracer( False ) draw_field( ) num_of_rows = 14 num_of_cols = 14 for r in range( 0, num_of_rows ): for c in range( 0, num_of_cols ): x = ( c - (num_of_cols - 1) / 2 ) * 7 + random.uniform( -1.0, 1.0 ) y = ( r - (num_of_rows - 1) / 2 ) * 7 x_screen, y_screen = world_to_screen( x, y ) size = 3 * world_to_scale( x, y ) type_list = [ 'lex', 'anya' ] house_type = random.choice( type_list ) color_list = [ 'yellow', 'orange', 'red', 'maroon', 'violet', 'magenta', 'navy', 'blue', 'cyan', 'turquoise', 'chocolate', 'gray' ] house_color = random.choice( color_list ) color_list.remove( house_color ) roof_color = random.choice( color_list ) color_list.remove( roof_color ) door_color = random.choice( color_list ) color_list.remove( door_color )
Xh = x - x2 Yh = y - y2 def smooth_r(x2, y2, x, y): # 平滑三阶贝塞尔曲线到相对坐标(x,y) global Xh global Yh te.penup() X_now = te.xcor() + Width / 2 Y_now = Height / 2 - te.ycor() Bezier_3(X_now, Y_now, X_now + Xh, Y_now + Yh, X_now + x2, Y_now + y2, X_now + x, Y_now + y) Xh = x - x2 Yh = y - y2 te.tracer(10) te.setup(Width, Height, 0, 0) te.pensize(1) te.speed(Speed) te.penup() # 图层_2 # time.sleep(20) te.color("black", "#F2F2F2") # 外套 Moveto(61, 462) te.begin_fill() smooth_r(12, -41, 27, -58) curveto_r(-6, -36, 6, -118, 9, -132) curveto_r(-15, -27, -23, -51, -26, -74) curveto_r(4, -66, 38, -105, 65, -149) Horizontal(486)
# Python Intro Turtle Graphics # Python has a rich "library" of functions. # We are going to use "turtle" to do some simple graphics. import turtle from random import randint if __name__ == "__main__": # Setup our drawning surface turtle.setup(800,600) # Sets up the size of the window turtle.Screen() # Turns on the graphics window width = 50 # Create a variable called "width" turtle.tracer(0,0); turtle.pencolor("white") turtle.goto(0,300) # and make it equal to 10 # Do some turtle graphics commands # Notice all commands from the turtle library is prefixed by "turtle." for x in range(0, 1000): turtle.pencolor((randint(0, 255)/255.0, randint(0, 255)/255.0, randint(0, 255)/255.0)) for y in range(0, 360): turtle.forward((x+5)/10) turtle.right(1) turtle.update();
def __init__(self, sid, sname, snickname, cid, auth): # validate student id if STUDENT_ID == '2018123456': print('\n\nInvalid STUDENT_ID!') # student info self.sid = sid self.sname = sname self.snickname = snickname self.cid = cid self.auth = auth # screen dimension self.swidth = 1000 self.sheight = 500 self.margin = 100 # init turtle module self.screen = turtle.Screen() turtle.setup(self.swidth + self.margin * 2, self.sheight + self.margin * 2) turtle.tracer(0, 0) # a tutle for drawing nodes self.turtle_node = turtle.Turtle() self.turtle_node.shape('circle') self.turtle_node.color('navy') self.turtle_node.shapesize(0.4) self.turtle_node.penup() self.turtle_node.ht() # a tutle for drawing paths self.turtle_path = turtle.Turtle() self.turtle_path.color('green') self.turtle_path.ht() # a tutle for drawing texts self.turtle_text = turtle.Turtle() self.turtle_text.ht() self.turtle_text.penup() # texts self.title_text = 'Traveling Salesman Problem' self.name_text = '{} {} ({})'.format(self.sid, self.sname, self.snickname) self.status_text = '' self.menu_text = 'Key: (1) Random (2) Greedy (3) 2-Opt (Q) QUIT' # init path self.path = [] self.path_length = 0 self.path_to_be_uploaded = None # draw timer self.upload_timer = 0 self.draw_timer = 0 # initialize nodes self.download_from_server() # initial drawing self.draw() self.write_texts()
def drawString(self, dstring, distance, angle): """ Interpret the characters in string dstring as a series of turtle commands. Distance specifies the distance to travel for each forward command. Angle specifies the angle (in degrees) for each right or left command. The list of turtle supported turtle commands is: F : forward - : turn right + : turn left [ : save position, heading ] : restore position, heading < : saves color > : restore color g : set color to green y : set color to light yellow r : set color to light red B : set color to brown L : draws a filled in semicircular leaf f : fills in shape n : ends filling in shape R : set color to brightest red possible b : set color to black s : set color to light blue """ stack = [] colorstack = [] for c in dstring: turtle.tracer(False) if c == 'F': turtle.forward(distance) elif c == '+': turtle.left(angle) elif c == '-': turtle.right(angle) elif c == '[': stack.append(turtle.position()) stack.append(turtle.heading()) elif c == ']': turtle.up() turtle.setheading(stack.pop()) turtle.goto(stack.pop()) turtle.down() elif c == 'B': turtle.color('brown') elif c == '<': colorstack.append(turtle.color()[0]) elif c == '>': turtle.color(colorstack.pop()) elif c == 'g': turtle.color((0.15, 0.5, 0.2)) elif c == 'y': turtle.color((0.8, 0.8, 0.3)) elif c == 'r': turtle.color((0.7, 0.2, 0.3)) elif c == 'L': turtle.fill(True) turtle.circle(distance, 180) turtle.fill(False) elif c == 'f': turtle.fill(True) elif c == 'n': turtle.fill(False) elif c == 'R': turtle.color('red') elif c == 'b': turtle.color('black') elif c == 's': turtle.color('lightblue')
def aumenta_velocidade_de_Robertina ( ) : turtle.delay ( 0 ) Robertina.color ( "yellow" ) Robertina.speed ( 9 ) turtle.tracer ( 30, 0 )
def __init__(self, dx=800, dy=800): turtle.setup() turtle.tracer(False)
# Start fill t.color(r.colour) t.pencolor("black") t.begin_fill() # Go to the next three coordinates in order for i in range(1, 4): t.goto(points[i]) # End fill t.end_fill() # Set up turtle t.tracer(0, 0) t.hideturtle() # Create a rectangle r = Rect(-50, 50, 200, 200, "blue", 0) # Game loop while True: # Clear the canvas t.clear() # Draw a rect drawRect(r) # Rotate r
import os import random import turtle turtle.title("Space Wars") turtle.fd(0) turtle.speed(0) turtle.bgcolor("black") turtle.ht() turtle.setundobuffer(1) turtle.tracer(1) class Sprite(turtle.Turtle): *tab*def __init__(self, spriteshape, color, startx, starty): *tab**tab*turtle.Turtle.__init__(self, shape = spriteshape) *tab**tab*self.speed(0) *tab**tab*self.penup() *tab**tab*self.color(color) *tab**tab*self.fd(0) *tab**tab*self.goto(startx, starty) *tab**tab*self.speed = 1 *tab*def move(self): *tab**tab*self.fd(self.speed) *tab**tab*if self. xcor() > 290: *tab**tab**tab*self.setx(290) *tab**tab**tab*self.rt(60) *tab**tab*if self. xcor() < -290: *tab**tab**tab*self.setx(-290) *tab**tab**tab*self.rt(60)
# Maze Game python code import turtle from math import sqrt, acos, pi import random as r # Create a screen screen = turtle.Screen() screen.bgcolor("black") screen.title("Maze Game") screen.setup(800, 800) turtle.setundobuffer(1) #limits the memory to undo. turtle.tracer(0) #update speed # Create a pen class Pen(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self) self.shape("square") self.color("white") self.penup() self.speed(0) # Create objective class Objective(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self) self.shape("circle")
import turtle as tu import math lines = 10 with open("1miopi.txt", "r") as f: pi = f.read() print(pi[0:10]) # gib mir nur die ersten 10 Zeichen wieder der gegebenen Liste print(pi[-10:]) #du sollst anfangen 10 zeichen vor Ende und das ausdrucken tu.mode("logo") tu.tracer(False) tu.screensize(5000, 5000, "black") #tu.pencolor("red") tu.colormode(255) for n in range( lines ): #schritt der wiederholung =n #lines ist definiert, wie oft soll er wiederholen? color = int(n / (lines / 255)) b = color if color < 20: g = 0 else: g = 255 - color if 235 < g < 200: r = 0 else: if color < 240: r = 255 else:
# Arleth Salinas # Lab 4 # August 4, 2019; 10pm # Imports the turtle graphics module import turtle # creates a turtle (pen) an sets the speed (where 0 is fastest and 10 is slowest) # The colors can be set through their names or through hexadecimal codes, use hex for accuracy startingX = -200 startingY = 200 turtle.screensize(200, 200, bg="#FFFFFF") turtle.tracer(60) myPen = turtle.Turtle() myPen.color("#000000") myPen.speed(0) doneDrawing = False # If you would like to slow down the animation, uncomment the next line. Higher delay, the slower it will be #turtle.delay(100) # setting out box sizes to the n sq pixels per box boxSize = 10 #paths of each art piece choices = [ 'art/banana.txt', 'art/blinky.txt', 'art/epic_smiley_face.txt', 'art/mario.txt', 'art/mushroom.txt', 'art/heart.txt', 'art/sushi.txt' ] #names of each art piece choiceNames = [
def main(): """ Main function. """ trt.hideturtle() trt.tracer(0) screen = trt.getscreen() answer = screen.textinput('Welcome!', ru.WELCOME) if answer == '1': data = get_data(100, 20) place('1') sq(data['size'], data['depth']) elif answer == '2': data = get_data(100, 4) place('2') tree(data['size'], data['depth']) elif answer == '3': data = get_data(400, 3) place('3') branch(data['depth'], data['size']) elif answer == '4': data = get_data(500, 3) place('4') koch(data['depth'], data['size']) elif answer == '5': data = get_data(100, 3) place('5') snowflake(data['depth'], data['size']) elif answer == '6': data = get_data(200, 3) place('6') mink(data['depth'], data['size']) elif answer == '7': data = get_data(50, 3) place('7') ice_fractal(data['size'] * 10, data['depth']) elif answer == '8': data = get_data(50, 3) place('7') ice_2fractal(data['size'] * 10, data['depth']) elif answer == '9': data = get_data(150, 3) place('7') ice_snowflake(data['size'], data['depth']) elif answer == '10': data = get_data(20, 7) place('6') lev(data['depth'], data['size']) elif answer == '11': data = get_data(200, 12) place('6') dragon(data['depth'], data['size'], 1) trt.update() trt.mainloop()
def main(): screen = turtle.Screen() turtle.mode('standard') xspan, yspan = screen.screensize() turtle.setworldcoordinates(0, 0, xspan, yspan) # makes the turtle invisible, improves drawing speed turtle.hideturtle() # fastest speed for the drawing turtle.speed('fastest') # no tracing within turtle, improves drawing speed turtle.tracer(0, 0) # turtle pen is off the canvas to start turtle.penup() board = Grid(xspan // SIZE, yspan // SIZE) def flip_state(x, y): x_cell = x // SIZE y_cell = y // SIZE board.flip_state(x_cell, y_cell) board.display() turtle.onscreenclick(turtle.listen) turtle.onscreenclick(flip_state) def clear_board(): board.clear_board() board.display() # binds function to the 'e' key turtle.onkey(clear_board, 'e') # binds function to the 'q' key turtle.onkey(sys.exit, 'q') continuous = False def step_once(): # allows for the rebinding of variables outside of the local scope nonlocal continuous continuous = False perform_step() def step_continuous(): nonlocal continuous continuous = True perform_step() def perform_step(): board.step() board.display() if continuous: # calls function in question after t milliseconds turtle.ontimer(perform_step, 25) # binds functions to the 's' and 'c' keys respectively turtle.onkey(step_once, 's') turtle.onkey(step_continuous, 'c') # prints out the coordinates (keys) of the current live cells def print_live(): board.print_keys() turtle.onkey(print_live, 'p') # draws a Glider in the upper left of the display def draw_glider(): board.glider() board.display() turtle.onkey(draw_glider, '1') # draws a Garden of Eden in the display def draw_garden(): board.garden() board.display() turtle.onkey(draw_garden, '2') # draws a Gosper Glider Gun in the display def draw_glider_gun(): board.glider_gun() board.display() turtle.onkey(draw_glider_gun, '3') # draws a Sparky in the display def draw_sparky(): board.sparky() board.display() turtle.onkey(draw_sparky, '4') # turtle listens for key events turtle.listen() # required last statement in a program using turtle graphics turtle.mainloop()
elif current == ']': heading, position = stack.pop() myturtle.penup() myturtle.goto(position) myturtle.setheading(heading) myturtle.pendown() x = axiom for i in range(5): x = generate(x, rules) # print(x, '\n') t = turtle.Turtle() t.color("white") t.setposition(0, -300) t.color("black") t.pensize(1) t.hideturtle() wn = turtle.Screen() wn.setup(width=0.8, height=0.8, startx=0, starty=0) t.left(90) t.speed(10) turtle.tracer(0, 0) parser(t, x, 25) turtle.update() turtle.getscreen().getcanvas().postscript(file='outputname.eps') wn.exitonclick()
elif memglobal.tipoMem(e) == type([]): lir = lee_memoria(e) aux.append(lee_arreglo(lir)) else: aux.append(lee_memoria(e)) return aux # Descripción: Método de instancia el cual nos indica si el registro de memoria de la funcion esta listo. def registro_listo(self): return stackeje.stack.Peek().rm.ready() def main(): if (len(sys.argv) <= 1): print "No se encuentra archivo." exit(1) else: turtle.title("Raplog - "+sys.argv[1]) cargarArchivo(sys.argv[1]) if permiteEjecutar(): ejecutaCuadruplos() if a: turtle.done() if __name__ == "__main__": # parametros iniciales de trutle turtle.title("Raplog") turtle.speed("normal") turtle.tracer(True) main() turtle.done()
t.circle(30) t.end_fill() def snowflake(): t.pencolor("#ADD8E6") t.goto(random.randint(-500, 500), random.randint(-500, 500)) t.pendown() t.rt(90) for i in range(6): t.fd(10) t.bk(10) t.rt(60) t.penup() if __name__ == "__main__": screen = turtle.Screen() t = turtle.Turtle() turtle.tracer(10000, 0) #main() t.penup() n = 0 while (n == 0): t.penup() for i in range(1000): t.penup() snowflake() t.reset() screen.exitonclick()
# SpaceWare by @TokyoEdTech # Part I : Getting started import os import random import turtle turtle.speed(0) # Set the animations sepeed to the maximum turtle.bgcolor('black') # Change the background color turtle.hideturtle() # hide the default turtle turtle.setundobuffer(1) # This saves memory turtle.tracer(1) # This speeds up drawing turtle.register_shape('fishtank.gif') class Sprite(turtle.Turtle): def __init__(self, spriteshape, color, startx, starty): turtle.Turtle.__init__(self, shape= spriteshape) #self.shape(spriteshape) self.speed(0) self.penup() self.color(color) self.goto(startx, starty) self.speed = 1 def move(self): self.fd(self.speed) class Player(Sprite):
def main(): display_help_window() scr = turtle.Screen() turtle.mode('standard') xsize, ysize = scr.screensize() turtle.setworldcoordinates(0, 0, xsize, ysize) turtle.hideturtle() turtle.speed('fastest') turtle.tracer(0, 0) turtle.penup() board = LifeBoard(xsize // CELL_SIZE, 1 + ysize // CELL_SIZE) # Set up mouse bindings def toggle(x, y): cell_x = x // CELL_SIZE cell_y = y // CELL_SIZE if board.is_legal(cell_x, cell_y): board.toggle(cell_x, cell_y) board.display() turtle.onscreenclick(turtle.listen) turtle.onscreenclick(toggle) board.makeRandom() board.display() # Set up key bindings def erase(): board.erase() board.display() turtle.onkey(erase, 'e') def makeRandom(): board.makeRandom() board.display() turtle.onkey(makeRandom, 'r') turtle.onkey(sys.exit, 'q') # Set up keys for performing generation steps, either one-at-a-time or not. continuous = False def step_once(): nonlocal continuous continuous = False perform_step() def step_continuous(): nonlocal continuous continuous = True perform_step() def perform_step(): board.step() board.display() # In continuous mode, we set a timer to display another generation # after 25 millisenconds. if continuous: turtle.ontimer(perform_step, 25) turtle.onkey(step_once, 's') turtle.onkey(step_continuous, 'c') # Enter the Tk main loop turtle.listen() turtle.mainloop()
import bisect import math import turtle import random maze_data = ((0, 0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 2, 1, 1, 2, 1, 2, 1, 2, 0), (0, 1, 0, 0, 0, 0, 0, 0, 1, 0), (0, 1, 0, 2, 1, 1, 2, 0, 1, 0), (0, 2, 0, 1, 0, 0, 1, 0, 1, 0), (0, 1, 0, 1, 0, 0, 1, 0, 2, 0), (0, 1, 0, 2, 1, 0, 2, 0, 1, 0), (0, 1, 0, 0, 0, 0, 1, 0, 1, 0), (0, 2, 1, 1, 2, 1, 2, 0, 1, 0), (0, 0, 0, 0, 0, 0, 0, 0, 2, 0)) PARTICLE_COUNT = 5000 ROBOT_HAS_COMPASS = False turtle.tracer(50000, delay=0) # turtle.register_shape("dot", ((-3,-3), (-3,3), (3,3), (3,-3))) turtle.register_shape("tri", ((-3, -2), (0, 3), (3, -2), (0, 0))) turtle.speed(0) turtle.title("Importance sampling and resampling") UPDATE_EVERY = 0 DRAW_EVERY = 2 def add_noise(level, *coords): return [x + random.uniform(-level, level) for x in coords] def add_little_noise(*coords): return add_noise(0.02, *coords)
p.seth(0) def tlo(r): p.begin_fill() p.color(kolor_bombki, kolor_bombki) p.circle(r) p.end_fill() def gwiazdka(r): p.begin_fill() p.color(kolor_bombki, kolor_gwiazki) for i in range(5): p.fd(r*2-10) p.rt(180 - 36) p.end_fill() def bombka(r): wysrodkowanie(r) tlo(r) p.lt(90) p.fd(r*2) p.rt(180 - (36/2)) gwiazdka(r) tracer(0) bombka(100) update() mainloop()