LoginSignup
4
7

More than 5 years have passed since last update.

単純な文字列アニメーション

Last updated at Posted at 2017-08-17

常識かもしれませんが、文字列で簡易的にアニメーションする方法を書いてみます。
こんな感じのアニメーションが作れます。

プゲラ.gif

アヒャヒャヒャ(゚∀゚)ヒャヒャヒャ.gif

Python 3.6.1で作っていますが、原理的に言語が違っても作成できます。
キャリッジリターンが認識される環境ならば思い通りに表示されると思います。

仕組みは、単純です。

  1. printの改行を抑制する
  2. 文字列を表示させたらキャリッジリターンを表示させる

の2つだけです。
後は、アニメーションらしく表示間隔を調整してやらばそれらしく見えます。

一番単純なものは以下のようなものでしょうか。

python
import time
interval = 0.50
print("1     \r", end="")
time.sleep(interval)
print(" 2    \r", end="")
time.sleep(interval)
print("  3   \r", end="")
time.sleep(interval)
print("   4  \r", end="")
time.sleep(interval)
print("    5 \r", end="")
time.sleep(interval)
print("      \r", end="")
time.sleep(interval)

もう少しプログラムらしくすると、以下のような感じになります。

python
import time

def animation(sts, times=3, interval=0.25):
  for n in range(times):
    for st in sts:
      print(st, end="")
      time.sleep(interval)
      print("\r", end="")
  print()

sts = [
    "  (・∀・)       ",
    "  (・∀・)ニヤ     ",
    "  (・∀・)ニヤニヤ   ",
    "  (・∀・)ヒャ     ",
    "  (・∀・)ヒャヒャ   ",
    "  (・∀・)プゲラ  ",
]

times = 3
interval = 0.25
animation(sts, times, interval)
4
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7