2010-04-28 16 views

回答

11

我只是移植用gif动画,以ASCII动画从我的答案here到Python我的例子。您需要安装here中的pyglet库,因为python不幸没有内置的动画gif支持。希望你喜欢它:)

import pyglet, sys, os, time 

def animgif_to_ASCII_animation(animated_gif_path): 
    # map greyscale to characters 
    chars = ('#', '#', '@', '%', '=', '+', '*', ':', '-', '.', ' ') 
    clear_console = 'clear' if os.name == 'posix' else 'CLS' 

    # load image 
    anim = pyglet.image.load_animation(animated_gif_path) 

    # Step through forever, frame by frame 
    while True: 
     for frame in anim.frames: 

      # Gets a list of luminance ('L') values of the current frame 
      data = frame.image.get_data('L', frame.image.width) 

      # Built up the string, by translating luminance values to characters 
      outstr = '' 
      for (i, pixel) in enumerate(data): 
       outstr += chars[(ord(pixel) * (len(chars) - 1))/255] + \ 
          ('\n' if (i + 1) % frame.image.width == 0 else '') 

      # Clear the console 
      os.system(clear_console) 

      # Write the current frame on stdout and sleep 
      sys.stdout.write(outstr) 
      sys.stdout.flush() 
      time.sleep(0.1) 

# run the animation based on some animated gif 
animgif_to_ASCII_animation(u'C:\\some_animated_gif.gif') 
+0

没有用python 3.x进行测试,我的电脑上只有2.6。如果任何人都可以在3.x上测试:会很棒。 – 2010-05-07 01:15:49

+2

实际上提供的代码为 – Adam 2010-05-07 01:19:07

+0

我已经在python 3.5.2上试过了,但不幸的是编译器声明存在这样的错误:TypeError:ord()期望的长度为1的字符串,但找到了int。 SO中的一些答案指出应删除ord()函数。但是当你这样做的时候,它也会从与以下相同的行中断开:TypeError:元组索引必须是整数或切片,而不是浮点数。所以我相信我需要有人来测试这个:) – Prometheus 2017-01-20 13:27:09

2

简单的控制台动画,在Ubuntu的python3测试。 addch()不喜欢那个非ascii字符,但它在addstr()中起作用。

#this comment is needed in windows: 
# encoding=latin-1 
def curses(win): 
    from curses import use_default_colors, napms, curs_set 
    use_default_colors() 
    win.border() 
    curs_set(0) 

    row, col = win.getmaxyx() 
    anim = '.-+^°*' 
    y = int(row/2) 
    x = int((col - len(anim))/2) 
    while True: 
     for i in range(6): 
      win.addstr(y, x+i, anim[i:i+1]) 
      win.refresh() 
      napms(100) 
      win.addch(y, x+i, ' ') 

if __name__ == "__main__": 
    from curses import wrapper 
    wrapper(curses) 

@Philip Daubmeier:我Windoze下进行测试这一点,它不工作:(有三种基本选择前进。(请选择)

  1. 安装第三三方Windows的诅咒库(http://adamv.com/dev/python/curses/
  2. 应用Windows-诅咒补丁蟒蛇(http://bugs.python.org/msg94309
  3. 完全放弃诅咒别的东西。
+0

你安装了pyglet吗?哪个错误信息显示出来?我测试了它,就像我在窗口上用python 2.6和'cmd'控制台所说的那样工作。 – 2010-05-07 18:23:58

+0

顺便说一句:你不一定需要使用诅咒,就像你在我的答案中看到的那样。 – 2010-05-07 18:26:18

2

这正是我为asciimatics所创建的那种应用。

它是一个跨平台的控制台API,支持从丰富的文本效果中生成动画场景。它已被证明可以用于CentOS,Windows和OSX的各种风格。

可以从gallery获得可能的样品。这里有一个类似于其他答案中提供的动画GIF代码的示例。

Colour images

我假设你只是寻找一个方式做任何动画,但如果你真的想复制的蒸汽火车,你可以将其转换为雪碧,给它只是运行路径它穿过屏幕,然后作为场景的一部分播放。对象的完整解释可以在docs中找到。

相关问题