2010-04-28 19 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中找到。

相關問題