如何使用Python 3.x在控制台应用程序中创建ASCII动画? [英] How to create ASCII animation in a console application using Python 3.x?

查看:164
本文介绍了如何使用Python 3.x在控制台应用程序中创建ASCII动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将此问题移植到Python(Windows + Linux + Mac OS)

I would like to port this question to Python (Windows + Linux + Mac Os)

How to create ASCII animation in Windows Console application using C#?

谢谢!

推荐答案

我刚刚将我的示例(带有动画gif)从答案移植到ASCII动画< a href = https://stackoverflow.com/questions/2725529/how-to-create-ascii-animation-in-windows-console-application-using-c/2725584#2725584>此处至python 。您需要从此处安装pyglet库,因为不幸的是python没有内置动画-gif支持。希望您喜欢它:)

I just ported my example with the animated gif to ASCII animation from my answer here to python. You will need to install the pyglet library from here, as python unfortunately has no built-in animated-gif support. Hope you like it :)

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')

这篇关于如何使用Python 3.x在控制台应用程序中创建ASCII动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆