Пример #1
0
def process(data):
    positions = [pos for pos, vel in data]
    velocities = [vel for pos, vel in data]

    prev_width, prev_height = None, None
    left, top = 0, 0
    best_positions = None

    while True:
        left, right = minmax(x for x, y in positions)
        top, bottom = minmax(y for x, y in positions)

        width, height = right - left, bottom - top

        if prev_width and width > prev_width and prev_height and height > prev_height:
            break
        else:
            prev_width, prev_height = width, height

        best_positions = positions.copy()

        for i, (dx, dy) in enumerate(velocities):
            x, y = positions[i]
            x += dx
            y += dy
            positions[i] = (x, y)

    c = Canvas()
    for x, y in best_positions:
        c.set(x - left, y - top)
    print(c.frame())
def draw(canvas: Canvas, room: Room):
    _TILE_SIZE = Vector2(5, 5)
    for x in range(room.size.x):
        for y in range(room.size.y):
            # draw walls
            # door directions for this tile
            door_directions = []
            for door in room.doors:
                if Vector2(x, y) == door.position:
                    door_directions += [door.direction]
            for i in range(_TILE_SIZE.x):
                for j in range(_TILE_SIZE.y):
                    if x == 0 and Direction.LEFT not in door_directions:
                        canvas.set((room.position.x + x) * _TILE_SIZE.x,
                                   (room.position.y + y) * _TILE_SIZE.y + j)
                    if x == room.size.x - 1 and Direction.RIGHT not in door_directions:
                        canvas.set((room.position.x + x + 1) * _TILE_SIZE.x,
                                   (room.position.y + y) * _TILE_SIZE.y + j)
                    if y == 0 and Direction.TOP not in door_directions:
                        canvas.set((room.position.x + x) * _TILE_SIZE.x +
                                   i, (room.position.y + y) * _TILE_SIZE.y)
                    if y == room.size.y - 1 and Direction.BOTTOM not in door_directions:
                        canvas.set((room.position.x + x) * _TILE_SIZE.x + i,
                                   (room.position.y + y + 1) * _TILE_SIZE.y)
            for i in range(2, _TILE_SIZE.x - 1):
                for j in range(2, _TILE_SIZE.y - 1):
                    canvas.set((room.position.x + x) * _TILE_SIZE.x + i,
                        (room.position.y + y) * _TILE_SIZE.y + j)
Пример #3
0
def make_canvas(matrix):
    canvas = Canvas()
    for r, row in enumerate(matrix):
        for c, val in enumerate(row):
            if val > 127:
                canvas.set(c, r)
    return canvas
Пример #4
0
def image2term(image, threshold=128, ratio=None):
    if image.startswith('http://') or image.startswith('https://'):
        i = Image.open(StringIO(urllib2.urlopen(image).read())).convert('L')
    else:
        i = Image.open(open(image)).convert('L')
    w, h = i.size
    if ratio:
        w = int(w * ratio)
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)
    else:
        tw, th = getTerminalSize()
        tw *= 2
        th *= 2
        if tw < w:
            ratio = tw / float(w)
            w = tw
            h = int(h * ratio)
            i = i.resize((w, h), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0
    for pix in i.tobytes():
        if ord(pix) < threshold:
            can.set(x, y)
        x += 1
        if x >= w:
            y += 1
            x = 0
    return can.frame()
Пример #5
0
def image2term(image, threshold=128, ratio=None, invert=False):
    if image.startswith('http://') or image.startswith('https://'):
        i = Image.open(StringIO(urllib2.urlopen(image).read())).convert('L')
    else:
        i = Image.open(open(image)).convert('L')
    w, h = i.size
    if ratio:
        w = int(w * ratio)
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)
    else:
        tw, th = getTerminalSize()
        tw *= 2
        th *= 2
        if tw < w:
            ratio = tw / float(w)
            w = tw
            h = int(h * ratio)
            i = i.resize((w, h), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0
    for pix in i.tobytes():
        if invert:
            if ord(pix) > threshold:
                can.set(x, y)
        else:
            if ord(pix) < threshold:
                can.set(x, y)
        x += 1
        if x >= w:
            y += 1
            x = 0
    return can.frame(0, 0)
Пример #6
0
def draw_simple_map(stdscr):

    c = Canvas()

    v1 = Point(-20, 20)
    v2 = Point(20, 20)
    v3 = Point(-20, -20)
    v4 = Point(20, -20)

    lines = [
        (v1, v2),
        (v1, v3),
        (v3, v4),
        (v4, v2),
    ]

    for start, end in lines:
        for x, y in line(start.x, start.y, end.x, end.y):
            c.set(x, y)

    df = c.frame(-40, -40, 80, 80)
    stdscr.addstr(1, 0, f"{df}")
    stdscr.refresh()

    sleep(10)
    c.clear()
Пример #7
0
    def render(self, width, height, values):
        """
        :type width: int
        :type height: int
        :type values: list[int or float]
        :rtype: list[str or unicode]
        """
        from drawille import Canvas

        vertical_chart_resolution = height * self.char_resolution_vertical
        horizontal_chart_resolution = width * self.char_resolution_horizontal

        canvas = Canvas()
        x = 0
        for value in values:
            for y in range(1, int(round(value, 0)) + 1):
                canvas.set(x, vertical_chart_resolution - y)
            x += 1

        rows = canvas.rows(min_x=0, min_y=0, max_x=horizontal_chart_resolution, max_y=vertical_chart_resolution)

        if not rows:
            rows = [u'' for _ in range(height)]

        for i, row in enumerate(rows):
            rows[i] = u'{0}'.format(row.ljust(width))

        return rows
Пример #8
0
    def render(self, width, height, values):
        """
        :type width: int
        :type height: int
        :type values: list[int or float]
        :rtype: list[str or unicode]
        """
        from drawille import Canvas

        vertical_chart_resolution = height * self.char_resolution_vertical
        horizontal_chart_resolution = width * self.char_resolution_horizontal

        canvas = Canvas()
        x = 0
        for value in values:
            for y in range(1, int(round(value, 0)) + 1):
                canvas.set(x, vertical_chart_resolution - y)
            x += 1

        rows = canvas.rows(min_x=0,
                           min_y=0,
                           max_x=horizontal_chart_resolution,
                           max_y=vertical_chart_resolution)

        if not rows:
            rows = [u'' for _ in range(height)]

        for i, row in enumerate(rows):
            rows[i] = u'{0}'.format(row.ljust(width))

        return rows
Пример #9
0
def image2term(image, threshold=128, ratio=None, invert=False):
    """
    Prints an image converted to drawille
    Args:
        image: filepath / URL of the image
        threshold: The color (0-255) threshold to convert a pixel to a drawille dot
        ratio: Ratio to scale the printed image (e.g. ratio=0.5 is 50%)
        invert: Inverts the threshold check
    """

    if image.startswith('http://') or image.startswith('https://'):
        r = requests.get(image,stream=True)
        i = Image.open(r.raw).convert('L')
    else:
        f = open(image,'rb') #Open in binary mode
        i = Image.open(f).convert('L')
    image_width, image_height = i.size
    if ratio:
        image_width = int(image_width * ratio)
        image_height = int(image_height * ratio)
        i = i.resize((image_width, image_height), Image.ANTIALIAS)
    else:
        terminal_width = getTerminalSize()[0] * 2#Number of Columns
        terminal_height = getTerminalSize()[1] * 4
    
        w_ratio = 1
        h_ratio = 1

        if terminal_width < image_width:
            w_ratio = terminal_width / float(image_width)
        
        if terminal_height < image_height:
            h_ratio = terminal_height / float(image_height)
        

        ratio = min([w_ratio,h_ratio])
        image_width = int(image_width * ratio)
        image_height = int(image_height * ratio)
        i = i.resize((image_width, image_height), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0

    try:
        i_converted = i.tobytes()
    except AttributeError:
        i_converted = i.tostring()

    for pix in i_converted:
        if invert:
            if pix > threshold:
                can.set(x, y)
        else:
            if pix < threshold:
                can.set(x, y)
        x += 1
        if x >= image_width:
            y += 1
            x = 0
    return can.frame(0, 0)
Пример #10
0
 def test_get(self):
     c = Canvas()
     self.assertEqual(c.get(0, 0), False)
     c.set(0, 0)
     self.assertEqual(c.get(0, 0), True)
     self.assertEqual(c.get(0, 1), False)
     self.assertEqual(c.get(1, 0), False)
     self.assertEqual(c.get(1, 1), False)
Пример #11
0
 def test_get(self):
     c = Canvas()
     self.assertEqual(c.get(0, 0), False)
     c.set(0, 0)
     self.assertEqual(c.get(0, 0), True)
     self.assertEqual(c.get(0, 1), False)
     self.assertEqual(c.get(1, 0), False)
     self.assertEqual(c.get(1, 1), False)
Пример #12
0
def main(args, opts):
    curses.use_default_colors()
    curses.curs_set(0)

    win = curses.initscr()

    source = Image.open(opts.filename)

    c = Canvas()

    try:
        while True:
            (wh, ww) = win.getmaxyx()

            try:
                source.seek(source.tell() + 1)
            except:
                if opts.onetime:
                    break
                source.seek(0)

            img = (source
                    .resize(((ww - 1) * 2, wh * 4))
                    .convert("1")
                    )
            w = img.width

            (x, y) = (0, 0)
            for v in img.getdata():

                if opts.reverse:
                    if not v:
                        c.set(x, y)

                else:
                    if v:
                        c.set(x, y)

                x += 1

                if w <= x:
                    x = 0
                    y += 1

            for r in range(wh):
                line = c.rows(min_y=(r*4), max_y=((r+1)*4))[0]
                win.addnstr(r, 0, pad(line, ww), ww)

            win.refresh()
            c.clear()
            time.sleep(opts.interval)

    except KeyboardInterrupt:
        pass
Пример #13
0
def complexset2drawille(complexset, n):
    can = Canvas()
    w, h = getTerminalSize()
    w *= 2
    h *= 4

    for row in range(h):
        for col in range(w):
            if complexset.plot(col, row, w, h, n) >= complexset.MAX_ITER:
                can.set(col, row)
    return can.frame()
Пример #14
0
def __main__():
    args = argparser()
    out = args['output']

    orig_img = image.load(args['image']).convert('RGB')
    if args['contrast'] != None:
        orig_img = ImageEnhance.Contrast(orig_img).enhance(args['contrast'])
    orig_img = resizer.resize(orig_img, 1, ANTI_FONT_DISTORTION)
    fit_ratio = resizer.fit_in_ratio(orig_img.size, term.size())
    if args['ratio']:
        fit_ratio *= args['ratio']

    img = resizer.resize(orig_img, fit_ratio, (1, 1))
    lows, mids, highs = posterizer.thresholds(img)
    if args['color'] != None:
        lows = map(lambda val: bound_addition(val, args['color']), lows)
        mids = map(lambda val: bound_addition(val, args['color']), mids)
        highs = map(lambda val: bound_addition(val, args['color']), highs)
    colors = posterizer.posterize(img, mids, highs)

    #    img.show()
    shapes = resizer.resize(orig_img, fit_ratio, (2, 4))
    #    shapes.show()
    shapes = shapes.convert('L')
    threshold = otsu.threshold(shapes.histogram())
    #    mask = shapes.point(lambda val: 255 if val <= threshold else 0).convert('1')
    #    threshold = otsu.threshold(shapes.histogram(mask))
    if args['shape'] != None:
        threshold = bound_addition(threshold, args['shape'])
    shapes = shapes.point(lambda val: 255
                          if val > threshold else 0).convert('1')
    #    shapes.show()
    dots = Canvas()
    w, h = shapes.size
    for index, pixel in enumerate(list(shapes.getdata()), 0):
        if pixel:
            dots.set(index % w, index // w)


#    out.write(dots.frame(0,0,w,h))
#    out.write('\n')

    w, h = colors.size
    for index, pixel in enumerate(list(colors.getdata()), 0):
        x = (index % w) * 2
        y = (index // w) * 4
        miniframe = unicode(dots.frame(x, y, x + 2, y + 4), 'utf-8')
        miniframe = miniframe if len(miniframe) else u'\u2800'
        out.write(color_print.rgb2esc(pixel, [0, 0, 0], lows, highs,
                                      miniframe))
        if not (1 + index) % w:
            out.write('\n')
Пример #15
0
def __main__(stdscr, projection=False):
    angleX, angleY, angleZ = 0, 0, 0
    c = Canvas()
    while 1:
        # Will hold transformed vertices.
        t = []

        for v in vertices:
            # Rotate the point around X axis, then around Y axis, and finally around Z axis.
            p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ)
            if projection:
                # Transform the point from 3D to 2D
                p = p.project(50, 50, 50, 50)
             #Put the point in the list of transformed vertices
            t.append(p)

        for f in faces:
            for x,y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y):
                c.set(x,y)
            for x,y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y):
                c.set(x,y)
            for x,y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y):
                c.set(x,y)
            for x,y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y):
                c.set(x,y)

        f = c.frame(-40, -40, 80, 80)
        stdscr.addstr(0, 0, '{0}\n'.format(f))
        stdscr.refresh()

        angleX += 2
        angleY += 3
        angleZ += 5
        sleep(1.0/20)
        c.clear()
Пример #16
0
def __main__(stdscr, projection=False):
    angleX, angleY, angleZ = 0, 0, 0
    c = Canvas()
    while 1:
        # Will hold transformed vertices.
        t = []

        for v in vertices:
            # Rotate the point around X axis, then around Y axis, and finally around Z axis.
            p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ)
            if projection:
                # Transform the point from 3D to 2D
                p = p.project(50, 50, 50, 50)
            #Put the point in the list of transformed vertices
            t.append(p)

        for f in faces:
            for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y):
                c.set(x, y)
            for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y):
                c.set(x, y)
            for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y):
                c.set(x, y)
            for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y):
                c.set(x, y)

        f = c.frame(-40, -40, 80, 80)
        stdscr.addstr(0, 0, '{0}\n'.format(f))
        stdscr.refresh()

        angleX += 2
        angleY += 3
        angleZ += 5
        sleep(1.0 / 20)
        c.clear()
Пример #17
0
def update(im, delay=0.1):

  im = im.resize((CANVAS_W, CANVAS_H))
  canvas = Canvas()
  any(canvas.set(i % CANVAS_W, i // CANVAS_W)
      for i, px in enumerate(im.tobytes()) if px)
  print(canvas.frame(0, 0, CANVAS_W, CANVAS_H), end='')
  time.sleep(delay)
Пример #18
0
def __main__(stdscr):
    i = 0
    c = Canvas()
    height = 40
    while True:

        for x,y in line(0, height, 180, int(math.sin(math.radians(i)) * height + height)):
            c.set(x,y)

        for x in range(0, 360, 2):
            coords = (x/2, height + int(round(math.sin(math.radians(x+i)) * height)))
            c.set(*coords)

        f = c.frame()
        stdscr.addstr(0, 0, '{0}\n'.format(f))
        stdscr.refresh()

        i += 2
        sleep(1.0/24)
        c.clear()
Пример #19
0
def __main__(stdscr):
    i = 0
    c = Canvas()
    height = 40
    while True:

        for x,y in line(0, height, 180, int(math.sin(math.radians(i)) * height + height)):
            c.set(x,y)

        for x in range(0, 360, 2):
            coords = (x/2, height + int(round(math.sin(math.radians(x+i)) * height)))
            c.set(*coords)

        f = c.frame()
        stdscr.addstr(0, 0, '{0}\n'.format(f))
        stdscr.refresh()

        i += 2
        sleep(1.0/24)
        c.clear()
Пример #20
0
def image2term(image, threshold=128, ratio=None, invert=False):
    if image.startswith('http://') or image.startswith('https://'):
        f = BytesIO(requests.get(image).content)
        i = Image.open(f).convert('L')
    else:
        with open(image, 'rb') as f:
            i = Image.open(f).convert('L')
    w, h = i.size
    if ratio:
        w = int(w * ratio)
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)
    else:
        tw = getTerminalSize()[0]
        tw *= 2
        if tw < w:
            ratio = tw / float(w)
            w = tw
            h = int(h * ratio)
            i = i.resize((w, h), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0

    try:
        i_converted = i.tobytes()
    except AttributeError:
        i_converted = i.tostring()

    for pix in i_converted:
        if type(pix) is not int: pix = ord(pix)
        if invert:
            if pix > threshold:
                can.set(x, y)
        else:
            if pix < threshold:
                can.set(x, y)
        x += 1
        if x >= w:
            y += 1
            x = 0
    return can.frame(0, 0)
Пример #21
0
def draw_coords(stdscr, design):

    c = Canvas()

    for i in range(10):

        for point in design:
            c.set(point.x, point.y)
    
        df = c.frame(-40, -40, 80, 80)
        stdscr.addstr(1, 0, df)
        stdscr.refresh()

        new_move_delta = Point(choice([-1, 0, 1]), choice([-1, 0, 1]))
        design = move(design, new_move_delta)

        sleep(.5)
        c.clear()

    sleep(6)
    c.clear()
Пример #22
0
    async def handle_client(cls, process):
        pos = 0, 0
        i = 0
        process.stdout.write('\e[8;50;100t')
        while i < 1000:
            c = Canvas()

            process.stdout.write('\033[2J')
            process.stdout.write("\033[?25l")

            for i in range(pos[0], pos[0] + 10):
                for j in range(pos[1], pos[1] + 10):
                    c.set(i % 80 - 40, j % 60 - 30)

            process.stdout.write(c.frame(-40, -30, 40, 30))

            await asyncio.sleep(1. / 15)
            pos = pos[0] + 1, pos[1] + 1
            i += 1

        process.exit(0)
Пример #23
0
def main(stdscr):
    global frame_no, speed, position, score
    c = Canvas()
    bar_width = 16
    bars = [Bar(bar_width)]
    stdscr.refresh()

    while True:
        frame_no += 1
        for bar in bars:
            if check_collision(position, bar):
                return
        while not keys.empty():
            if keys.get() == 113:
                return
            speed = 32.0

        c.set(0,0)
        c.set(width, height)
        if frame_no % 50 == 0:
            bars.append(Bar(bar_width))
        for x,y in bird:
            c.set(x,y+position)
        for bar_index, bar in enumerate(bars):
            if bar.x < 1:
                bars.pop(bar_index)
                score += 1
            else:
                bars[bar_index].x -= 1
                for x,y in bar.draw():
                    c.set(x,y)
        f = c.frame()+'\n'
        stdscr.addstr(0, 0, f)
        stdscr.addstr(height/4+1, 0, 'score: {0}'.format(score))
        stdscr.refresh()
        c.clear()

        speed -= 2

        position -= speed/10

        if position < 0:
            position = 0
            speed = 0.0
        elif position > height-13:
            position = height-13
            speed = 0.0


        sleep(1.0/fps)
Пример #24
0
def main(stdscr):
    global frame_no, speed, fps, position, delta, score
    c = Canvas()
    bar_width = 16
    bars = [Bar(bar_width)]
    stdscr.refresh()

    while True:
        frame_no += 1
        for bar in bars:
            if check_collision(position, bar):
                return
        while not keys.empty():
            if keys.get() == 113:
                return
            speed = 32.0

        c.set(0,0)
        c.set(width, height)
        if frame_no % 50 == 0:
            bars.append(Bar(bar_width))
        for x,y in bird:
            c.set(x,y+position)
        for bar_index, bar in enumerate(bars):
            if bar.x < 1:
                bars.pop(bar_index)
                score += 1
            else:
                bars[bar_index].x -= 1
                for x,y in bar.draw():
                    c.set(x,y)
        f = c.frame()+'\n'
        stdscr.addstr(0, 0, f)
        stdscr.addstr(height/4+1, 0, 'score: {0}'.format(score))
        stdscr.refresh()
        c.clear()

        speed -= 2

        position -= speed/10

        if position < 0:
            position = 0
            speed = 0.0
        elif position > height-13:
            position = height-13
            speed = 0.0


        sleep(1.0/fps)
Пример #25
0
def get_frame(terminal_width: int = 80) -> str:
    pixel_width = terminal_width * 2
    cutoff = get_cutoff(pixel_width)

    base_path = path.dirname(__file__)
    world_path = path.abspath(path.join(base_path, "world.svg"))

    drawing = svg2rlg(world_path)
    image = renderPM.drawToPIL(drawing)
    height, width = image.size
    image = image.resize((pixel_width, int(width / height * pixel_width)))
    height, width = image.size

    canvas = Canvas()

    for x in range(0, height):
        for y in range(0, width):
            pixel = image.getpixel((x, y))
            if pixel[0] < cutoff and pixel[1] < cutoff and pixel[2] < cutoff:
                canvas.set(x, y)

    return canvas.frame()
Пример #26
0
def image2term(image, threshold=128, ratio=None, invert=False):
    if image.startswith('http://') or image.startswith('https://'):
        i = Image.open(StringIO(urllib2.urlopen(image).read())).convert('L')
    else:
        i = Image.open(open(image)).convert('L')
    w, h = i.size
    if ratio:
        w = int(w * ratio)
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)
    else:
        tw = getTerminalSize()[0]
        tw *= 2
        if tw < w:
            ratio = tw / float(w)
            w = tw
            h = int(h * ratio)
            i = i.resize((w, h), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0

    try:
         i_converted = i.tobytes()
    except AttributeError:
         i_converted = i.tostring()

    for pix in i_converted:
        if invert:
            if ord(pix) > threshold:
                can.set(x, y)
        else:
            if ord(pix) < threshold:
                can.set(x, y)
        x += 1
        if x >= w:
            y += 1
            x = 0
    return can.frame(0, 0)
Пример #27
0
def __main__(stdscr, projection=False):
    angleX, angleY, angleZ = 0, 0, 0
    canvas = Canvas()
    while 1:
        # Will hold transformed vertices.
        transformed_vertices = []

        for vertex in vertices:
            # Rotate the point around X axis, then around Y axis, and finally around Z axis.
            point = vertex.rotateX(angleX).rotateY(angleY).rotateZ(angleZ)
            if projection:
                # Transform the point from 3D to 2D
                point = point.project(50, 50, 50, 50)
            #Put the point in the list of transformed vertices
            transformed_vertices.append(point)

        for face in faces:
            for x, y in line(transformed_vertices[face[0]].x,
                             transformed_vertices[face[0]].y,
                             transformed_vertices[face[1]].x,
                             transformed_vertices[face[1]].y):
                canvas.set(x, y)
            for x, y in line(transformed_vertices[face[1]].x,
                             transformed_vertices[face[1]].y,
                             transformed_vertices[face[2]].x,
                             transformed_vertices[face[2]].y):
                canvas.set(x, y)
            for x, y in line(transformed_vertices[face[2]].x,
                             transformed_vertices[face[2]].y,
                             transformed_vertices[face[3]].x,
                             transformed_vertices[face[3]].y):
                canvas.set(x, y)
            for x, y in line(transformed_vertices[face[3]].x,
                             transformed_vertices[face[3]].y,
                             transformed_vertices[face[0]].x,
                             transformed_vertices[face[0]].y):
                canvas.set(x, y)

        frame = canvas.frame(-40, -40, 80, 80)
        stdscr.addstr(0, 0, '{0}\n'.format(frame))
        stdscr.refresh()

        angleX += 2
        angleY += 3
        angleZ += 5
        sleep(1.0 / 20)
        canvas.clear()
Пример #28
0
    def to_txt(self, sep="\n", tw=240, invert=False, threshold=200):
        # import pdb; pdb.set_trace()

        buf = io.BytesIO()
        self.print_png(buf)
        buf.seek(0)

        i = Image.open(buf)

        w, h = i.size

        ratio = tw / float(w)
        w = tw
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)

        i = i.convert(mode="L")

        can = Canvas()

        for y in range(h):
            for x in range(w):

                pix = i.getpixel((x, y))

                if invert:
                    if pix > threshold:
                        can.set(x, y)
                else:
                    if pix < threshold:
                        can.set(x, y)

        for x, y, s in self.renderer.texts:
            can.set_text(int(x * ratio), int(y * ratio), s)

        return can.frame()
Пример #29
0
def __main__(projection=False):
    angleX, angleY, angleZ = 0, 0, 0
    c = Canvas()
    while 1:
        # Will hold transformed vertices.
        t = []

        for v in vertices:
            # Rotate the point around X axis, then around Y axis, and finally around Z axis.
            p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ)
            if projection:
                # Transform the point from 3D to 2D
                p = p.project(50, 50, 50, 50)
            # Put the point in the list of transformed vertices
            t.append(p)

        for f in faces:
            for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y):
                c.set(x, y)
            for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y):
                c.set(x, y)
            for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y):
                c.set(x, y)
            for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y):
                c.set(x, y)

        f = c.frame(-20, -20, 20, 20)
        s = 'broadcast "\\n\\n\\n'
        for l in format(f).splitlines():
            s += l.replace(" ", "  ").rstrip("\n") + "\\n"
        s = s[:-2]
        s += '"'
        print(s)
        sys.stdout.flush()

        angleX += 2
        angleY += 3
        angleZ += 5
        sleep(1.0 / 10)
        c.clear()
Пример #30
0
def __main__(projection=False):
    angleX, angleY, angleZ = 0, 0, 0
    c = Canvas()
    while 1:
        # Will hold transformed vertices.
        t = []

        for v in vertices:
            # Rotate the point around X axis, then around Y axis, and finally around Z axis.
            p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ)
            if projection:
                # Transform the point from 3D to 2D
                p = p.project(50, 50, 50, 50)
            #Put the point in the list of transformed vertices
            t.append(p)

        for f in faces:
            for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y):
                c.set(x, y)
            for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y):
                c.set(x, y)
            for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y):
                c.set(x, y)
            for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y):
                c.set(x, y)

        f = c.frame(-20, -20, 20, 20)
        s = 'broadcast "\\n\\n\\n'
        for l in format(f).splitlines():
            s += l.replace(' ', '  ').rstrip('\n') + '\\n'
        s = s[:-2]
        s += '"'
        print(s)
        sys.stdout.flush()

        angleX += 2
        angleY += 3
        angleZ += 5
        sleep(1.0 / 10)
        c.clear()
Пример #31
0
 def test_set(self):
     c = Canvas()
     c.set(1, 1)
     self.assertTrue(1 in c.pixels and 1 in c.pixels[1])
Пример #32
0
		tb = tb / ( ppd * ppd )
		sum = (tr + tg + tb) / 3
		#python doesn't have bools, it's like see where 0 is false and anything else is true
		if (dither or trippy) :
			#because you can't divide by zero
			if (sum == 0) :
				canvo.unset(x,y)
			else:
				#the RGB scale is exponential , so the ratio of light from 255 to 80 would be 255^2/80^2
				# however since the image is 3 dimensional, then the dither turns on in 1/mod * 1/mod
				# so mod should be 255/80 instead
				mod = int(255 / sum)
				# the ratio here is (2x-1)/x^2 where x is 255/sum
				if (trippy) :
					if (((x % mod) == 0) or ((y % mod) == 0)) :
						canvo.set(x,y)
					else:
						canvo.unset(x,y)
				#ratio is 1/x^2
				elif (dither) :
					if (((x % mod) == 0) and ((y % mod) == 0)) :
						canvo.set(x,y)
					else:
						canvo.unset(x,y)
		else:
			if (threshup >=  sum >= threshdown ) :
				# turns the dot on at x,y
				canvo.set(x,y)
			else :
				# it seems if an entire character is blank, draille does not print it regardless of this
				canvo.unset(x,y)
Пример #33
0
def view(in_file, file_format=None, curr_model=1, chains=[], box_size=100.0):
    if box_size < 10.0 or box_size > 400.0:
        print("Box size must be between 10 and 400")
        return

    auto_spin = False
    cycle_models = False

    coords, info = read_inputs(in_file, file_format, curr_model, chains)
    if coords is None:
        return

    # Build help strings
    info_str = (
        f"{os.path.basename(in_file)} with {info['num_struc']} models, "
        f"{len(info['chain_ids'])} chains ({''.join(info['chain_ids'])}) "
        f"{info['res_counter']} residues, {info['atom_counter']} atoms.")
    help_str = "W/A/S/D rotates, T/F/G/H moves, I/O zooms, U spins, P cycles models, Q quits"

    # Make square bounding box of a set size and determine zoom
    x_min, x_max = float(coords[curr_model - 1, :,
                                0].min()), float(coords[curr_model - 1, :,
                                                        0].max())
    y_min, y_max = float(coords[curr_model - 1, :,
                                1].min()), float(coords[curr_model - 1, :,
                                                        1].max())
    x_diff, y_diff = x_max - x_min, y_max - y_min
    box_bound = float(np.max([x_diff, y_diff])) + 2.0
    zoom = box_size / box_bound
    x_min = zoom * (x_min - (box_bound - x_diff) / 2.0)
    x_max = zoom * (x_max + (box_bound - x_diff) / 2.0)
    y_min = zoom * (y_min - (box_bound - y_diff) / 2.0)
    y_max = zoom * (y_max + (box_bound - y_diff) / 2.0)

    # Set up curses screen
    # https://docs.python.org/3/howto/curses.html
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.curs_set(False)
    stdscr.keypad(True)  # Respond to keypresses w/o Enter
    stdscr.nodelay(True)  # Don't block while waiting for keypress

    # Divide curses screen into windows
    window_info = stdscr.subwin(
        2,
        curses.COLS - 1,  # height, width
        0,
        0)  # begin_y, begin_x
    window_structure = stdscr.subwin(
        curses.LINES - 1 - 2,
        curses.COLS - 1,  # height, width
        2,
        0)  # begin_y, begin_x

    # Print help strings (only need to do this once)
    window_info.addnstr(0, 0, info_str, window_info.getmaxyx()[1] - 1)
    window_info.addnstr(1, 0, help_str, window_info.getmaxyx()[1] - 1)
    window_info.refresh()

    canvas = Canvas()
    trans_x, trans_y = 0.0, 0.0
    rot_x, rot_y = 0.0, 0.0

    try:
        points = []
        do_update = True
        while True:
            curses.napms(50)  # Delay a short while

            # Re-draw structure if needed
            if do_update:
                points = []
                for x_start, y_start, x_end, y_end in (
                    (x_min, y_min, x_max, y_min),
                    (x_max, y_min, x_max, y_max),
                    (x_max, y_max, x_min, y_max),
                    (x_min, y_max, x_min, y_min),
                ):
                    for x, y in line(x_start, y_start, x_end, y_end):
                        points.append([x, y])

                rot_mat_x = np.array([
                    [1.0, 0.0, 0.0],
                    [0.0, np.cos(rot_x), -np.sin(rot_x)],
                    [0.0, np.sin(rot_x), np.cos(rot_x)],
                ],
                                     dtype=np.float32)
                rot_mat_y = np.array([
                    [np.cos(rot_y), 0.0, np.sin(rot_y)],
                    [0.0, 1.0, 0.0],
                    [-np.sin(rot_y), 0.0, np.cos(rot_y)],
                ],
                                     dtype=np.float32)
                trans_coords = coords[curr_model - 1] + np.array(
                    [trans_x, trans_y, 0.0], dtype=np.float32)
                zoom_rot_coords = zoom * np.matmul(
                    rot_mat_y, np.matmul(rot_mat_x, trans_coords.T)).T

                for i in range(coords.shape[1] - 1):
                    if not info['connections'][i]:
                        continue
                    x_start, x_end = float(zoom_rot_coords[i, 0]), float(
                        zoom_rot_coords[i + 1, 0])
                    y_start, y_end = float(zoom_rot_coords[i, 1]), float(
                        zoom_rot_coords[i + 1, 1])
                    # Check if the bond fits in the box
                    if x_min < x_start < x_max and x_min < x_end < x_max and y_min < y_start < y_max and y_min < y_end < y_max:
                        for x, y in line(x_start, y_start, x_end, y_end):
                            points.append([x, y])

                # Update displayed structure
                canvas.clear()
                for x, y in points:
                    canvas.set(x, y)
                window_structure.addstr(0, 0, canvas.frame())
                window_structure.refresh()
                do_update = False

            # Prepare rotation/model selection for next time
            if auto_spin:
                rot_y += spin_speed
                do_update = True
            if cycle_models:
                curr_model += 1
                if curr_model > len(coords):
                    curr_model = 1
                do_update = True

            # Handle keypresses
            try:
                c = stdscr.getch()
                if c != curses.ERR:
                    do_update = True
                    if c in (ord("o"), ord("O")):
                        zoom /= zoom_speed
                    elif c in (ord("i"), ord("I")):
                        zoom *= zoom_speed
                    elif c in (ord("f"), ord("F")):
                        trans_x -= trans_speed
                    elif c in (ord("h"), ord("H")):
                        trans_x += trans_speed
                    elif c in (ord("g"), ord("G")):
                        trans_y -= trans_speed
                    elif c in (ord("t"), ord("T")):
                        trans_y += trans_speed
                    elif c in (ord("s"), ord("S")):
                        rot_x -= rot_speed
                    elif c in (ord("w"), ord("W")):
                        rot_x += rot_speed
                    elif c in (ord("a"), ord("A")):
                        rot_y -= rot_speed
                    elif c in (ord("d"), ord("D")):
                        rot_y += rot_speed
                    elif c in (ord("u"), ord("U")):
                        auto_spin = not auto_spin
                    elif c in (ord("p"), ord("P")) and len(coords) > 1:
                        cycle_models = not cycle_models
                    elif c in (ord("q"), ord("Q")):
                        return
            except IOError:
                pass
    except KeyboardInterrupt:
        # If user presses Ctrl+C, pretend as if they pressed q.
        return
    finally:
        # Teardown curses interface
        curses.nocbreak()
        curses.echo()
        curses.curs_set(True)
        stdscr.keypad(False)
        curses.endwin()

        # Make sure last view stays on screen
        print(info_str)
        print(help_str)
        print(canvas.frame())
Пример #34
0
 def test_max_min_limits(self):
     c = Canvas()
     c.set(0, 0)
     self.assertEqual(c.frame(min_x=2), '')
     self.assertEqual(c.frame(max_x=0), '')
Пример #35
0
 def test_clear(self):
     c = Canvas()
     c.set(1, 1)
     c.clear()
     self.assertEqual(c.chars, dict())
Пример #36
0
 def test_unset_empty(self):
     c = Canvas()
     c.set(1, 1)
     c.unset(1, 1)
     self.assertEqual(len(c.chars), 0)
Пример #37
0
 def test_frame(self):
     c = Canvas()
     self.assertEqual(c.frame(), '')
     c.set(0, 0)
     self.assertEqual(c.frame(), 'РаЂ')
Пример #38
0
 def test_clear(self):
     c = Canvas()
     c.set(1, 1)
     c.clear()
     self.assertEqual(c.chars, dict())
Пример #39
0
 def test_unset_nonempty(self):
     c = Canvas()
     c.set(0, 0)
     c.set(0, 1)
     c.unset(0, 1)
     self.assertEqual(c.chars[0][0], 1)
Пример #40
0
 def test_unset_empty(self):
     c = Canvas()
     c.set(1, 1)
     c.unset(1, 1)
     self.assertEqual(len(c.chars), 0)
Пример #41
0
    else:
        url = 'http://xkcd.com/%s/' % argv[1]
    c = urllib2.urlopen(url).read()
    img_url = re.findall('http:\/\/imgs.xkcd.com\/comics\/.*\.png', c)[0]
    i = Image.open(StringIO(urllib2.urlopen(img_url).read())).convert('L')
    w, h = i.size
    tw, th = getTerminalSize()
    tw *= 2
    th *= 2
    if tw < w:
        ratio = tw / float(w)
        w = tw
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0

    try:
         i_converted = i.tobytes()
    except AttributeError:
         i_converted = i.tostring()

    for pix in i_converted:
        if ord(pix) < 128:
            can.set(x, y)
        x += 1
        if x >= w:
            y += 1
            x = 0
    print(can.frame())
Пример #42
0
 def test_unset_nonempty(self):
     c = Canvas()
     c.set(1, 1)
     c.set(2, 1)
     c.unset(1, 1)
     self.assertEqual(c.pixels, {1:{2: 2}})
Пример #43
0
    mv = move
    rt = right
    lt = left
    bk = back

########NEW FILE########
__FILENAME__ = basic
from __future__ import print_function
from drawille import Canvas
import math


s = Canvas()

for x in range(1800):
    s.set(x/10, math.sin(math.radians(x)) * 10)

print(s.frame())

s.clear()

for x in range(0, 1800, 10):
    s.set(x/10, 10 + math.sin(math.radians(x)) * 10)
    s.set(x/10, 10 + math.cos(math.radians(x)) * 10)

print(s.frame())

s.clear()

for x in range(0, 3600, 20):
    s.set(x/20, 4 + math.sin(math.radians(x)) * 4)
Пример #44
0
 def test_set(self):
     c = Canvas()
     c.set(0, 0)
     self.assertTrue(0 in c.chars and 0 in c.chars[0])
Пример #45
0
 def test_max_min_limits(self):
     c = Canvas()
     c.set(0, 0)
     self.assertEqual(c.frame(min_x=2), '')
     self.assertEqual(c.frame(max_x=0), '')
Пример #46
0
 def test_unset_nonempty(self):
     c = Canvas()
     c.set(0, 0)
     c.set(0, 1)
     c.unset(0, 1)
     self.assertEqual(c.chars[0][0], 1)
Пример #47
0
 def test_unset_empty(self):
     c = Canvas()
     c.set(1, 1)
     c.unset(1, 1)
     self.assertEqual(c.pixels, dict())
Пример #48
0
 def test_frame(self):
     c = Canvas()
     self.assertEqual(c.frame(), '')
     c.set(0, 0)
     self.assertEqual(c.frame(), 'РаЂ')
Пример #49
0
 def test_set(self):
     c = Canvas()
     c.set(0, 0)
     self.assertTrue(0 in c.chars and 0 in c.chars[0])
Пример #50
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from drawille import Canvas
from timeit import timeit

c = Canvas()

frames = 1000 * 10

sizes = ((0, 0), (10, 10), (20, 20), (20, 40), (40, 20), (40, 40), (100, 100))

for x, y in sizes:
    c.set(0, 0)

    for i in range(y):
        c.set(x, i)

    r = timeit(c.frame, number=frames)
    print('{0}x{1}\t{2}'.format(x, y, r))
    c.clear()
Пример #51
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
from drawille import Canvas
import math

s = Canvas()

for x in range(1800):
    s.set(x / 10, math.sin(math.radians(x)) * 10)

print(s.frame())

s.clear()

for x in range(0, 1800, 10):
    s.set(x / 10, 10 + math.sin(math.radians(x)) * 10)
    s.set(x / 10, 10 + math.cos(math.radians(x)) * 10)

print(s.frame())

s.clear()

for x in range(0, 3600, 20):
    s.set(x / 20, 4 + math.sin(math.radians(x)) * 4)

print(s.frame())

s.clear()
Пример #52
0
class GameOfLife:

    def __init__(self, rows, cols):
        self.rows = rows
        self.cols = cols
        self.can = Canvas()
        self.state = [[bool(random.getrandbits(1)) for y in range(rows)] for x in range(cols)]

    def tick(self):
        next_gen = [[False for y in range(self.rows)] for x in range(self.cols)]

        for y in range(self.rows):
            for x in range(self.cols):
                nburs = self._ncount(x, y)
                if self.state[x][y]:
                    # Alive
                    if nburs > 1 and nburs < 4:
                        self.can.set(x,y)
                        next_gen[x][y] = True
                    else:
                        next_gen[x][y] = False
                else:
                    # Dead
                    if nburs == 3:
                        self.can.set(x,y)
                        next_gen[x][y] = True
                    else:
                        next_gen[x][y] = False

        self.state = next_gen

    def draw(self):
        f = self.can.frame(0,0,self.cols,self.rows)
        stdscr.addstr(0, 0, '{0}\n'.format(f))
        self.can.clear()

    def put(self, matrix, x, y):
        for mx in range(len(matrix)):
            for my in range(len(matrix[0])):
                self.state[min(x+my,self.cols-1)][min(y+mx,self.rows-1)] = matrix[mx][my]


    def _ncount(self, x, y):
        nburs = 0

        # Left
        if x > 0:
            if self.state[x-1][y]:
                nburs += 1
            # Top
            if y > 0:
                if self.state[x-1][y-1]:
                    nburs += 1
            # Bottom
            if y < self.rows-1:
                if self.state[x-1][y+1]:
                    nburs += 1

        # Right
        if x < self.cols-1:
            if self.state[x+1][y]:
                nburs += 1
            # Top
            if y > 0:
                if self.state[x+1][y-1]:
                    nburs += 1
            # Bottom
            if y < self.rows-1:
                if self.state[x+1][y+1]:
                    nburs += 1

        # Top
        if y > 0:
            if self.state[x][y-1]:
                nburs += 1
        # Bottom
        if y < self.rows-1:
            if self.state[x][y+1]:
                nburs += 1

        return nburs
Пример #53
0
from __future__ import print_function
from drawille import Canvas
import math


s = Canvas()

for x in range(1800):
    s.set((x/10, math.sin(math.radians(x)) * 10))

print(s.frame())

s.clear()

for x in range(0, 1800, 10):
    s.set((x/10, 10 + math.sin(math.radians(x)) * 10))
    s.set((x/10, 10 + math.cos(math.radians(x)) * 10))

print(s.frame())

s.clear()

for x in range(0, 3600, 20):
    s.set((x/20, 4 + math.sin(math.radians(x)) * 4))

print(s.frame())

s.clear()

for x in range(0, 360, 4):
    s.set((x/4, 30 + math.sin(math.radians(x)) * 30))
Пример #54
0
def printa_parabola(lado):
    s = Canvas()
    s.clear()
    for x in range(0, 180):
        s.set(x / 4, lado + sin(radians(x)) * lado)
    return s.frame()
Пример #55
0
    if tw < w or th < h:
        ratio = min(tw / float(w), th / float(h))
        w = int(w * ratio)
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0

    try:
         i_converted = i.tobytes()
    except AttributeError:
         i_converted = i.tostring()

    for pix in i_converted:
        if pix < 128:
            can.set(x, y)
        x += 1
        if x >= w:
            y += 1
            x = 0

    info_json = urlopen('https://xkcd.com/info.0.json').read().decode('utf-8')
    info = json.loads(info_json)

    """
    redirect_url = "https://www.explainxkcd.com/wiki/api.php?{}".format(urlencode({
        'action': 'query',
        'titles': info['num'],
        'redirects': 'true',
        'format': 'json',
    }))
Пример #56
0
from drawille import Canvas
from timeit import timeit

canvas = Canvas()

frames = 1000 * 10

sizes = ((0, 0),
         (10, 10),
         (20, 20),
         (20, 40),
         (40, 20),
         (40, 40),
         (100, 100))

for x, y in sizes:
    canvas.set(0, 0)

    for i in range(y):
        canvas.set(x, i)

    r = timeit(canvas.frame, number=frames)
    print('{0}x{1}\t{2}'.format(x, y, r))
    canvas.clear()
Пример #57
0
from drawille import Canvas
from timeit import timeit

c = Canvas()

frames = 1000 * 10

sizes = ((0, 0),
         (10, 10),
         (20, 20),
         (20, 40),
         (40, 20),
         (40, 40),
         (100, 100))

for x, y in sizes:
    c.set(0, 0)

    for i in range(y):
        c.set(x, i)

    r = timeit(c.frame, number=frames)
    print('{0}x{1}\t{2}'.format(x, y, r))
    c.clear()