Пример #1
0
def hilbert_gen(order, size, pos=t.Vec2D(0, 0), heading=t.Vec2D(0, 1)):

    def draw_hilbert(symbols, order, size):
        if order == 0:
            return
        for symbol in symbols:
            op = operations[symbol]
            yield from op(order-1, size)
    
    def forward(order, size):
        nonlocal pos
        pos += heading * size
        yield pos
    
    def right(order, size):
        nonlocal heading
        heading = heading.rotate(90)
        return
        yield

    def left(order, size):
        nonlocal heading
        heading = heading.rotate(-90)
        return
        yield

    operations = {
        'X': partial(draw_hilbert, 'XFYFX+F+YFXFY-F-XFYFX'),
        'Y': partial(draw_hilbert, 'YFXFY-F-XFYFX+F+YFXFY'),
        'F': forward,
        '+': right,
        '-': left,
    }

    yield from draw_hilbert('X', order, size)
Пример #2
0
    def test_mt(self):
    
        agent = t.Turtle()
        
        # First Quadrant
        expected = t.Vec2D(5, 10)
        geoLib.mt(agent, expected, 20)
        
        self.assertEqual(agent.pos(), expected)
        
        # Second Quadrant
        expected = t.Vec2D(-50, 110)
        geoLib.mt(agent, expected, 20)

        self.assertEqual(agent.pos(), expected)
        
        # Third Quadrant
        expected = t.Vec2D(-10, -20)
        geoLib.mt(agent, expected, 20)

        self.assertEqual(agent.pos(), expected)
        
        # Fourth Quadrant
        expected = t.Vec2D(20, -120)
        geoLib.mt(agent, expected, 20)

        self.assertEqual(agent.pos(), expected)
Пример #3
0
class TurtleState:

    currentPosition = turtle.Vec2D(0, 0)
    currentAttitude = turtle.Vec2D(
        1, 0)  # Represents an angle in a nice computable way
    currentPenState = PenState.DOWN

    def move(self, distance: int):
        logging.info("simulating move {0}".format(distance))

        self.currentPosition = self.currentPosition + distance * self.currentAttitude

    def turn(self, angle: int):
        logging.info("simulating turn {0} degree".format(angle))

        self.currentAttitude = self.currentAttitude.rotate(angle)

    def penup(self):
        logging.info("simulating pen UP")
        self.currentPenState = PenState.UP

    def pendown(self):
        logging.info("simulating pen DOWN")
        self.currentPenState = PenState.DOWN

    # Adding these to complete the model with a minimum of useful functions
    def home(self):
        logging.info("simulating going home")
        self.currentPosition = turtle.Vec2D(0, 0)
        self.currentAttitude = turtle.Vec2D(1, 0)
Пример #4
0
def _letter_to_baseline_coords(letter, height, base_xy, base_heading):
    """rotate letter points to match a baseline 
    Users should not typically have to access this helper function,
    as text() will rotate text to match the base_heading"""
    # lower left corner "normalized" to height 1
    xmin, ymin = letter.get_start_delta(1)
    letter_points = []
    # this all could probably be done much more concisely,
    # but it helped me to debug it to break it down into steps
    for point in letter.data:
        # the "raw" letter data
        x, y = point
        # translate to have lower-left at (0,0)
        lx = x - xmin
        ly = y
        # rotate it
        xy = turtle.Vec2D(lx, ly).rotate(base_heading)
        # translate to the start position
        delta_left = letter.get_delta_left(1)
        width = letter.get_width(1)
        xy += turtle.Vec2D(xmin + delta_left, 0).rotate(base_heading)
        # now with height
        hxy = turtle.Vec2D(*xy) * height
        # translate along the baseline
        tx, ty = turtle.Vec2D(*hxy) + turtle.Vec2D(*base_xy)
        letter_points.append((tx, ty))
    return letter_points
Пример #5
0
    def goto(self, x, y=None):
        __doc__ = turtle.Turtle.goto.__doc__

        if y is None:
            self._goto(turtle.Vec2D(*x))
        else:
            self._goto(turtle.Vec2D(x, y))
Пример #6
0
 def test_dist(self):
     
     vec1 = t.Vec2D(0, 0)
     vec2 = t.Vec2D(3, 4)
     
     actual = geoLib.dist(vec1, vec2)
 
     self.assertEqual(round(actual, 2), 5.00)
Пример #7
0
    async def goto(self, x, y=None):
        __doc__ = turtle.Turtle.goto.__doc__

        with (await self.lock):
            if y is None:
                await self._goto(turtle.Vec2D(*x))
            else:
                await self._goto(turtle.Vec2D(x, y))
Пример #8
0
    def drawarrow(self, end, start=None):
        startvec = turtle.Vec2D(*start) if start is not None else t.pos()
        endvec = turtle.Vec2D(*end)
        lineend = endvec + (startvec - endvec) * (self.pensize() /
                                                  abs(startvec - endvec))

        self.drawline(lineend, start)
        arrowhead = self.drawarrowhead(end, self.heading(), self.pencolor())
        arrowhead.showturtle()
Пример #9
0
def draw_tri(origin, size, angle):
    cur_point = t.Vec2D(*origin)
    orientation = t.Vec2D(1, 0).rotate(angle)
    goto(*cur_point)
    cur_point += orientation * size
    lineto(*cur_point)
    cur_point += orientation.rotate(-120) * size
    lineto(*cur_point)
    lineto(*origin)
Пример #10
0
 def __init__(self, switch, coords):
     if switch == 0:
         self.pos = turtle.Vec2D(random.randrange(-200, 201),
                                 random.randrange(-200, 201))
     elif switch == 1:
         self.pos = turtle.Vec2D(coords[0], coords[1])
     tf.draw_point(turk, self.pos, Location.count)
     send_to_console(right_text,
                     "Loc %r pos: %r \n" % (Location.count, self.pos))
     Location.count += 1
Пример #11
0
    def test_mv_team(self):

        # Define the team of agents.
        upperRight = t.Turtle()
        lowerRight = t.Turtle()
        lowerLeft = t.Turtle()
        upperLeft = t.Turtle()

        agents = [upperRight, lowerRight, lowerLeft, upperLeft]

        geolib.hide_all(agents)
        geolib.set_speed(agents)

        # Define their starting positions
        origins = [
            t.Vec2D(300, 300),
            t.Vec2D(300, -300),
            t.Vec2D(-300, -300),
            t.Vec2D(-300, 300)
        ]
        dests = [
            t.Vec2D(300, -300),
            t.Vec2D(-300, -300),
            t.Vec2D(-300, 300),
            t.Vec2D(300, 300)
        ]

        # Move.
        geolib.mv_team(agents, origins, dests, 5)
Пример #12
0
 def __init__(self, tshape, tcolor, x, y):
     t.Turtle.__init__(self)
     self.penup()
     self.speed(0)
     self.shape(tshape)
     self.shapesize(stretch_wid=0.6, stretch_len=1.1, outline=None)
     self.color(tcolor)
     self.r = 3.0
     self.speed = 1
     self.max_speed = 4.0
     self.max_force = 0.1
     self.acceleration = t.Vec2D(0, 0)
     self.velocity = t.Vec2D(0, 0)
     self.location = t.Vec2D(x, y)
Пример #13
0
 def test_pa(self):
 
     agent = t.Turtle()
     expected = t.Vec2D(5, 10)
     geoLib.pa(agent, expected)
     
     self.assertEqual(agent.pos(), expected)
Пример #14
0
 def _draw_letter(self, letter_obj, spacing):
     """Draw a letter object 
     It is recommended to use text() 
     rather than this helper function for most cases
     (You can call text() with a single character, if you like)
     """
     base_heading = self.heading()
     xy_start = self.position()
     segment_length = letter_obj.get_width(self.text_height) + spacing
     self.penup()
     p_data = _letter_to_baseline_coords(letter_obj, self.text_height,
                                         xy_start, base_heading)
     for i, p in enumerate(p_data):
         # The first move positions the turtle for writing the character
         # (which may not start at the current position)
         # so do not put the pen down on the first move.
         # For a space character, there is a special case to not put the
         # pen down.
         if i > 0 and not letter_obj.is_space:
             self.pendown()
         self.head_to(*p)
     self.penup()
     xy_start += turtle.Vec2D(segment_length, 0).rotate(base_heading)
     self.head_to(*xy_start)
     self.setheading(base_heading)
Пример #15
0
class TurtleState(typing.NamedTuple):
    """
    Immutable public State
    """
    position: turtle.Vec2D = turtle.Vec2D(0, 0)
    angle: int = 1 * ureg.degrees  # pint and types ???
    pen: PenState = PenState.DOWN
Пример #16
0
def draw_grid(turt, size):
    """ supply turtle and size - produces
        cartesian coordinate grid with red
        central axis, and coord labels """
    turt.ht()
    corner_list = [
        turtle.Vec2D(-size / 2, -size / 2),
        turtle.Vec2D(size / 2, -size / 2),
        turtle.Vec2D(size / 2, size / 2),
        turtle.Vec2D(-size / 2, size / 2)
    ]  # set coords
    # outer grid
    turt.goto(corner_list[0])  # goto start
    turt.pd()
    turt.color("white")
    turt.write(turt.position(), True, align="right")
    for i in range(1, 4):
        turt.goto(corner_list[i])
        if i == 3:
            turt.write(turt.position(), True, align="right")
        else:  # reallign text for right side
            turt.pu()
            turt.write(turt.position(), True, align="left")
        turt.pu()
        turt.goto(corner_list[i])  # reallign after writing
        turt.pd()

    turt.goto(corner_list[0])  # back to start
    # inner grid
    for j in range(2):
        turt.pd()
        turt.forward(size / 4)
        turt.left(90)
        turt.forward(size)
        turt.right(90)
        turt.forward(size / 4)
        turt.right(90)
        turt.color("red")
        turt.forward(size)
        turt.left(90)
        turt.color("white")
        turt.forward(size / 4)
        turt.left(90)
        turt.forward(size)
        turt.pu()
        if j == 0:
            turt.goto(corner_list[1])
Пример #17
0
class TurtleState:

    # Immutable state
    state = (turtle.Vec2D(0, 0), turtle.Vec2D(1, 0), PenState.DOWN)

    @property
    def position(self):
        return self.state[0]

    @property
    def attitude(self):
        return self.state[1]

    @property
    def penState(self):
        return self.state[2]

    # Note : using self is how we pass the state(=instance) around in python !
    def move(self, distance: int):
        endPosition = self.position + distance * self.attitude

        # mutating the state(=instance)
        self.state = (endPosition, self.attitude, self.penState)
        return self

    def turn(self, angle: int):
        # mutating the state(=instance)
        self.state = (self.position, self.attitude.rotate(angle),
                      self.penState)
        return self

    def penup(self):
        # mutating the state(=instance)
        self.state = (self.position, self.attitude, PenState.UP)
        return self

    def pendown(self):
        # mutating the state(=instance)
        self.state = (self.position, self.attitude, PenState.DOWN)
        return self

    # Adding these to complete the model with a minimum of useful functions
    def home(self):
        # mutating the state(=instance)
        self.state = (turtle.Vec2D(0, 0), turtle.Vec2D(1, 0), self.penState)
        return self
Пример #18
0
def draw_tri_filled(origin, size, angle):
    origin = t.Vec2D(*origin)
    spacing = pen_width
    corner = t.Vec2D(1, 0).rotate(angle - 30)
    goto(*origin)
    while size > spacing:
        cur_point = t.Vec2D(*origin)
        orientation = t.Vec2D(1, 0).rotate(angle)
        lineto(*cur_point)
        cur_point += orientation * size
        lineto(*cur_point)
        cur_point += orientation.rotate(-120) * size
        lineto(*cur_point)
        lineto(*origin)

        size -= 2 * spacing * SQRT_3
        origin += corner * spacing * 2
Пример #19
0
 def legit_route(self, x, y):
     if snake.hard_mode is True and not self.check_if_inside_border():
         return False
     given_position = turtle.Vec2D(x, y)
     for position in self.route[0:len(self.route) - 1]:
         if given_position == position:
             return False
     else:
         return True
Пример #20
0
 def check_if_apple(self):
     apple_position = turtle.Vec2D(self.apple_x, self.apple_y)
     if self.position() == apple_position:
         self.snake_length += 1
         self.score += 1
         self.apple.clearstamp(self.apple_stamp)
         self.place_apple()
         return True
     else:
         return False
Пример #21
0
class TurtleState:
    _position = turtle.Vec2D(0, 0)
    _attitude = turtle.Vec2D(1, 0)
    _penState = PenState.DOWN

    # Read-only state
    @property
    def position(self):
        return self._position

    @property
    def attitude(self):
        return self._attitude

    @property
    def penState(self):
        return self._penState

    # Note : using self is how we pass the state(=instance) around in python !
    def move(self, distance: int):
        endPosition = self.position + distance * self.attitude

        # mutating the state(=instance)
        self._position = endPosition

    def turn(self, angle: int):

        # mutating the state(=instance)
        self._attitude = self.attitude.rotate(angle)

    def penup(self):
        logging.info("simulating pen UP")
        self._penState=PenState.UP

    def pendown(self):
        logging.info("simulating pen DOWN")
        self._penState=PenState.DOWN

    # Adding these to complete the model with a minimum of useful functions
    def home(self):
        logging.info("simulating going home")
        self._position=turtle.Vec2D(0, 0)
        self._attitude=turtle.Vec2D(1, 0)
Пример #22
0
def draw_grid(turt, size):
    turt.ht()
    """ supply turtle and size - produces
        square of width/length = size
        with 0,0 at centre """
    corner_list = [
        turtle.Vec2D(-size / 2, -size / 2),
        turtle.Vec2D(size / 2, -size / 2),
        turtle.Vec2D(size / 2, size / 2),
        turtle.Vec2D(-size / 2, size / 2)
    ]  # set coords
    # outer grid
    turt.goto(corner_list[0])  # goto start
    turt.pd()
    turt.color("white")
    turt.write(turt.position(), True, align="right")
    for i in range(1, 4):
        turt.goto(corner_list[i])
        turt.write(turt.position(), True, align="right")
        turt.pu()
        turt.goto(corner_list[i])  # reallign after writing
        turt.pd()
    turt.goto(corner_list[0])  # back to start
    # inner grid
    for j in range(2):
        turt.pd()
        turt.forward(size / 4)
        turt.left(90)
        turt.forward(size)
        turt.right(90)
        turt.forward(size / 4)
        turt.right(90)
        turt.color("red")
        turt.forward(size)
        turt.left(90)
        turt.color("white")
        turt.forward(size / 4)
        turt.left(90)
        turt.forward(size)
        turt.pu()
        if j == 0:
            turt.goto(corner_list[1])
Пример #23
0
def draw_shape(agent, num_edges, radius, start_point=t.Vec2D(0, 0)):

    side_len = calc_side_len(num_edges, radius)

    vertex_angle = calc_vertex_angle(num_edges)

    # Go to first vertex
    # geolib.pa(agent, start_point + t.Vec2D(radius, 0))

    for i in range(num_edges):
        # Turn
        agent.lt(math.pi - vertex_angle)
        agent.fd(side_len)
def intro():
    pen = turtle.Turtle()
    pen.hideturtle()
    pen.penup()
    pen.color("blue")
    pen.goto(
        turtle.Vec2D(-sc.window_width() // 2 + 200,
                     sc.window_height() // 2 - 200))
    pen.write(text["welcome"], font=font_title)

    time.sleep(sleep_time)
    picture = turtle.Turtle()
    picture.shape("icon.gif")

    time.sleep(sleep_time)
    pen.goto(
        turtle.Vec2D(-sc.window_width() // 2 + 200,
                     -sc.window_height() // 2 + 100))
    pen.color("black")
    pen.write(text["next"], font=font)

    sc.onkeypress(next_slide, "space")
    sc.listen()
Пример #25
0
def make_square(agents, x_dim, y_dim, steps):

    # Origins are the corners of which the turtles start.
    origins = [t.Vec2D(x_dim, y_dim), t.Vec2D(x_dim, -1 * y_dim), t.Vec2D(-1 * x_dim, -1 * y_dim), t.Vec2D(-1 * x_dim, y_dim)]

    # Destinations are the same as origins but shifted one to the left.
    dests= [t.Vec2D(x_dim, -1 * y_dim), t.Vec2D(-1 * x_dim, -1 * y_dim), t.Vec2D(-1 * x_dim, y_dim), t.Vec2D(x_dim, y_dim)]

    mv_team(agents, origins, dests, steps)
Пример #26
0
def hilbert_gen(order, size, pos=t.Vec2D(0, 0), heading=t.Vec2D(0, 1)):
    inc = size / ((2 ** (order-1)) - 1)

    def draw_hilbert(symbols, order):
        if order == 0:
            return
        for symbol in symbols:
            op = operations[symbol]
            yield from op(order-1)
    
    def forward(order):
        nonlocal pos
        pos += heading * inc 
        yield pos
    
    def right(order):
        nonlocal heading
        heading = heading.rotate(90)
        return
        yield

    def left(order):
        nonlocal heading
        heading = heading.rotate(-90)
        return
        yield

    operations = {
        'A': partial(draw_hilbert, '-BF+AFA+FB-'),
        'B': partial(draw_hilbert, '+AF-BFB-FA+'),
        'F': forward,
        '+': right,
        '-': left,
    }

    yield from draw_hilbert('A', order)
def draw_sun():
    t.pendown()
    pos = t.Vec2D(-220, 120)
    abs_default = abs(pos)
    t.goto(pos)
    t.color('red', 'yellow')
    t.begin_fill()

    while True:
        t.forward(200)
        t.left(130)

        abs_current = abs(t.pos())
        if abs_current < abs_default + 1 and abs_current > abs_default - 1:
            # if int(curPos[0]) == -219 and int(curPos[1]) == 119:
            break
    t.end_fill()
    t.penup()
    def outOfBounds(self, screen):
        '''
        screen : 2D canvas where the turtle draw and roam around
        '''

        #Establishing the canvas boundaries
        leftBound = -screen.window_width() / 2
        rightBound = screen.window_width() / 2
        topBound = screen.window_height() / 2
        bottomBound = -screen.window_height() / 2

        turtleX = self.xcor()
        turtleY = self.ycor()
        location = self.pos()
        origin = turtle.Vec2D(0, 0)
        #When turtle reaches boundary based on its coordinates \ make it turn around and move forward back to the canvas
        if turtleX > rightBound or turtleX < leftBound and turtleY > topBound or turtleY < bottomBound:
            self.undo()
            angle = Vec2DExpansion().findAngle(location, origin)
            self.setheading(angle)
            self.forward(100)
Пример #29
0
def sierpinski(coord, degree, myTurtle):

    drawRectangle(coord, colours[degree], myTurtle)

    if degree > 0:
        origin = coord[0] * (2 / 3
                             )  # vectors multiply by a scalar, but not divide

        coord = [point * (1 / 3) for point in coord
                 ]  # new rectangle is 1/3 size of old rectangle

        width, height = coord[2] - coord[0]  # vector subtraction

        for y in range(3):
            for x in range(3):
                if x == 1 == y:
                    continue  # leave hole in the center

                offset = origin + turtle.Vec2D(width * x, height * y)

                sierpinski([offset + point for point in coord], degree - 1,
                           myTurtle)
Пример #30
0
if __name__ == '__main__':
    t.tracer(500)
    t.setworldcoordinates(0, 8, 8, 0)
    t.hideturtle()

    ad = axidraw.AxiDraw()
    ad.interactive()
    ad.options.const_speed = True
    ad.connect()
    ad.pendown()

    order = 6
    size = .032
    # size = 100 / (2 ** order) - 2
    # 2 8 26
    points_gen = hilbert_gen(order, size, heading=t.Vec2D(1, 0))
    rx = random.uniform(-1, 1)
    ry = random.uniform(-1, 1)
    for (x, y) in points_gen:
        # weight = get_weight(x, y) * size * 2
        # rx = lerp(rx, random.uniform(-1, 1), 0.6)
        # ry = lerp(ry, random.uniform(-1, 1), 0.6)
        # x += weight*rx
        # y += weight*ry
        t.goto(x, y)
        t.update()
        ad.goto(x, y)

    t.update()
    t.done()