示例#1
0
def main():
  ap = ArgumentParser()
  ap.add_argument('--speed', type=int, default=10,
                  help='Number 1-10 for drawing speed, or 0 for no added delay')
  ap.add_argument('program')
  args = ap.parse_args()

  for kind, number, path in parse_images(args.program):
    title = '%s #%d, path length %d' % (kind, number, path.shape[0])
    print(title)
    if not path.size:
      continue
    pen_up = (path==0).all(axis=1)
    # convert from path (0 to 65536) to turtle coords (0 to 655.36)
    path = path / 100.
    turtle.title(title)
    turtle.speed(args.speed)
    turtle.setworldcoordinates(0, 655.36, 655.36, 0)
    turtle.pen(shown=False, pendown=False, pensize=10)
    for i,pos in enumerate(path):
      if pen_up[i]:
        turtle.penup()
      else:
        turtle.setpos(pos)
        turtle.pendown()
        turtle.dot(size=10)
    _input('Press enter to continue')
    turtle.clear()
  turtle.bye()
示例#2
0
   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)
示例#3
0
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():
    t.setworldcoordinates(0,0,
        WINDOW_WIDTH, WINDOW_HEIGHT)
    t.up()
    t.setheading(90)
    t.forward(75)
    t.title('Typography:Name')
 def __init__(self, T, lmbda, mu, speed=6, costofbalking=False):
     ##################
     bLx = -10 # This sets the size of the canvas (I think that messing with this could increase speed of turtles)
     bLy = -110
     tRx = 230
     tRy = 5
     setworldcoordinates(bLx,bLy,tRx,tRy)
     qposition = [(tRx+bLx)/2, (tRy+bLy)/2]  # The position of the queue
     ##################
     self.costofbalking = costofbalking
     self.T = T
     self.completed = []
     self.balked = []
     self.lmbda = lmbda
     self.mu = mu
     self.players = []
     self.queue = Queue(qposition)
     self.queuelengthdict = {}
     self.server = Server([qposition[0] + 50, qposition[1]])
     self.speed = max(0,min(10,speed))
     self.naorthreshold = False
     if type(costofbalking) is list:
         self.naorthreshold = naorthreshold(lmbda, mu, costofbalking[1])
     else:
         self.naorthreshold = naorthreshold(lmbda, mu, costofbalking)
     self.systemstatedict = {}
def init_board():
    board = turtle.Turtle()
    wn = turtle.Screen()
    turtle.setworldcoordinates(-400,-400,400,400)
    wn.bgcolor('green')
    board.ht()
    board.speed(0)
    board.pensize(4)
    board.pencolor('black')

    coordinate = [[-300,-400,90,None,800],
		  [-200,-400,None,None,800],
		  [-100,-400,None,None,800],
		  [0,-400,None,None,800],
		  [100,-400,None,None,800],
		  [200,-400,None,None,800],
		  [300,-400,None,None,800],
		  [-400,-300,None,90,800],
		  [-400,-200,None,None,800],
		  [-400,-100,None,None,800],
		  [-400,0,None,None,800],
		  [-400,100,None,None,800],
		  [-400,200,None,None,800],
		  [-400,300,None,None,800]]
		  
    for i in range(14):
        X=0
        Y=1
        LEFT=2
        RIGHT=3
        FORWARD=4
示例#7
0
 def __init__(self, world_size, beacons):
     self.beacons = beacons
     self.width = int(world_size)
     self.height = int(world_size)
     turtle.setworldcoordinates(0, 0, self.width, self.height)
     self.update_cnt = 0
     self.one_px = float(turtle.window_width()) / float(self.width) / 2
def regression():
    filename = input("Please provide the name of the file including the extention: ")
    while not (os.path.exists(filename)):
        filename = input("Please provide a valid name for the file including the extention: ")
    ds = []
    file = open(filename)

    for line in file:
        coordinates = line.split()
        x = float(coordinates[0])
        y = float(coordinates[1])
        point = (x, y)
        ds.append(point)
    my_turtle = turtle.Turtle()
    turtle.title("Least Squares Regression Line")

    turtle.clearscreen()
    xmin = min(getXcoords(ds))
    xmax = max(getXcoords(ds))
    ymin = min(getYcoords(ds))
    ymax = max(getYcoords(ds))
    xborder = 0.2 * (xmax - xmin)
    yborder = 0.2 * (ymax - ymin)
    turtle.setworldcoordinates(xmin - xborder, ymin - yborder, xmax + xborder, ymax + yborder)
    plotPoints(my_turtle, ds)
    m, b = leastSquares(ds)
    print("The equation of the line is y=%fx+%f" % (m, b))
    plotLine(my_turtle, m, b, xmin, xmax)
    plotErrorBars(my_turtle, ds, m, b)
    print("Goodbye")
示例#9
0
    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)
示例#10
0
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)
示例#11
0
	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 )
示例#12
0
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)
示例#13
0
	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"
示例#14
0
def init():
    """
    sets the window size and the title of the program
    """
    t.setworldcoordinates(0, 0, WINDOW_LENGTH, WINDOW_HEIGHT)
    t.title('Forest')
    t.up()
    t.forward(100)
示例#15
0
    def __init__(self, dim_x, dim_y, maze):
        # 'maze' is a list of pairs of points, which represent the endpoints
        # of each line segment.
        self.maze = maze

        self.dim_x = dim_x
        self.dim_y = dim_y

        turtle.setworldcoordinates(0, 0, self.dim_x, self.dim_y)
        self.update_cnt = 0
示例#16
0
def init():
    turtle.setworldcoordinates(-WINDOW_WIDTH / 2, -WINDOW_WIDTH / 2,
                               WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)
    turtle.up()
    turtle.setheading(0)
    turtle.hideturtle()
    turtle.title('Snakes')
    turtle.showturtle()
    turtle.setx(-225)
    turtle.speed(0)
示例#17
0
def init():
    """
    Initialize the canvas
    :pre: relative (0,0), heading east, up
    :post: relative (0,0), heading east, up
    :return: None
    """
    t.setworldcoordinates(-BOUNDARY/2, -BOUNDARY/2, BOUNDARY, BOUNDARY)
    t.title("SQUARES")
    t.speed(0)
示例#18
0
文件: pi2c.py 项目: mmercedes/18-549
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 __init__(self):
        #Creates display for visualization. 
        self.window = turtle.Screen()
        turtle.setworldcoordinates(-5, -5, 5, 5)
        turtle.speed(0)

        #Initializes ROS and subscribes to particle filter. 
        rospy.init_node('particle_visualizer', anonymous=True)
        rospy.Subscriber('particle_filter', Particle_vector, self.update)

        #Initializes list of particles. 
        self.particles = []
示例#20
0
def _init():
    root = Tk()
    menubar = Menu(root)
    menubar.add_command(label="Save", command=save_image) 
    menubar.add_command(label="Clear", command=_clear)
    root.config(menu=menubar)
    turtle.speed(0)
    turtle.delay(0)
    turtle.setworldcoordinates(-xCoor,-yCoor,xCoor,yCoor)
    turtle.up()
    turtle.setpos(0,0)
    turtle.down()
示例#21
0
def main():
    # eixos
    turtle.setworldcoordinates(-pi,-2,pi,2)
    linha(-pi,0,pi,0)
    linha(0,-2,0,2)
    # inicializa
    turtle.pen(pensize=3, pencolor='red')
    grafico(sin, -pi,pi)
    turtle.pen(pencolor='blue')
    grafico(cos,-pi,pi)
    turtle.hideturtle()
    turtle.exitonclick()
示例#22
0
def init():
    """
    Initialize for drawing, (-500, -250) is in the lower left and
    (500, 500) is in the upper right
    :pre: pos (0,0), heading (east), up
    :pos: pos (0,0), heading (north), up
    :return: None
    """
    t.setworldcoordinates(-WINDOW_WIDTH, -WINDOW_HEIGHT/2, WINDOW_WIDTH, WINDOW_HEIGHT)
    t.left(90)
    t.title('Enhanced Tree')
    t.speed(0)
示例#23
0
def monte_carlo_animado(num_dardos):
    """
    Valor de pi pelo método de Monte Carlo.
    Versão gráfica.
    """
    # prepara a visualização
    turtle.setworldcoordinates(-2,-2,2,2)
    
    janela = turtle.Turtle()
    janela.hideturtle()
    # Desenha os eixos
    janela.up()
    janela.goto(-1,0)
    janela.down()
    janela.goto(1,0)
    
    janela.up()
    janela.goto(0,1)
    janela.down()
    janela.goto(0,-1)
    
    # Desenha circunferência
    janela.up()
    janela.goto(0,-1)
    janela.down()
    janela.circle(1, steps=360)
    
    # Desenha quadrado
    
    quadrado(janela,2,(-1,-1))
  
    
    # vamos aos cálculos
    conta_dardos_in = 0
    janela.up()
    
    for i in range(num_dardos):
        x = random.random()
        y = random.random()
        
        d = (x**2 + y**2)** 0.5
        janela.goto(x,y)
        
        if d <= 1:
            conta_dardos_in = conta_dardos_in + 1
            janela.color("blue")
        else:
            janela.color("red")
        
        janela.dot()   
    res = 4 * (conta_dardos_in / num_dardos)
    return res
示例#24
0
def init():
    """
    Initialize for drawing, (-50, -200) is in the lower left and
    (500, 200) is in the upper right
    :pre: pos (0,0), heading (east), up
    :pos: pos (0,0), heading (east), up
    :return: None
    """
    turtle.setworldcoordinates(-WINDOW_WIDTH/20, -WINDOW_HEIGHT/2,
                               WINDOW_WIDTH/2, WINDOW_HEIGHT/2)
    turtle.up()
    turtle.setheading(0)
    turtle.title('Typography')
    turtle.speed(1)
示例#25
0
def init():
    """
    This function initializes the Position of turtle and sets the window
    co-ordinates
    :pre: pos (0,0), heading (east), up
    :post: pos (-300,-100), heading (east), up
    :return: None
    """
    t.setworldcoordinates(-WINDOW_WIDTH/2, -WINDOW_WIDTH/2,
        WINDOW_WIDTH/2, WINDOW_HEIGHT/2)
    t.up()
    t.setpos(-300,-100)
    t.setheading(0)
    t.title('ForestHome')
def init():
    """
    Initialize for drawing.
    :pre: pos (0,0), heading (east), up
    :post: pos (0,0), heading (east), up
    :return: None
    """

    turtle.setworldcoordinates(-WINDOW_WIDTH/2, -WINDOW_WIDTH/2,
        WINDOW_WIDTH/2, WINDOW_HEIGHT/2)
    turtle.up()
    turtle.setheading(0)
    turtle.title('Typography')
    turtle.speed(0)
示例#27
0
def set_scale(lines,grid=False):
	"""This sets the coordinate scale so that lines will nearly fill
	the window that you're drawing in. It doesn't actually draw anything.
	If grid=True, it will then draw a grid.
	"""
	global lowerleft
	global upperright
	lowerleft = min([min(x0,y0,x1,y1) for ((x0,y0),(x1,y1)) in lines])
	upperright = max([max(x0,y0,x1,y1) for ((x0,y0),(x1,y1)) in lines])
	size = upperright - lowerleft
	margin = size*.1
	turtle.setworldcoordinates(lowerleft-margin,lowerleft-margin,upperright+margin,upperright+margin)
	turtle.pen(speed=10,shown=False)
	if grid: draw_grid(lowerleft,upperright)
示例#28
0
def init():
    """
    Initializing the drawing window.
    :return:
    """
    turtle.title('Recursion Tree Lab 3')  # Giving the window a name
    turtle.setworldcoordinates(-WINDOW_WIDTH, -WINDOW_WIDTH,  # Setting the Coordinates
                               WINDOW_WIDTH, WINDOW_HEIGHT)
    l.hideturtle()
    t.speed(0)
    t.left(90)
    t.penup()
    t.sety(-280)
    t.pendown()
示例#29
0
    def __init__(self, maze):
        self.maze = maze
        self.width   = len(maze[0])
        self.height  = len(maze)
        turtle.setworldcoordinates(0, 0, self.width, self.height)
        self.blocks = []

        self.beacons = []
        for y, line in enumerate(self.maze):
            for x, block in enumerate(line):
                if block:
                    nb_y = self.height - y - 1
                    self.blocks.append((x, nb_y))
                    self.beacons.extend(((x, nb_y), (x+1, nb_y), (x, nb_y+1), (x+1, nb_y+1)))
def init(height):
    '''
    The init method sets the window size based on the user specified height
    and then moved the turtle to the centre of the width and facing north
    :param height: input from the user regarding the approximate height of the tree
    '''
    width=height+5 #adding border to the approximate height
    length=height+5
    t.setworldcoordinates(0, 0, length, width)
    t.up()
    t.forward((width) / 2)
    t.left(90)
    t.forward(15)
    t.speed(0)
示例#31
0
def initBannerCanvas():
    """
    Set up the drawing canvas to draw a banner of 22 characters
    Set a window to fit 1 line for the number of characters
    """
    # The setup function makes the drawing canvas wide and short
    t.setup(1200, 80)

    # Set the world coordinates to start turtle in lower left and match the number of characters.
    # The function setworldcoordinates moves the origin to the lower left
    # with 5 units of margin around where the characters will go
    # setworldcoordinates( -5, -5, 30 * 22 + 5, 30 + 5)
    t.setworldcoordinates(-5, -5, 665, 35)
    t.reset()
    t.up()
    t.pensize(2)
    t.speed(5)
示例#32
0
def main():
    limit = 1
    scale = 150
    iterations = 5000
    sidelength = scale * 2
    count = 0
    radius = limit * scale
#    print(area)
    turtle.tracer(0)
    turtle.setworldcoordinates(-(scale), -(scale), (scale), (scale))
    turtle.hideturtle()

    turtle.penup()
    turtle.goto(0, -(scale))
    turtle.pendown()
    turtle.circle(radius)

    turtle.penup()
    turtle.goto(-(scale), -(scale))
    turtle.pendown()
    turtle.forward(sidelength)
    turtle.left(90)
    turtle.forward(sidelength)
    turtle.left(90)
    turtle.forward(sidelength)
    turtle.left(90)
    turtle.forward(sidelength)
    turtle.left(90)

    bullseye = 0
    while(count <= (iterations)):
        turtle.penup()
        turtle.goto((random.randint(-(scale), (scale))), (random.randint(-(scale), (scale))))
        turtle.pendown()
#        turtle.position()
#        print(turtle.position())
        if math.sqrt(turtle.xcor()**2 + turtle.ycor()**2) <= radius:
            turtle.dot(5,"green")
            bullseye += 1
        else:
            turtle.dot(5,"red")
        count += 1
    turtle.update()
    pi = 4 * bullseye/iterations
    print(pi)
	def show_maze(self):

		turtle.setworldcoordinates(0, 0, self.width * 1.005, self.height * 1.005)
		wally = turtle.Turtle()
		wally.speed(0)
		wally.width(1.5)
		wally.hideturtle()
		turtle.tracer(0, 0)

		for i in range(self.num_rows):
			for j in range(self.num_cols):
				permissibilities = self.permissibilities(cell = (i,j))
				turtle.up()
				wally.setposition((j * self.grid_width, i * self.grid_height))
				# Set turtle heading orientation
				# 0 - east, 90 - north, 180 - west, 270 - south
				wally.setheading(0)
				if not permissibilities[0]:
					wally.down()
				else:
					wally.up()
				wally.forward(self.grid_width)
				wally.setheading(90)
				wally.up()
				if not permissibilities[1]:
					wally.down()
				else:
					wally.up()
				wally.forward(self.grid_height)
				wally.setheading(180)
				wally.up()
				if not permissibilities[2]:
					wally.down()
				else:
					wally.up()
				wally.forward(self.grid_width)
				wally.setheading(270)
				wally.up()
				if not permissibilities[3]:
					wally.down()
				else:
					wally.up()
				wally.forward(self.grid_height)
				wally.up()
		turtle.update()
 def setScreen(self):
     #to view display
     turtle.setworldcoordinates(-350, -340, 450, 300)
     self.c_pop.sort()
     y_max = 500 / self.c_pop[5]
     self.point_list = []
     for x in self.c_pop:
         self.point = int(x * y_max - 300)
         self.point_list.append(self.point)
     turtle.penup()
     turtle.goto(-310, -300)
     turtle.pendown()
     #creating ticks on x_axis at the year between -300 and 250
     x_len = [(-300, 2010), (-190, 2011), (-80, 2012), (30, 2013),
              (140, 2014), (250, 2015)]
     for x, y in x_len:
         turtle.goto(x, -300)
         turtle.goto(x, -295)
         turtle.goto(x, -310)
         turtle.goto(x, -295)
         turtle.penup()
         turtle.goto(x, -320)
         turtle.write(y, align="center")
         turtle.goto(x, -300)
         turtle.pendown()
     turtle.goto(260, -300)
     turtle.penup()
     turtle.goto(-300, -300)
     turtle.left(90)
     turtle.pendown()
     #creating ticks on y-axis for every quarter of 200, labeled by the population respectively
     quarters = [0.25, 0.5, 0.75, 1]
     for i in quarters:
         turtle.goto(-300, 500 * i - 300)
         turtle.write(int(self.c_pop[5] * i), align="right")
         turtle.right(90)
         turtle.forward(10)
         turtle.right(180)
         turtle.forward(20)
         turtle.left(90)
         turtle.right(90)
         turtle.right(180)
         turtle.forward(10)
         turtle.right(90)
     turtle.goto(-300, self.point + 20)
def monte_carlo_animado(num_dardos):
    """
    Valor de pi pelo método de monte Carlo.
    Versão gráfica.
    """
    # prepara a visualização
    turtle.setworldcoordinates(-2, -2, 2, 2)

    janela = turtle.Turtle()
    janela.hideturtle()

    janela.up()
    janela.goto(-1, 0)
    janela.down()
    janela.goto(1, 0)

    janela.up()
    janela.goto(0, 1)
    janela.down()
    janela.goto(0, -1)

    # vamos aos cálculos
    conta_dardos_in = 0
    janela.up()

    for i in range(num_dardos):
        x = random.random()
        y = random.random()

        d = math.sqrt(x**2 + y**2)
        janela.goto(x, y)

        if d <= 1:
            conta_dardos_in = conta_dardos_in + 1
            janela.color("blue")
        else:
            janela.color("red")

        janela.dot()

    janela.exitonclick()

    res = 4 * (conta_dardos_in / float(num_dardos))

    return res
示例#36
0
def init():
    """
    Initialize for drawing.  (-5000, -5000) is in the lower left and
    (5000, 5000) is in the upper right.
    :return: None
    """
    turtle.setworldcoordinates(-WINDOW_WIDTH/2, -WINDOW_WIDTH/2,
        WINDOW_WIDTH/2, WINDOW_HEIGHT/2)
    turtle.up()
    turtle.tracer(0,0)
    turtle.setheading(0)
    turtle.title('Polygons')

    #Setting the position to write team member names
    turtle.goto(2250,4000)
    turtle.write("Rohit Ravishankar", True, align="left",font=("Arial", 16, "normal"))
    turtle.goto(2250,3750)
    turtle.write("Parinitha Nagaraja", True, align="left",font=("Arial", 16, "normal"))
示例#37
0
def initCanvas( wide, high ):
    """
    initCanvas : Natural Natural -> NoneType
    initCanvas creates a square canvas with a coordinate system 
    that has the origin at the top-center of the canvas.
    This is suitable for 'hanging' a mobile.

    pre-conditions: wide and high values should be less than screen size.
    post-conditions: size 2 pen is down at origin, facing South.
    """

    margin = 10
    tt.setup( wide, high )
    tt.clear()
    tt.reset()
    tt.setworldcoordinates( -wide / 2, -high, wide / 2, margin )
    tt.right( 90 )
    tt.pensize( 2 )
def main():
    t = turtle.Turtle()
    s = turtle.Screen()

    s.setup(WIDTH, HEIGHT)
    turtle.setworldcoordinates(0, 0, WIDTH, HEIGHT)

    t.penup()
    t.goto((WIDTH // 10, HEIGHT // 10))
    t.down()

    order = 2

    t.speed("fastest")

    hilbert(t, order, 1, (WIDTH // 5) // order)

    s.exitonclick()
示例#39
0
def lumber():
    t.screensize(800, 800)
    t.setworldcoordinates(0, 0, 800, 800)
    t.write('Harvest and Sort')
    t.up()
    t.fd(680)
    t.down()
    t.write('Harvest Unsorted')
    t.up()
    t.fd(120)
    t.left(90)
    t.fd(50)
    t.left(90)
    t.down()
    t.fd(800)
    t.up()
    t.left(180)
    t.onscreenclick(abc)
def main() -> None:
    """The entrypoint of my scene."""
    colormode(255)
    setworldcoordinates(0, 0, 1000, 1000)
    tracer(0, 0)
    ito: Turtle = Turtle()
    ito.speed(MAX_SPEED)
    major_rectangle(ito, 0, 200, 1000, 800, 65, 107, 165)  # sky
    stars(ito, 100, 10, 40, 0, 200, 1000, 800, 230, 229, 234)  # stars
    cir(ito, 500, 0, 200, 1000, 75, 28, 174, 192, 212)  # darkest clouds
    cir(ito, 500, 0, 275, 1000, 75, 28, 209, 216, 224)  # darker clouds
    cir(ito, 500, 0, 350, 1000, 100, 28, 211, 224, 239)  # light clouds
    major_rectangle(ito, 0, 0, 1000, 200, 91, 102, 42)  # ground
    lines(ito, 4000, 10, 20, 0, 0, 1000, 200, 135, 151, 62)  # grass
    leaves(ito, 800, 500, 800, 100, 325, 40, 94, 109, 75)  # leaves
    wood(ito, 325, 50, 520, 0, 69, 68, 65, 65, 63, 56)  # tree
    update()
    done()
示例#41
0
def main():
    turtle.mode("logo")
    turtle.register_shape('dot', DotShape())
    turtle.pu()
    turtle.setup(SCREEN_SIZE[0], SCREEN_SIZE[1], 0, 0)
    turtle.setworldcoordinates(0, 0, SCREEN_SIZE[0], SCREEN_SIZE[1])
    turtle.setpos(0, 0)
    turtle.pd()
    turtle.setpos(0, SCREEN_SIZE[1])
    turtle.setpos(SCREEN_SIZE[0], SCREEN_SIZE[1])
    turtle.setpos(SCREEN_SIZE[0], 0)
    turtle.setpos(0, 0)
    turtle.ht()
    turtle.pu()
    turtle.setpos(-20, -20)
    Board(auto=False)
    turtle.listen()
    turtle.mainloop()
示例#42
0
def hirst():
    screen.bgcolor("mint cream")

    t.setworldcoordinates(-1, -1, 10, 10)
    turtle.hideturtle()

    def draw_row():
        for i in range(10):
            turtle.dot(15, random.choice(extracted_colors))
            turtle.penup()
            turtle.forward(1)
            turtle.pendown()

    for row in range(10):
        turtle.penup()
        turtle.goto(0, row)
        turtle.pendown()
        draw_row()
示例#43
0
def mset():
    width=300
    height=200
    turtle.speed(0)
    turtle.tracer(0,0)
    turtle.screensize(width,height)
    turtle.setworldcoordinates(0,0,width,height)
    turtle.setpos(0,0)
    turtle.penup()
    image=PNGImage(width,height)
    for col in range(width):
        for row in range(height):
            turtle.setpos(col,row)
            #ADD CODE HERE
            if inmset(c,25):
                turtle.dot()
    turtle.update()
    turtle.done()
示例#44
0
文件: scenery.py 项目: Jcvita/CS1
def main():
    turtle.setworldcoordinates(-1, -1, 1000, 1000)
    turtle.penup()
    turtle.forward(150)
    turtle.pendown()
    draw_tree(50, 200, 50, 'brown', 'green')
    turtle.forward(150)
    house_length = 100
    big_house_height = 150
    small_house_height = 75
    draw_house(house_length, big_house_height, 50, 'blue', 'orange', 'green', 'yellow')
    turtle.forward(150)
    draw_house(house_length, small_house_height, 50, 'red', 'yellow', 'purple', 'green')
    turtle.forward(150)
    draw_tree(30, 150, 75, 'blue', 'pink')
    print("Bigger house area: ", house_length * big_house_height)
    print("Smaller house area: ", house_length * small_house_height)
    print("Press the [x] button on the top of the window to close")
示例#45
0
def screen(xpos, ypos, distance, tps):
    """ Fonction qui adapte la fenêtre affichée à la taille du dessin"""
    import turtle as tt
    Mx = int(max(xpos))
    mx = int(min(xpos))
    My = int(max(ypos))
    my = int(min(ypos))
    xmax = max(Mx, mx)
    ymax = max(My, my)
    Max = int(max(
        xmax, ymax)) + 1  #on définit la valeur de la position la plus éloignée
    tt.setworldcoordinates(
        -Max, -Max, Max,
        Max)  #on réorganise la fenêtre en fonction de cette position
    tt.update()  #on réactualise l'écran
    tt.mainloop(
        tps
    )  #on laisse tourner la tortue pour ne pas faire planter le programme
示例#46
0
    def __init__(self, maze):
        self.maze = maze
        self.width = len(maze[0])
        self.height = len(maze)
        turtle.setworldcoordinates(0, 0, self.width, self.height)
        self.blocks = []
        self.update_cnt = 0
        self.one_px = float(turtle.window_width()) / float(self.width) / 2

        self.beacons = []
        for y, line in enumerate(self.maze):
            for x, block in enumerate(line):
                if block:
                    nb_y = self.height - y - 1
                    self.blocks.append((x, nb_y))
                    if block == 2:
                        self.beacons.extend(((x, nb_y), (x + 1, nb_y),
                                             (x, nb_y + 1), (x + 1, nb_y + 1)))
示例#47
0
def TurtleSetUp(XmotionOJVel, YmotionOJF, Ron, Allen, InitialAngle):
    Ron.speed(1000000)
    Allen.speed(1000000)
    Parameter = 550
    if InitialAngle >= 45:
        turtle.setworldcoordinates(0, 0, Parameter * YmotionOJF / 2,
                                   Parameter * YmotionOJF / 2)
    elif InitialAngle < 45:
        turtle.setworldcoordinates(0, 0, Parameter * XmotionOJF / 2,
                                   Parameter * XmotionOJF / 2)
    Ron.color("white")
    Allen.color("white")
    Ron.left(90)
    Allen.left(90)
    Ron.forward(Parameter * XmotionOJVel / 4)
    Allen.forward(Parameter * XmotionOJVel / 4)
    Ron.right(90)
    Allen.right(90)
示例#48
0
 def draw(self):
     colormode(255)
     setup(self.tk.race_area.width, self.tk.race_area.height)
     setworldcoordinates(0, 0, self.tk.race_area.width,
                         self.tk.race_area.height)
     speed(self.default_speed)
     pensize(3)
     penup()
     pencolor('#333333')
     fillcolor('#66ff66')
     for b in self.tk.barriers:
         self.draw_rct(b)
     pencolor('#333333')
     fillcolor('#ff6666')
     self.draw_rct(self.tk.goal_area)
     for rl in self.rls:
         self.draw_rl(self.tk.start_point, rl)
     done()
示例#49
0
def draw_plotter():
    turtle.setworldcoordinates(-200, -200, 1000, 1000)
    background = turtle.Screen()  #create the background
    background.bgcolor("#005ce6")  #background color

    plot = turtle.Turtle()
    plot.shape("arrow")
    plot.color("red", "white")
    plot.speed(50)
    x = 0
    y = 0
    T = 8  #triangle sides, counter backward
    R = T  #counter forward
    L = 100  #length of side
    h = math.sqrt((L)**2 - (L / 2)**2)  #height small triangle
    n = 0  #level counter
    plot.up()
    #plot.setpos(x+L,y)
    plot.down()
    I = T  #number of interaction

    while I > 0:
        n = n + 1
        while T > 0:
            plot.up()
            plot.setpos(x + L, y)
            plot.down()
            plot.setpos(x, y)
            plot.left(60)
            plot.forward(L)
            plot.right(120)
            plot.forward(L)
            plot.left(60)
            x = x + L
            T = T - 1

        T = R - n
        x = L / 2 * n
        y = h * (n)

        I = I - 1

    background.exitonclick()  #close background
示例#50
0
def initTurtle():
    global sqSize, fontSize
    turtle.setup(1000, 1000, 0, 0)
    turtle.title("Knight's Tour")
    turtle.setworldcoordinates(0, 1000, 1000, 0)
    turtle.ht()
    turtle.pen(pensize=3)
    turtle.speed(0)
    sqSize = turtle.window_height() / (boardSize)
    for r in range(0, boardSize + 1):  #draw horizontal rows
        goto(-2, r * sqSize - 2)
        drto(boardSize * sqSize + 0, r * sqSize - 2)
    for c in range(0, boardSize + 1):  #draw vertical columns
        goto(c * sqSize - 2, 0)
        drto(c * sqSize - 2, boardSize * sqSize + 0)
    if boardSize > 25:
        fontSize = 10
    else:
        fontSize = 16
示例#51
0
def sa_cosine_turtles(bounded):
    turtle.setworldcoordinates(-6.2, -12, 6.2, 12)
    curr_x = [-6.0, 0, +6.0]
    f = lambda x: 10 * math.cos(x)
    count = 3
    demo = [Demo(f) for _ in range(count)]
    x_points = [x * 0.1 for x in range(-62, 62)]
    demo[0].bag(x_points)
    min_x, max_x = bounds(bounded, x_points)
    gens = []
    temperature = 10.0
    step = 0.2
    for i, x in enumerate(curr_x):
        demo[i].start(curr_x[i])
        gens.append(sim_anneal.seek(x, step, f, temperature, min_x, max_x))
    for (x1, y1, t1, j1), (x2, y2, t2, j2), (x3, y3, t3, j3) in zip(*gens):
        demo[0].move(x1, y1, j1)
        demo[1].move(x2, y2, j2)
        demo[2].move(x3, y3, j3)
示例#52
0
def main():
    n = int(input("Enter a number: "))
    print(seq3np1(n))
    upbound = int(input("What would you like the upper bound to be?: "))
    start = range(1, upbound + 1)
    wn = turtle.Screen()
    mike = turtle.Turtle()
    dave = turtle.Turtle()
    turtle.setworldcoordinates(0, 0, 10, 10)
    max_so_far = 0
    for i in (start):
        numit = seq3np1(i)
        if numit > max_so_far:
            max_so_far = numit
            writeTurtle(i, max_so_far, dave)
        print("The number of iterations required for " + str(i) + " is " +
              str(numit))
        graph(start, i, numit, max_so_far, mike)
    wn.exitonclick()
示例#53
0
def init():
    WINDOW_WIDTH = calWindowWidth()
    WINDOW_HEIGHT = 3 * FONT_SIZE + 2 * MARGIN

    turtle.title('Jietong Chen')
    turtle.setup(width=WINDOW_WIDTH,
                 height=WINDOW_HEIGHT,
                 startx=None,
                 starty=None)
    turtle.setworldcoordinates(-MARGIN, -MARGIN - FONT_SIZE,
                               WINDOW_WIDTH - MARGIN,
                               WINDOW_HEIGHT - MARGIN - FONT_SIZE)

    turtle.up()
    turtle.color(FONT_COLOR)
    turtle.pensize(FONT_THICKNESS)
    turtle.speed(0)
    turtle.hideturtle()
    turtle.bgcolor(BG_COLOR)
示例#54
0
    def draw_maze(self):
        # Initialise Window with its attributes
        turtle.title("Pokemon Maze")
        window = turtle.Screen()
        turtle.setworldcoordinates(0, 0, self.width + 0.5, self.height + 0.5)
        window.bgcolor("white")

        # Initialise my drawing Turtle
        drawingTurtle = turtle.Turtle()
        drawingTurtle.speed(0)
        for x in range(1, self.width + 1):
            for y in range(1, self.height + 1):
                drawingTurtle.penup()
                drawingTurtle.setpos(x - 1, y - 1)
                cell = self.cells[x][y]
                if cell.south:
                    drawingTurtle.pendown()
                else:
                    drawingTurtle.penup()
                drawingTurtle.setpos(drawingTurtle.xcor() + 1, drawingTurtle.ycor())
                if cell.east:
                    drawingTurtle.pendown()
                else:
                    drawingTurtle.penup()
                drawingTurtle.setpos(drawingTurtle.xcor(), drawingTurtle.ycor() + 1)
                if cell.north:
                    drawingTurtle.pendown()
                else:
                    drawingTurtle.penup()
                drawingTurtle.setpos(drawingTurtle.xcor() - 1, drawingTurtle.ycor())
                if cell.west:
                    drawingTurtle.pendown()
                else:
                    drawingTurtle.penup()
                drawingTurtle.setpos(drawingTurtle.xcor(), drawingTurtle.ycor() - 1)
        drawingTurtle.color("blue")
        for x in range(0,len(self.pokes_locations)):
            drawingTurtle.penup()
            drawingTurtle.setposition(self.pokes_locations[x].x + 0.5, self.pokes_locations[x].y + 0.5)
            drawingTurtle.pendown()
            drawingTurtle.dot(10)
        drawingTurtle.penup()
        drawingTurtle.setposition(0,0)
示例#55
0
def draw_square():
    turtle.setworldcoordinates(-300, -300, 600, 600)
    background = turtle.Screen() #create the background
    background.bgcolor ("#084B8A") #background color
    titi = turtle.Turtle()  #titi is an intance of Turtle class
    titi.shape("arrow")
    titi.color("#084B8A","grey")
    titi.speed(200)
    toto = turtle.Turtle()  #titi is an intance of Turtle class
    toto.shape("arrow")
    toto.color("#084B8A","red")
    toto.speed(200)
    
    
    s = 5  #number of polygon sides
    factor_ang = 7
    n = s #counter
    x = 36 # counter of polygons
    d = 360/s #degrees in angle
    ang_obtuso = 360/factor_ang
    ang_agudo = (360-ang_obtuso*2)/2
    
    while x > 0:  #to draw in each degree of a circle
        while s > 0:
            titi.begin_fill()
            titi.left(d)
            titi.forward(95)
            titi.circle(25)
            toto.begin_fill()
            toto.left(d)
            toto.forward(100)
            toto.circle(25)
            s = s - 1
    
        x = x - 1
        s = n
        titi.right(ang_agudo)
        titi.right(ang_obtuso)
        titi.end_fill()
        toto.right(ang_obtuso)
        titi.right(ang_agudo)
        toto.end_fill()
    background.exitonclick() #close background
def main():
    """
    The main function.
    :pre: pos (0,0), heading (east), up
    :post: pos (0,0), heading (east), up
    :return: None
    """
    trees = int(input("How many trees in your forest? "))
    while trees != 1 and trees != 2 and trees != 3 and trees != 4:
        trees = int(input("How many trees in your forest? "))
    house = (input("Is there a house in the forest (yes/no)? "))
    while house != 'yes' and house != 'no':
        house = input("Is there a house in the forest (yes/no)? ")

    init()
    for x in range(0,trees):
        y = random.randint(0,2)
        if y == 0:
            y = pine_tree()
        if y == 1:
            y = maple_tree()
        if y == 2:
            y = bush_tree()
    if house == 'yes' or 'no':
        if house == 'yes':
            nighthouse()
    star(wood, halfwood)
    input("Night is done. Press enter for day")
    turtle.clear()

    turtle.setworldcoordinates(-WINDOW_WIDTH, -WINDOW_WIDTH, WINDOW_WIDTH*2, WINDOW_HEIGHT*2)
    """Initialize for drawing. (-400,-400) is in the lower left and
    (800, 800) is in the upper right.
    :pre: pos (0,0), heading (east), up
    :post: pos (0,0), heading (east), up
    :return: None"""

    dayhouse()
    amount_woods = ((4 * 200) + (2 * (100 * math.cos((45)))))
    print('We have',amount_woods,'units of lumber for building')
    sun(amtwood, halfamtwood)
    input("Day is done. Press enter to quit")
    turtle.bye()
示例#57
0
def fib(currentNum, nextNum, secondNextNum, i, coords):
    turtle.circle(currentNum * 5, 90)
    turtle.circle(currentNum * 5, -90)
    turtle.setworldcoordinates(-coords[0], -coords[1], coords[0], coords[1])
    for i in range(3):
        turtle.forward(currentNum * 5)
        turtle.left(90)
    turtle.right(90)
    turtle.backward(currentNum * 5)
    turtle.right(90)

    coords[0] *= 1.618
    coords[1] *= 1.618

    if i <= iterations:
        return fib(nextNum, secondNextNum, nextNum + secondNextNum, i + 1,
                   coords)
    else:
        return currentNum
示例#58
0
def draw(figurePath,
         filterStrength=1.5,
         fastMode=False,
         resize=1,
         wait=True):  # encapsulation for drawing methods
    t = turtle.Turtle()
    img = getLineFig(figurePath, filterStrength, fastMode,
                     resize)  # function written in  linefig.py
    height, width = img.shape
    turtle.screensize(width, height)
    turtle.setworldcoordinates(0, height, width, 0)
    t.hideturtle()  # to improve speed
    t.speed(0)
    print('\n')
    for x in range(1, width - 1):
        # for each pixel that is black, draw line line to any pixels
        # that is around it and is also black
        for y in range(1, height - 1):
            if img[y, x]:
                goto(t, x, y)
                if img[y, x + 1]:
                    t.goto(x + 1, y)
                    goto(t, x, y)
                if img[y + 1, x]:
                    t.goto(x, y + 1)
                    goto(t, x, y)
                if img[y + 1, x + 1]:
                    t.goto(x + 1, y + 1)
                    goto(t, x, y)
                if img[y + 1, x - 1]:
                    t.goto(x - 1, y + 1)
        # remove the last line. MIGHT NOT WORK ON EVERY MACHINE. Tested on Ubuntu 19.04 with Python 3.7.3
            sys.stdout.write("\033[F")  #back to previous line
            sys.stdout.write("\033[K")  #clear line
            print("Progress: {:.1%}".format(
                ((x - 1) * (height - 2) + y) /
                ((width - 2) * (height - 2))))  # printing the progress
    sys.stdout.write("\033[F")  #back to previous line
    sys.stdout.write("\033[K")  #clear line
    print("done")
    if wait:
        turtle.mainloop()
def visualiza(pontos):
    """
    Valor de pi pelo método de Monte Carlo.
    Versão gráfica.
    """
    # Prepara a visualização
    turtle.setworldcoordinates(-2, -2, 2, 2)
    janela = turtle.Turtle()
    janela.hideturtle()
    # Desenha os eixos
    janela.up()
    janela.goto(-1, 0)
    janela.down()
    janela.goto(1, 0)

    janela.up()
    janela.goto(0, 1)
    janela.down()
    janela.goto(0, -1)
    # Desenha circunferência
    janela.up()
    janela.goto(0, -1)
    janela.down()
    janela.circle(1, steps=360)
    # Desenha quadrado
    janela.up()
    janela.goto(-1, -1)
    janela.down()
    for i in range(4):
        janela.forward(2)
        janela.left(90)
    janela.up()
    # Mostra dardos
    for elem in pontos:
        x, y = elem
        d = (x**2 + y**2)**0.5
        if d <= 1:
            janela.color("blue")
        else:
            janela.color("red")
        janela.goto(x, y)
        janela.dot()
示例#60
0
def initWorld(size):
    """ Initialize the drawing area.

        :param size: integer
                     length of tree trunk to draw
                     (not currently used)
        :pre: size > 0
        :post: coordinate system goes from
               (-2*size, -2*size) at lower-left
                 to (2*size, 2*size) at upper-right.
    """

    turtle.setup(600, 600)

    # The lines below are removed because they keep one from
    # seeing the difference that the size parameter makes
    # in the perceived size of the tree.
    #
    turtle.setworldcoordinates( -2*size - MARGIN, -2*size - MARGIN, \
                                2*size + MARGIN, 2*size + MARGIN)