コード例 #1
0
ファイル: draw.py プロジェクト: kangtaoo/nnbp
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
コード例 #2
0
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 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())
コード例 #4
0
ファイル: renderers.py プロジェクト: andras-tim/tchart
    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
コード例 #5
0
ファイル: image2term.py プロジェクト: MB6/drawille
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()
コード例 #6
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
コード例 #7
0
ファイル: widget.py プロジェクト: sysr-q/wopr
    def __init__(self, scr, data, maxlen=1024, enc="utf-8", name="Sparkline"):
        super(Sparkline, self).__init__(scr, enc=enc, name=name)

        def mkcanvases():
            d = {
                "data": collections.deque([], maxlen=maxlen),
                "canvas": Canvas(),
                "attr": curses.color_pair(random.choice([1, 2, 3, 4, 5])),
                "dirty": True,
            }
            return d

        self.axes = Canvas()
        self.canvases = collections.defaultdict(mkcanvases)
        self.maxlen = maxlen

        for x in data:  # data=[("foo", [...]), ("bar", [...])]
            if len(x) == 3:
                name, d, attr = x
            else:
                name, d = x
                attr = None
            self.add_data(name, d, attr=attr)

        self.edge_buffer = 20  # 20px from edges
        self.data_buffer = 3  # + 3px added buffer for the data canvas
        self.rounding = 5  # round axes up to nearest 5.
        self.fill = True  # fill inbetween points with lines
コード例 #8
0
ファイル: trailer.py プロジェクト: livibetter/READYT
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)
コード例 #9
0
ファイル: __init__.py プロジェクト: yoavtzelnick/graphscii
 def draw(self):
     """Draw the graph
     """
     c = Canvas()
     for node in self.nodes.itervalues():
         self.draw_node(c, node)
     for edge in self.edges:
         self.draw_edge(c, edge)
     print(c.frame())
コード例 #10
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()
コード例 #11
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')
コード例 #12
0
ファイル: gameoflife.py プロジェクト: A1rPun/GameOfLife
def main(stdscr):
    stdscr.nodelay(1)
    curses.curs_set(0)

    termSize = getTerminalSize()
    argsSize = len(sys.argv)
    WIDTH = min((int(sys.argv[1]) if argsSize > 1 else 64), termSize[0] * 2)
    HEIGHT = min((int(sys.argv[2]) if argsSize > 2 else 64), termSize[1] * 4)
    FRAMES = 4
    display = Canvas()
    grid = getGrid(WIDTH, HEIGHT)

    addPentomino(grid, int(WIDTH / 2), int(HEIGHT / 2))
    drawGrid(display, grid, stdscr)
    time.sleep(1. / FRAMES)

    while True:
        grid = updateGrid(grid, WIDTH, HEIGHT)
        drawGrid(display, grid, stdscr)
        key = stdscr.getch()
        if key == ord('q'):
            break
        elif key == ord('s'):
            addPentomino(grid, int(WIDTH / 2), int(HEIGHT / 2))
        elif key == curses.KEY_UP:
            FRAMES += 1 if FRAMES < 60 else 0
        elif key == curses.KEY_DOWN:
            FRAMES -= 1 if FRAMES > 2 else 0
        time.sleep(1. / FRAMES)
コード例 #13
0
ファイル: widget.py プロジェクト: sysr-q/wopr
 def mkcanvases():
     d = {
         "data": collections.deque([], maxlen=maxlen),
         "canvas": Canvas(),
         "attr": curses.color_pair(random.choice([1, 2, 3, 4, 5])),
         "dirty": True,
     }
     return d
コード例 #14
0
ファイル: image2term.py プロジェクト: lzskiss/drawille
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)
コード例 #15
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()
コード例 #16
0
ファイル: image2term3.py プロジェクト: zhengsongyue/drawille
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)
コード例 #17
0
ファイル: main.py プロジェクト: zaftzaft/terminal-anime
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
コード例 #18
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)
コード例 #19
0
ファイル: pong.py プロジェクト: tomparks/Terminal-pong
def setup():
    # set the size of the board to the size of the terminal at ther start
    width, height = os.popen('stty size', 'r').read().split()
    height, width = 50, 50
    board = Canvas()
    frame = (0, 0, width, height)
    assert(frame[YSEC] == height)
    board.frame(*frame)
    draw_bounds(board, frame)

    # get some paddles
    lpaddle = Paddle('left', board, frame)
    rpaddle = Paddle('right', board, frame)
    ball = Ball(board, frame)

    # get some output!
    stdscr = curses.initscr()
    stdscr.refresh()
    return (lpaddle, rpaddle, ball), board, frame, stdscr
コード例 #20
0
ファイル: server.py プロジェクト: staceb/sshoneypot
    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)
コード例 #21
0
ファイル: __init__.py プロジェクト: ikornaselur/scatterping
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()
コード例 #22
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 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)
コード例 #23
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()
コード例 #24
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()
コード例 #25
0
ファイル: ui.py プロジェクト: ajaiswal-ht/imdino
    def update(self):
        '''
            Update the form in background
        '''
        # get the information
        try:

            # game Stats
            row1 = [
                'Status: %s' % (self.learn.state, ),
                'Fitness: %s ' % (self.gm.points, ),
                'GameStatus: %s ' % (self.gm.gamestate, ),
                'Generation: %s : %s/%s' %
                (self.learn.generation, self.learn.genome,
                 len(self.learn.genomes))
            ]
            self.genome_stats.values = row1
            self.genome_stats.display()
            if self.gm.gameOutput:
                row2 = 'Action: %s \n Activation: %s \n' % (
                    self.gm.gameOutputString, self.gm.gameOutput)

            else:
                row2 = 'Loading...'
            self.game_stats.value = row2
            self.game_stats.display()

            ### current state
            network_canvas = Canvas()
            y = {
                'size': self.gm.sensors[0].size,
                'distance': self.gm.sensors[0].value,
                'speed': self.gm.sensors[0].speed,
                'activation': self.gm.gameOutput
            }
            self.network_chart.value = (self.draw_chart(network_canvas,y)) + \
            '\n   %s     %s    %s    %s  \n     Distance         Size          Speed            Activation\n' % (self.gm.sensors[0].value,
                self.gm.sensors[0].size,self.gm.sensors[0].speed,self.gm.gameOutput)
            self.network_chart.display()
            #self.logger.info(self.gm.gameOutput)

        # catch the KeyError caused to c
        # cumbersome point of reading the stats data structures
        except KeyError:
            pass
コード例 #26
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
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()
コード例 #27
0
ファイル: __init__.py プロジェクト: gooofy/drawilleplot
    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()
コード例 #28
0
ファイル: image2term.py プロジェクト: ubunatic/drawille
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)
コード例 #29
0
 def spawn(self):
     while(True):
         self.spawn_next()
         print(chr(27) + "[2J")
         _canvas = Canvas()
         for room in self.queue:
             draw(_canvas, room)
         print(_canvas.frame())
         if self.total_amount_required == 0:
             # seal all doors
             for room in self.queue:
                 for door in room.available_doors:
                     room.doors.remove(door)
             print(chr(27) + "[2J")
             _canvas = Canvas()
             for room in self.queue:
                 draw(_canvas, room)
             print(_canvas.frame())
             break
         time.sleep(0.05)
コード例 #30
0
ファイル: image2term.py プロジェクト: ChrisOHu/vimrc
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)
コード例 #31
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()
コード例 #32
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
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)
コード例 #33
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 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), '')
コード例 #34
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 def test_set_text(self):
     c = Canvas()
     c.set_text(0, 0, "asdf")
     self.assertEqual(c.frame(), "asdf")
コード例 #35
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 def test_clear(self):
     c = Canvas()
     c.set(1, 1)
     c.clear()
     self.assertEqual(c.chars, dict())
コード例 #36
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 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_max_min_limits(self):
     c = Canvas()
     c.set(0, 0)
     self.assertEqual(c.frame(min_x=2), '')
     self.assertEqual(c.frame(max_x=0), '')
コード例 #38
0
 def test_frame(self):
     c = Canvas()
     self.assertEqual(c.frame(), '')
     c.set(0, 0)
     self.assertEqual(c.frame(), 'РаЂ')
コード例 #39
0
 def test_set_text(self):
     c = Canvas()
     c.set_text(0, 0, "asdf")
     self.assertEqual(c.frame(), "asdf")
コード例 #40
0
 def test_toggle(self):
     c = Canvas()
     c.toggle(0, 0)
     self.assertEqual(c.chars, {0: {0: 1}})
     c.toggle(0, 0)
     self.assertEqual(c.chars, dict())
コード例 #41
0
 def test_clear(self):
     c = Canvas()
     c.set(1, 1)
     c.clear()
     self.assertEqual(c.chars, dict())
コード例 #42
0
ファイル: tests.py プロジェクト: chrisrammy/drawille
 def test_unset_empty(self):
     c = Canvas()
     c.set(1, 1)
     c.unset(1, 1)
     self.assertEqual(c.pixels, dict())
コード例 #43
0
ファイル: tests.py プロジェクト: chrisrammy/drawille
 def test_set(self):
     c = Canvas()
     c.set(1, 1)
     self.assertTrue(1 in c.pixels and 1 in c.pixels[1])
コード例 #44
0
ファイル: game_of_life.py プロジェクト: glindste/gol
 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)]
コード例 #45
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 def test_set(self):
     c = Canvas()
     c.set(0, 0)
     self.assertTrue(0 in c.chars and 0 in c.chars[0])
コード例 #46
0
 def test_set(self):
     c = Canvas()
     c.set(0, 0)
     self.assertTrue(0 in c.chars and 0 in c.chars[0])
コード例 #47
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 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)
コード例 #48
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()
コード例 #49
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 def test_toggle(self):
     c = Canvas()
     c.toggle(0, 0)
     self.assertEqual(c.chars, {0: {0: 1}})
     c.toggle(0, 0)
     self.assertEqual(c.chars, dict())
コード例 #50
0
ファイル: basic.py プロジェクト: MB6/drawille
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))
コード例 #51
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 def test_frame(self):
     c = Canvas()
     self.assertEqual(c.frame(), '')
     c.set(0, 0)
     self.assertEqual(c.frame(), 'РаЂ')
コード例 #52
0
ファイル: GUI.py プロジェクト: bryant1410/ptop
    def update(self):
        '''
            Update the form in background
        '''
        # get the information
        try:
            disk_info = self.statistics['Disk']['text']['/']
            swap_info = self.statistics['Memory']['text']['swap_memory']
            memory_info = self.statistics['Memory']['text']['memory']
            processes_info = self.statistics['Process']['text']
            system_info = self.statistics['System']['text']
            cpu_info = self.statistics['CPU']['graph']

            # overview
            row1 = "Disk Usage (/) {4}{0: <6}/{1: >6} MB{4}{2: >2} %{5}Processes{4}{3: <8}".format(
                disk_info["used"], disk_info["total"], disk_info["percentage"],
                processes_info["running_processes"],
                " " * int(4 * self.X_SCALING_FACTOR),
                " " * int(9 * self.X_SCALING_FACTOR))

            row2 = "Swap Memory    {4}{0: <6}/{1: >6} MB{4}{2: >2} %{5}Threads  {4}{3: <8}".format(
                swap_info["active"], swap_info["total"],
                swap_info["percentage"], processes_info["running_threads"],
                " " * int(4 * self.X_SCALING_FACTOR),
                " " * int(9 * self.X_SCALING_FACTOR))

            row3 = "Main Memory    {4}{0: <6}/{1: >6} MB{4}{2: >2} %{5}Boot Time{4}{3: <8}".format(
                memory_info["active"], memory_info["total"],
                memory_info["percentage"], system_info['running_time'],
                " " * int(4 * self.X_SCALING_FACTOR),
                " " * int(9 * self.X_SCALING_FACTOR))

            self.basic_stats.value = row1 + '\n' + row2 + '\n' + row3
            self.basic_stats.display()

            ### cpu_usage chart
            cpu_canvas = Canvas()
            next_peak_height = int(
                math.ceil(
                    (float(cpu_info['percentage']) / 100) * self.CHART_HEIGHT))
            self.cpu_chart.value = (self.draw_chart(cpu_canvas,
                                                    next_peak_height, 'cpu'))
            self.cpu_chart.display()

            ### memory_usage chart
            memory_canvas = Canvas()
            next_peak_height = int(
                math.ceil((float(memory_info['percentage']) / 100) *
                          self.CHART_HEIGHT))
            self.memory_chart.value = self.draw_chart(memory_canvas,
                                                      next_peak_height,
                                                      'memory')
            self.memory_chart.display()

            ### processes_table
            processes_table = self.statistics['Process']['table']

            # check sorting flags
            if MEMORY_SORT:
                sorted_table = sorted(processes_table,
                                      key=lambda k: k['memory'],
                                      reverse=True)
            elif TIME_SORT:
                sorted_table = sorted(processes_table,
                                      key=lambda k: k['rawtime'],
                                      reverse=True)
            else:
                sorted_table = processes_table

            # to keep things pre computed
            temp_list = []
            for proc in sorted_table:
                if proc['user'] == system_info['user']:
                    temp_list.append(
                        "{0: <30} {1: >5}{5}{2: <10}{5}{3}{5}{4: >6.2f} % \
                    ".format((proc['name'][:25] + '...')
                             if len(proc['name']) > 25 else proc['name'],
                             proc['id'], proc['user'], proc['time'],
                             proc['memory'],
                             " " * int(5 * self.X_SCALING_FACTOR)))
            self.processes_table.entry_widget.values = temp_list
            self.processes_table.display()

        # catch the f*****g KeyError caused to c
        # cumbersome point of reading the stats data structures
        except KeyError:
            pass
コード例 #53
0
ファイル: lib.py プロジェクト: Tacolizard/arith
from drawille import Canvas, line, Turtle, polygon
from colorama import *
from math import sin, radians


init()
c = Canvas()
c.clear()
pnts = []
t = Turtle()
tpos = []


class plot:

	def lnres(inres):
		res = inres
				
	def printc(color):
		for x,y in pnts:
			c.set(x,y)
		if color == 'green':
			print(Fore.GREEN+c.frame())
		if color == 'red':
			print(Fore.RED+c.frame())
		if color == 'yellow':
			print(Fore.YELLOW+c.frame())
		if color == 'blue':
			print(Fore.BLUE+c.frame())
		if color == 'cyan':
			print(Fore.CYAN+c.frame())
コード例 #54
0
ファイル: xkcd.py プロジェクト: hakatashi/dotfiles
        usage()
    c = urlopen(url).read().decode('utf-8')
    img_url = 'https:' + ''.join(re.search('src="(\/\/imgs.xkcd.com\/comics\/.*\.)(jpg|png)"', c).groups())
    i = Image.open(BytesIO(urlopen(img_url).read())).convert('L')
    w, h = i.size
    tw, th = shutil.get_terminal_size((80, 25))
    tw -= 1
    th -= 10
    tw *= 2
    th *= 4
    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
コード例 #55
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
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()
コード例 #56
0
ファイル: game_of_life.py プロジェクト: glindste/gol
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
コード例 #57
0
ファイル: parabola.py プロジェクト: vasartori/parabola
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()
コード例 #58
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
    pu = up
    pd = down
    fd = forward
    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()
コード例 #59
0
ファイル: speed_test.py プロジェクト: lleixat/vim-minimap
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()
コード例 #60
0
ファイル: tests.py プロジェクト: chrisrammy/drawille
 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}})