登录  | 立即注册

游客您好!登录后享受更多精彩

查看: 848|回复: 0

[Python教程] 【Python】代码雨源码

[复制链接]

444

主题

509

帖子

2051

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2051

荣誉管理论坛元老

发表于 2021-6-30 22:29:53 来自手机 | 显示全部楼层 |阅读模式 来自:
  1. #!/usr/bin/env python3- ?6 H) Y1 h' |
  2. #
    ) _5 q3 u  X4 L
  3. # unimatrix.py* p7 M/ ^8 N( s: D. R# |1 M! y
  4. # <https://github.com/will8211/unimatrix>" I3 y% R; x  y1 s
  5. #
    % N3 ]0 O" `& F9 v5 V: z1 m
  6. # Python script to simulate the display from "The Matrix" in terminal. Uses
    ( A; S6 r$ v& _5 U, l0 m0 E
  7. # half-width katakana unicode characters by default, but can use custom
    4 V. z6 T" C/ r) O2 a
  8. # character sets. Accepts keyboard controls while running.
    9 [  p6 `2 b; d
  9. #: n/ e- T8 ^# [
  10. # Based on CMatrix by Chris Allegretta and Abishek V. Ashok. The following, v5 [. V5 ~$ k" `8 T! s. d
  11. # option should produce virtually the same output as CMatrix:
    % Z7 F1 N) ^9 c( }' `
  12. # $ unimatrix -n -s 96 -l o1 t/ Y* N) }  C
  13. #
    . k% S, _) x! \2 z
  14. # Unimatrix is free software: you can redistribute it and/or modify it under" A1 r8 N3 e) r6 a# g
  15. # the terms of the GNU General Public License as published by the Free Software
    3 I! V7 F3 v" P0 f2 g
  16. # Foundation, either version 3 of the License, or (at your option) any later) {. T0 q7 N7 C4 }/ k
  17. # version.
    . [( ~8 c5 ]- E4 g  h
  18. #
    5 K- r: a; `+ o4 h$ N6 T8 i" _
  19. # Unimatrix is distributed in the hope that it will be useful, but WITHOUT ANY
    + S, |, @, Q+ x( w9 \
  20. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
    & q, Z0 w+ n3 M; [7 Z/ J1 I
  21. # A PARTICULAR PURPOSE.  See the GNU General Public License at
    ; X# n& @+ C* J# U
  22. # <http://www.gnu.org/licenses/> for more details.
    9 L4 n+ v) }3 y1 y2 ^
  23. #
    7 M  q( ]4 D2 g$ |6 M
  24. # Created by William Mannard4 ~" a2 a# n  I2 u
  25. # 2018/01/19
    / H+ h. v4 J5 S4 h+ f

  26. / W& Z, d9 M# @9 _3 i
  27. import argparse- G! Q8 o! t, F; C0 H9 a. r2 y
  28. import curses
    3 {9 q4 f  f2 \. J, N/ c8 v
  29. import time2 }  ^( |; M# L& [( ~1 Z  o
  30. from random import choice, randint% f) F6 ^' E( D3 g" Z. U  K( I
  31. 3 W8 c9 L* R" I
  32. help_msg = '''
    : Z: |% Z8 i- ]
  33. USAGE
    ( o( Y8 Z1 N8 G6 ]8 ~* {1 z1 L
  34.   unimatrix [-a] [-b] [-c COLOR] [-f] [-g COLOR] [-h] [-l CHARACTER_LIST] [-n]
    ( m0 t5 H$ x& A, Z' b
  35.             [-o] [-s SPEED] [-u CUSTOM_CHARACTERS]
    , N  T* L  |) Q1 B
  36. % |7 B$ {) \6 u/ E  T! s
  37. OPTIONAL ARGUMENTS0 ?$ Q% b% }( |4 Y% F
  38.   -a                   Asynchronous scroll. Lines will move at varied speeds.
    . g7 y0 V; T( t; D/ J7 p

  39. 9 P3 U2 e+ z7 G1 s3 e
  40.   -b                   Use only bold characters+ q! ~3 |. d) Q% s5 g

  41. % M- [! l6 S, L- W" a: r) Q9 M
  42.   -c COLOR             One of: green (default), red, blue, white, yellow, cyan,
    , T6 H1 w+ [) M+ T& e1 P8 M
  43.                        magenta, black
    ! @$ y+ ?! {5 K$ Y& m
  44. $ t  Z* z4 s( _7 g+ ~+ `) h
  45.   -f                   Enable "flashers," characters that continuously change.
    , e2 A: w# p2 n4 [
  46. 2 x' J: D. W, r# _/ Q3 B
  47.   -g COLOR             Background color (See -c). Defaults to keeping
    8 W$ h0 e% [( [
  48.                        terminal's current background.) @) h: m) x, k* }

  49. : l+ W" T  b1 `
  50.   -h                   Show this help message and exit% I3 Q3 D) ]/ Z" L! a
  51. ) D( S' O- [- A0 v8 `
  52.   -l CHARACTER_LIST    Select character set(s) using a string over letter
    : [) r! l5 l# i/ `6 Y
  53.                        codes (see CHARACTER SETS below.). i$ G* t/ V$ \1 [  C, e# p/ L5 K! @
  54. : e# f$ u7 }3 Z9 P+ \& Q
  55.   -n                   Do not use bold characters (overrides -b)$ Y6 R  O- b* b5 m  w

  56. 9 i2 Y0 K: G1 o$ a9 o# [# a7 s2 I; k
  57.   -o                   Disable on-screen status
    , p. g* @8 ?. Q  i$ X" P$ M' Y

  58. ) z. o; x4 M/ C" F% j5 d+ V
  59.   -s SPEED             Integer up to 100. 0 uses a one-second delay before
    8 o) m9 R! q( L7 ?& o7 S. ]+ Z& l
  60.                        refreshing, 100 uses none. Use negative numbers for9 ~0 B5 ~  t7 h* k2 Z  B
  61.                        even lower speeds. Default=854 b# P9 L' m' v/ g3 V+ {& [
  62. 5 n: x$ |/ A' @4 d% ^/ [/ ^
  63.   -t TIME              Exit the process after TIME seconds3 ^# u& q$ n& B

  64. 6 q, x' P3 T7 `/ {! d5 H
  65.   -u CUSTOM_CHARACTERS Your own string of characters to display. Enclose in
    + C- |/ Z, q9 z( L4 a3 J
  66.                        single quotes ('') to escape special characters. For+ K1 Y  E4 z# D8 k/ p! ~' @1 p
  67.                        example: -u '#$('3 W: R. c, k4 @4 w+ N
  68. & G. J. Z  v, w# f0 G
  69.   -w                   Single-wave mode: Does a single burst of green rain,+ ?, S* B3 ^% y9 j3 \9 m0 ^+ Q1 m1 N5 Y
  70.                        exits. You can put in a .bashrc file to run when your' _- w& r9 Z. c
  71.                        terminal launches. Works well with speed at 95.! c% A4 ~3 W: X4 C( g! I

  72. , e: a0 W5 m. W6 }* v
  73. LONG ARGUMENTS
    & @8 @; i! Q# Q0 R5 w4 K
  74.   -a --asynchronous
    . A6 y' f6 H% n' a! H2 L* s
  75.   -b --all-bold
    * w* g* j3 r6 }
  76.   -c --color=COLOR( ^1 H4 I7 n, G$ c% p0 K
  77.   -f --flashers
      q( J3 ^6 s) |  n- }9 I% T6 D
  78.   -g --bg-color=COLOR/ A$ S: `7 G- _: w
  79.   -h --help
    " I% r& N$ K" `! J0 _. A1 r$ [* y9 B' i$ [
  80.   -l --character-list=CHARACTER_LIST: ^! ]  k* j# t) ]% M6 [7 `
  81.   -s --speed=SPEED
    4 r  I; M: x, g* o
  82.   -n --no-bold9 x/ ~) c$ ]8 I. [, D
  83.   -o --status-off5 E/ R- j( l5 a1 N0 V& _# }
  84.   -t --time
    " }( V$ E7 R  P2 g- r/ V" `
  85.   -u --custom_characters=CUSTOM_CHARACTERS  i% q5 [! i7 l, H4 I7 Y
  86.   -w --single_wave5 [, v& \/ k# A+ y  \

  87. 0 q, Z5 a( L- K! ~: f6 x
  88. CHARACTER SETS
    ( b: J: c% {! A4 Y& w1 \6 i
  89.   When using '-l' or '--character_list=' option, follow it with one or more of5 d+ Y* d  _% t! l% E1 d
  90.   the following letters:
    6 ]3 m8 l% Z  N: L3 p

  91. 5 K6 n9 t  H+ o  D" s0 ~
  92.   a   Lowercase alphabet' C6 Z6 n& u& I7 \
  93.   A   Uppercase alphabet, m* K! @; Q+ \0 v
  94.   c   Lowercase Russian Cyrillic alphabet; V) S# A: g. L1 Q
  95.   C   Uppercase Russian Cyrillic alphabet  G7 c% X5 N# K2 F& I5 ?
  96.   e   A few common emoji ( ☺☻✌♡♥❤⚘❀❃❁✼☀✌♫♪☃❄❅❆☕☂★ )
    ( }) n$ {# U6 v" W2 a2 n- k/ p! Q  O
  97.   g   Lowercase Greek alphabet
    ! k) Q0 M4 |( g4 Q# s7 C
  98.   G   Uppercase Greek alphabet" y/ I# x- @9 J' P( t- g
  99.   k   Japanese katakana (half-width)) r* b  s/ N# u+ m2 M
  100.   m   Default 'Matrix' set, equal to 'knnssss'' a1 U; i4 o) X% A/ T
  101.   n   Numbers 0-9/ y' D! ]" y1 u" m+ J3 V
  102.   o   'Old' style non-unicode set, like cmatrix. Equal to 'AaSn'0 g0 e  D9 _6 ^6 H% z2 R6 j/ Y
  103.   p   Klingon pIqaD (requires 'Horta' family font)*' r7 U! L& Q1 z1 D/ {, W! x
  104.   P   Klingon pIqaD (requires 'Klingon-pIqaD' or 'Code2000' family font)** o5 ]  ]: C* u" ]1 u( Z
  105.   r   Lowercase Roman numerals ( mcclllxxxxvvvvviiiiii )
    - [3 u9 i, g! u2 ?6 l9 w9 R
  106.   R   Uppercase Roman numerals ( MCCLLLXXXXVVVVVIIIIII ), m5 A7 z0 J% x# t/ `! o4 E! b! Z
  107.   s   A subset of symbols actually used in the Matrix films ( -=*_+|:<>" )
    8 y( [! O5 ?! C. ^: T
  108.   S   All common keyboard symbols ( `-=~!z#$%^&*()_+[]{}|\;':",./<>?" )* ]' P% R- C; [+ L2 ]6 f
  109.   u   Custom characters selected using -u switch
    ; c1 M2 \8 @& M( y: V6 C/ h
  110. + B. J; v7 l# H
  111.   For example: '-l naAS' or '--character_list=naAS' will give something similar! l- y' Q+ D7 z* _# w
  112.   to the output of the original cmatrix program in its default mode.& }  l9 N7 R) h0 |# J& P: Y1 \) \0 n
  113.   '-l ACG' will use all the upper-case character sets. Use the same
    6 m3 [8 d$ m5 O7 Z5 O5 L4 y, h% v
  114.   letter multiple times to increase the frequency of the character set. For
    - r& }$ M: i5 X) ~
  115.   example, the default setting is equal to '-l knnssss'." \" y) o. B, A; k( l0 F$ N
  116. 9 l& Y3 j( Z8 d1 ]
  117.   * With most modern Linux terminals (gnome-terminal, konsole, lxterminal,3 l$ V6 h4 d( S8 ?
  118.     xfce4-terminal, mate-terminal) simply having the font installed system-wide6 s  n3 q. ~, z
  119.     is enough. The terminal will fall back to it for the Klingon, meaning that9 }4 N- `8 Y$ j; L2 ?
  120.     you don't have to select the font in your terminal settings. 'Horta' seems
    + E$ U; _# U$ ]8 |) w; d
  121.     not to work in Konsole. Fonts may need to be set manually as fallbacks in
    " }& G/ V3 D% G- T
  122.     .Xresources for older terminals, such as urxvt and xterm.; ^9 A0 J; u6 k3 U' t  j# J

  123. / F: ?. X- W$ J" @( w$ ^
  124. KEYBOARD CONTROL
    # m+ X+ g$ j0 Z; T: }, X- Z; z% {
  125.   SPACE, CTRL-c or q   exit
    $ }  Z/ w0 a* C/ m" h
  126.   - or LEFT            decrease speed by 1
    ; A" _* u* K) b) B
  127.   + or RIGHT           increase speed by 1) n/ K) F. [3 b
  128.   [ or DOWN            decrease speed by 10' `  J1 {3 S# H+ @
  129.   ] or UP              increase speed by 10* t* |2 T. c; }; x
  130.   a                    toggle asynchronous scrolling
    3 ?) i6 a6 L; k: t# h/ s$ X
  131.   b                    cycle through bold character options7 b" p5 ?, I6 x, b  }7 T
  132.                            (bold off-->bold on-->all bold)
    1 o7 I; c4 U" H. q8 z
  133.   f                    toggle flashing characters
    6 t- g) y" `/ `
  134.   o                    toggle on-screen status
    : M! V2 @$ ^$ j% Y& }) _3 ~
  135.   1 to 9               set color: (1) Green   (2) Red   (3) Blue     (4) White, t. \/ O: X' S/ u5 K( B
  136.                                   (5) Yellow  (6) Cyan  (7) Magenta  (8) Black; w4 w, P1 g7 p7 _) Z6 c
  137.                                   (9) Terminal default
    * c  U1 M& N; k# ?
  138.   ! to (               set background color (same colors as above, but pressing: L4 d- R9 f( \1 R- @
  139.                            shift + number)
    ( J0 H7 a$ y2 q- Y0 i  _

  140. $ ?0 i7 h: i# E& b/ x2 c! x+ j
  141. EXAMPLES2 f* N$ I  ?/ I# D0 S% E
  142.   Mimic default output of cmatrix (no unicode characters, works in TTY):7 y. Z0 q: x& G- V( r$ g4 d" b
  143.     $ unimatrix -n -s 96 -l o& N/ @0 K3 Q' W. b5 B6 l6 H( L
  144. $ @6 J0 U" t; k! a( I& F2 |
  145.   Use the letters from the name of your favorite operating system in bold blue:
    " |+ Z2 @. i" {" J
  146.     $ unimatrix -B -u Linux -c blue" b, O$ o9 @4 ~& e) h# u2 U& ~3 a4 q
  147. & `' \' i  o2 O: D4 U9 e
  148.   Use default character set, plus dollar symbol (note single quotes around
    4 W# E- P& m3 r. E, [
  149.       special character):- w& M* b/ K: ~. v1 C" f( a
  150.     $ unimatrix -l knnssssu -u '$'5 o3 |/ `+ R6 ^' F. F0 a) i

  151. : C, ]5 Z% r* o/ U
  152.   No bold characters, slowly, using emojis, numbers and a few symbols:7 u: c# W" J& T. {3 c# Q, q/ h
  153.     $ unimatrix -n -l ens -s 50
    * u7 y. y# S% t
  154. '''* |5 ~6 s5 z& `0 Y

  155. 8 L3 z& y/ h- o) V9 z# S) S8 Z
  156. ### Set up parser and apply arguments settings
    6 h8 d1 T# j+ V$ f/ ~
  157. ' S0 Q% y9 H* N# `9 r
  158. parser = argparse.ArgumentParser(add_help=False)
    : V: a1 c8 }2 B) q

  159. 5 f% k5 B! b) p9 Q
  160. parser.add_argument('-a', '--asynchronous',
    ) p8 E$ M! e; z2 r; ]# y1 I2 s
  161.                     action='store_true',! c8 I% |" }# }/ R6 l% B" b( c
  162.                     help='use asynchronous scrolling')$ C6 R/ ~0 J0 ]  z  I3 R% W
  163. parser.add_argument('-b', '--all-bold',
    / F  _! a4 ^: _3 z  S+ K: m6 H7 s
  164.                     action='store_true',3 u& ^/ b3 z1 E. T4 |8 `
  165.                     help='use all bold characters')
      Y; U; ~1 Y7 h: E
  166. parser.add_argument('-c', '--color',
    - D/ o4 `  A$ m  W5 D4 V6 t
  167.                     default='green',# T# }- F9 J  d! O6 T
  168.                     help='one of: green (default), red, blue, white, yellow, \; F- C) b; m5 r7 }
  169.                           cyan, magenta, black',5 M5 \0 K( m/ p* ^
  170.                     type=str)
    ' K+ d1 e& s2 D/ |% ~
  171. parser.add_argument('-f', '--flashers',
    + n7 B# H0 H5 L; U2 o( l( I+ [& l
  172.                     action='store_true',  I  p  J# h2 v; }; R
  173.                     help='some characters will continuously change in place')7 b& A. V4 y" t, ]5 [$ e5 D
  174. parser.add_argument('-g', '--bg-color',$ I6 [& L6 o9 E" B* n; v
  175.                     default='default',
    , @$ A% [; |. z( D) i' C) y
  176.                     help='background color (see -c)',8 A9 l/ ?) h/ i1 h* e7 q. @. w
  177.                     type=str)9 Y' q" x" k" X/ `' j
  178. parser.add_argument('-h', '--help',
    9 x2 u) J" V6 Y0 _
  179.                     help='display extended usage information and exit.',- }  b6 i0 }# G3 |5 g# {
  180.                     action='store_true')
    $ f1 u: P  d9 l
  181. parser.add_argument('-l', '--character-list',
    4 [6 K) Y. R% d4 s( {
  182.                     help='character set. See details below',
    9 V9 h: s# @$ E# x0 U
  183.                     type=str)9 g# ^! b& D. p
  184. parser.add_argument('-n', '--no-bold',& g' s+ w. g  _7 `1 V
  185.                     action='store_true',+ F1 W0 D2 A  O4 a2 C
  186.                     help='do not use bold characters')3 w: S, |2 j8 k9 |
  187. parser.add_argument('-o', '--status-off',: e3 K* S* X1 u5 P5 R
  188.                     action='store_true',
    8 W3 i' G3 B$ j3 |
  189.                     help='Disable on-screen status')  X, }+ c" `* Z5 H& y
  190. parser.add_argument('-s', '--speed',
    + h: X1 B; B7 Q
  191.                     help='speed, integer up to 100. Default=85',& R3 Z6 b4 r& o/ `% `
  192.                     default=85,
    % ~5 h2 X" n, F2 h% n) j
  193.                     type=int)0 L( {: D9 y' Q4 a2 {: y0 J
  194. parser.add_argument('-t', '--time',7 V) h/ E8 _7 ]3 D
  195.                     help='time. See details below',
    : o: j1 q& e- }% s1 C4 r6 s
  196.                     type=int)
    9 E6 B6 h" c% o% F
  197. parser.add_argument('-u', '--custom-characters',0 n' D' t3 v2 m5 g+ c3 J' K
  198.                     help='your own string of characters to display',- L4 J( X- |/ h  R
  199.                     default='',' V* I$ `5 ?! U' N( e
  200.                     type=str)$ v' Q& n# G& z( q% c8 L* F& v
  201. parser.add_argument('-w', '--single-wave',
    ( P; e) P: a" E
  202.                     help='runs a single "wave" of green rain then exits',
    7 }  H' t9 u$ @8 }, P6 e
  203.                     action='store_true'), y* i2 L* v0 v* Z+ o- ^
  204. % h6 P6 V; @6 f* h. G+ I
  205. args = parser.parse_args()" K% j, A0 S9 v7 Z7 h% W& m
  206. ( |6 T3 r! o5 r3 C# C/ m
  207. if args.help:
    8 x* f3 C7 V6 x+ I7 i
  208.     print(help_msg): V6 |# M8 {. M' U. j
  209.     exit()) k5 e7 K0 J2 C( M* s- V, }6 W
  210.   z" H# A! F7 _7 G1 V
  211. char_set = {
    " k4 B6 F1 k9 C4 `/ I2 N( _
  212.   w$ A# @. {0 ?3 D
  213.     'a': 'qwertyuiopasdfghjklzxcvbnm',
    + q2 ^: U/ b& l; I1 W: o( c
  214.     'A': 'QWERTYUIOPASDFGHJKLZXCVBNM',3 o- p  ^: a8 p( U: B
  215.     'c': 'абвгдежзиклмнопрстуфхцчшщъыьэюя',7 P6 s& ?. ]/ m9 u" `6 S+ e: t
  216.     'C': 'АБВГДЕЖЗИКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ',+ Y5 ]4 x* n+ w# H& m
  217.     'e': '☺☻✌♡♥❤⚘❀❃❁✼☀✌♫♪☃❄❅❆☕☂★',) K9 a% o  P& }6 [' A
  218.     'g': 'αβγδεζηθικλμνξοπρστυφχψως',
    : ]  m, q  |2 u7 u6 R" O! Q) z
  219.     'G': 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ',$ ]" Q$ Z- L/ V8 |) U/ v2 r3 }
  220.     'k': 'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン',
    9 U- O$ K7 Z/ t6 @: p
  221.     'm': 'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン1234567890'" h3 I/ Y, C8 m" M/ Y6 V1 z) T
  222.          '1234567890-=*_+|:<>"-=*_+|:<>"-=*_+|:<>"-=*_+|:<>"',* o) s1 }' V5 Z$ ~7 m
  223.     'n': '1234567890',$ g* V; R5 z/ e
  224.     'o': 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890'; e% e# A% W" T/ u/ t" Q- i
  225.          '`-=~!@#$%^&*()_+[]{}|\;\':",./<>?"',8 x% k: D, D6 s4 p' H' `
  226.     'p': '',
    0 D" ?4 n3 D, n! D' x
  227.     'P': '',, A- }7 C' r  ?% c  a' ?
  228.     'r': 'mcclllxxxxvvvvviiiiii',/ r7 q' [9 u5 O% j+ F
  229.     'R': 'MCCLLLXXXXVVVVVIIIIII',
    5 s# X, e& ~: h4 p5 t# u
  230.     's': '-=*_+|:<>"',8 d. D# b6 y8 b, q1 H2 D  `
  231.     'S': '`-=~!@#$%^&*()_+[]{}|\;\':",./<>?"',6 x' r0 @" ^( i% ?
  232.     'u': args.custom_characters}. a/ ~, L! S& U" c4 a

  233. % p4 l# [( {& g9 k8 [" ^# T
  234. colors_str = {
    . U6 I1 k5 e8 t2 T& x: W
  235.     'green': curses.COLOR_GREEN,
    9 t) o; }/ M) U$ T- m3 r! a) E$ s
  236.     'red': curses.COLOR_RED,
    8 x/ d  I  P) @
  237.     'blue': curses.COLOR_BLUE,
      B( F0 E6 _' S+ X5 @
  238.     'white': curses.COLOR_WHITE,
    % F" |7 J( R' P
  239.     'yellow': curses.COLOR_YELLOW,& _1 ]5 K+ ~: U( V
  240.     'cyan': curses.COLOR_CYAN,8 R; U7 G$ t/ c. }8 ^4 f
  241.     'magenta': curses.COLOR_MAGENTA," G$ J9 B, t5 q3 {' t! r7 J" h! @, o
  242.     'black': curses.COLOR_BLACK," \1 L) Y7 _: P7 `+ n+ H
  243.     'default': -1}
      E' M0 W% D  S

  244. " B% q. C8 g  t
  245. start_color = colors_str[args.color]
    6 a+ _1 \( U; F1 Y
  246. start_bg = colors_str[args.bg_color]. H8 F; e: r! d; w9 I& ]& p$ I

  247. $ a2 C3 n# B# q3 `8 d( M
  248. speed = args.speed! v$ z% d# e/ N- D  N
  249. start_delay = (100 - speed) * 10
    3 ]: c$ f$ s( ~9 p
  250. 1 J, l$ q0 N7 b! ~; S
  251. runtime = None. n  p- u! i" {" N$ y4 M* C/ c
  252. : G: `; ^0 d9 I4 \
  253. if args.time:* l9 C6 u2 U3 t* ]
  254.     runtime = args.time0 m2 M+ P1 R& D/ V. z0 Z9 [

  255. ) J. M0 [: S: {  t4 @& x2 _
  256. # "-l" option has been used
    % _$ `( P% W, d: w7 b4 v5 z
  257. if args.character_list:
    0 y8 t* F. n6 b; r0 W. q. k* Z$ R: U* f
  258.     chars = ''% n9 X- x" Y3 x. r; T( ]. }
  259.     for letter in args.character_list:
    2 ~9 W/ b$ Q: l6 O* z8 h
  260.         try:
    2 X( T# @$ A1 @* T) Z% G
  261.             chars += char_set[letter]
    5 z; |& v; ~0 I6 c! T
  262.         except KeyError:6 D% L, g+ O( e- R7 C" |
  263.             print("Letter '%s' does not represent a valid character list."
    / l% [4 _' p- ~5 m& D( z1 O
  264.                   % letter)
    & {, t' G2 f2 U1 Q8 M1 S
  265.             exit(): r2 T- l, G1 P! V: v; i
  266. , J  G/ h% Y3 W
  267. # "-l" not used, but "-u" is set' Q! K5 m, @4 \( \( @
  268. elif args.custom_characters:
    + j! [  G- P" i" q
  269.     chars = args.custom_characters' s! Z' J4 U- Q9 K. f1 F

  270.   O+ {% P5 \! t; V/ h; F) ]
  271. # Neither "-l" nor "-u" has been set, use default characters' S7 v5 h( T( j3 K1 N
  272. else:- T0 u5 x$ q# T% c/ m5 O# i8 \
  273.     chars = char_set['m']
    1 X* g; z8 L, \6 @3 \& e9 o

  274. * g( G9 P4 E1 M! o
  275. if args.no_bold:) @9 Q+ t, U  q! X+ V
  276.     args.all_bold = False
    ! V* `" J& v6 |) m% \

  277. + `$ G% d" j* b: A
  278. chars_len = len(chars) - 1
    # w8 ~3 T% K- p( m  B5 j
  279. 7 s: w; m) M5 [4 ^! l- E

  280. & w8 K+ D+ X7 t( d9 f5 Z2 z
  281. ### Classes/ O* A, b( u8 r/ x8 x2 {; V" x5 d1 c
  282. & g+ \/ v$ e$ p3 c3 j
  283. class Canvas:& V) [. ]; [; d7 u$ k/ N
  284.     """6 h7 A7 k% Z2 f0 [" L6 b
  285.     Represents the whole screen and stores its height and width. Gets& I' _# l! D. v# B
  286.     overwritten whenever the screen resizes. Serves as a container for columns.
    / o, S9 B4 g5 g1 {' m( G, t
  287.     """) D! ?- ]3 O" |2 }  J7 ~. A

  288. $ h! H6 I9 n$ D8 F- L
  289.     def __init__(self, screen):
    ; P) {1 N; x3 e) _' F8 O% R
  290.         screen.clear(): k- a* ?- K/ Y6 x% `
  291.         rows, cols = screen.getmaxyx()* ~0 l" m+ }% g" {8 V1 V- Y) S
  292.         self.col_count = cols. I0 Z3 |. D( a5 A' A' R+ }
  293.         self.row_count = rows
    0 W! k% z* O# _  z- n' r
  294.         self.size_changed = False
    1 _0 B0 a5 u- V. G" w: G4 b: Z
  295.         self.columns = []: J( ~( `7 {6 G2 v9 F+ i
  296.         for col in range(0, cols, 2):' [6 e3 f- A( B
  297.             self.columns.append(Column(col, self.row_count))
    ) M% P0 b# @, ^$ }/ d0 T3 i
  298.         self.nodes = []
    ' N% s' r9 x8 M4 \! l' W9 z  u: f7 K
  299.         self.flashers = set(), X, ^& q, C0 `- V4 P
  300. / D, K  P: p* f9 k: p/ I
  301.         # Draw a background& o6 \! o" Y4 g) f0 A9 r5 D
  302.         for x in range(self.row_count):8 [& i- q, H$ c; f  A
  303.             try:' S  V, e9 g% P* W$ _: q
  304.                 screen.addstr(x, 0, ' ' * self.col_count, curses.color_pair(1))
    1 c1 o# P: N' M( U. {' k
  305.             except curses.error:) K+ V3 g6 I: e: N/ e! R3 x
  306.                 pass- o+ [- @- F7 Z+ E4 B
  307. 0 E8 R' O5 T) c: N* O; y( Q

  308. 4 f9 b) u' S% L5 B
  309. class Status:
    2 `0 b% B# E6 z; S3 u9 g9 I
  310.     """
    ; r8 I5 B' a% r( k3 G
  311.     Displays a status message at top left when a setting is changed., L4 v- `+ Y3 i: C2 W! n
  312.     """) W8 [8 @3 G4 A9 c

  313. % U6 A1 E% Z. r
  314.     def __init__(self, screen):
      S4 N1 }# D8 S+ Z2 Y: C
  315.         curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
    0 d! o$ f3 v7 n% l$ v8 N+ u
  316.         self.screen = screen) U( d* H: K: x/ o( t
  317.         self.countdown = 0
    6 c& R: ^# r2 }+ I( a+ H
  318.         self.last_message = ''. h& I2 P6 H; H$ @  I, J

  319. 9 O6 E6 N. v8 d. t& n0 X4 ^
  320.     def update(self, message, delay):" f+ j+ J0 f% K: Z8 w3 U
  321.         """+ |' O) K8 m% x
  322.         Writes new message to the status area: I$ }' y' O- W" J0 e
  323.         """
    , w6 y5 y. N: ]7 g( ^. J' H
  324.         if not args.status_off:( s" X6 T! n. S& b
  325.             message_str = message.ljust(11)
    + E; B3 I) J4 c
  326.             self.screen.addstr(0, 0, message_str, curses.color_pair(3))- S# i1 r) I, v! R6 Z  n1 T8 N& |3 w
  327.             self.last_message = message_str
    * Y% i! K- ^- \+ J
  328.             # More frames for faster speeds:
    2 q; J' [* J, m' M" l; H" Z# `" Q8 F
  329.             self.countdown = (100 // (delay // 10 + 1)) + 2
    : u3 O. d/ D% C% ]- k% J
  330.   H. B; `8 h5 K7 q$ n
  331.     def refresh(self):* v7 B0 M6 t! ?) O+ d
  332.         """* b; g& S7 f- K# t" i3 y7 t& p
  333.         Used to keep refreshing status message until countdown runs out
    ' ~0 N) L" ?6 z% r
  334.         """
    $ V3 u% g  u* m: Y" A7 P( ?
  335.         message_str = self.last_message
    % m6 H/ ]  V" `
  336.         self.screen.addstr(0, 0, message_str, curses.color_pair(3))
    * ~; j, h6 m& R' i: q

  337. ! R/ @5 J4 c$ Y0 t9 X9 J
  338.     def clear(self):
    1 L) d: a# w6 b4 U: \8 |2 s9 M6 J
  339.         """
    & t5 O+ a9 w$ ~8 a, X9 x
  340.         Erases message with spaces when the countdown runs out( {8 e) a$ |1 e: e
  341.         """
    % ^& \! ^) O  Y0 d* k+ o8 ]
  342.         self.screen.addstr(0, 0, ' ' * 11, curses.color_pair(1))
    ) i, |* M8 x; q2 Q/ s1 m/ _3 ^2 g
  343. ( J7 [/ p( j8 ~( h  |: x# a7 P0 u

  344. ! J5 W8 x) Z8 I
  345. class Column:
    0 _  m! j" f% x. {
  346.     """- s* M4 O1 v8 p! b
  347.     Creates nodes (points that move down the screen) that are then stored in
    # Y* ?. r% P. r4 Y) t- X
  348.     canvas.nodes. Countdown timer determines time to spawn new node.
    . b& q& I7 z" P, ~
  349.     """8 M( |* {; T# A

  350. ; R; F8 h4 b$ ?! ^) ^
  351.     def __init__(self, x_coord, row_count):6 }- r" Z, G! G8 i' w
  352.         self.drawing = None  # None means not yet. Later will be True or False+ }" z+ s+ J7 Y& O
  353.         self.x_coord = x_coord) \! J8 L! t8 \
  354.         self.timer = randint(1, row_count)
    ! a0 {$ c3 a' v( @) p
  355.         self.async_speed = randint(1, 3)
    8 F" i! D* y: D& s
  356.         if args.single_wave:8 V7 T+ j4 t! v+ i! i8 F. D. x
  357.             # Speeds it up a bit' s8 n  \/ D' }8 d3 \
  358.             self.timer = int(0.6 * self.timer)3 s2 R  v  \. b7 n9 d( g
  359. 9 A/ K. Y! |  p
  360.     def spawn_node(self, canvas):
    4 y$ ?+ u6 _( k: T/ R9 A* @7 P" k8 X* [
  361.         """
    % E/ K; M. d: S. i$ @+ B
  362.         Creates nodes: points that move down the screen either writing or' ^, p. m' J$ Z8 m1 q, X. [
  363.         erasing characters as they go down; v$ H/ G; W! H6 W& @& q
  364.         """; y) A. L$ o* f
  365.         if args.single_wave and self.drawing is False:
    0 R, t2 e! ^$ g) q' `5 q3 B; ?, Y
  366.             return- j' k% o4 R4 L( e# B5 S5 d
  367. 7 C  \* z7 w' H8 ]9 h
  368.         self.drawing = not self.drawing
    . ~( e( X5 L4 X3 n8 |. D; d

  369. 1 S4 I, H5 P- F8 S! x7 W  a4 _
  370.         # Multiplier (mult) is for spawning slow-moving asynchronous nodes
    & e' k, v2 G; J0 P9 @# a+ U  }8 Z2 C
  371.         # less frequently in order to maintain their length
    % ^: s0 Q3 t. W& A. S1 |2 Q) ~
  372.         if args.asynchronous:
    6 C# G6 i3 j# P6 r' t
  373.             mult = self.async_speed
    . i7 q. |( g* t3 t2 x& P% N, _, j
  374.         else:- e0 c: i/ Y! B3 b4 |
  375.             mult = 1
    : R4 n) e8 ]8 k7 M3 I% y

  376. : ?5 G2 V1 e4 |) T% g+ N" ]% U0 }
  377.         if self.drawing:
    1 L0 ^( ?' H+ V% A' _# t
  378.             # "max_range" prevents crash with very small terminal height- Q. D" |& o4 ]0 q+ [+ t5 Q# e
  379.             max_range = max((3 * mult), ((canvas.row_count - 3) * mult))% {3 Y, h8 u' R9 ~
  380.             self.timer = randint(3 * mult, max_range)
      _2 J3 `4 K7 E
  381.             if args.single_wave:% _9 k, ^2 _2 j! M7 C
  382.                 # A bit faster for single wave mode
      S) }1 \. l4 E' i& |
  383.                 self.timer = int(0.8 * self.timer); v9 s' \) P" k" P' @& L$ s6 ?
  384.         else:
    * g4 ~3 g& Z" o: U0 Q
  385.             self.timer = randint(1 * mult, canvas.row_count * mult)6 a4 J) _$ e4 T

  386. & h4 g  R8 _7 h0 C" Q8 G. I9 i% x6 _- s
  387.         x = self.x_coord
    ) l4 `* k" j6 ]. I7 {( _) q
  388.         n_type = 'eraser'# z# _$ G2 r& L4 L2 \) B
  389.         async_speed = self.async_speed% \3 g3 h$ Z. ~
  390.         white = False
    / r( R& |$ c+ X9 k
  391.         if self.drawing:: [3 b0 s4 F; d0 r
  392.             n_type = 'writer'4 B; c/ z) m: i- Y1 ^# I( N
  393.             if randint(0, 2) == 0:6 {7 l2 R( N( _- P5 l- G: g
  394.                 white = True$ v# R; [+ m4 K' W

  395. , Z& B1 e# e# |
  396.         canvas.nodes.append(Node(x, n_type, async_speed, white))
    # ^* g' I3 r- ^, t6 x$ Q
  397. 3 Y: ?% n8 J8 _8 u) f# v1 q
  398. - ~+ l0 |, w2 i; x" }, w
  399. class Node:
    0 o+ {$ o5 n6 P- w  l/ C+ `
  400.     """; b, s+ r% k. w6 C
  401.     A point that runs down the screen drawing or erasing characters.$ Y$ x$ Z. i2 F- H
  402.     n_type    -> 'writer' or 'eraser'1 `& h$ t# L- }) q% W
  403.     white     -> Bool. If True, a white char is written before the green one.+ s5 p/ M8 x' ^) o+ E6 K/ b1 s- v+ B
  404.     last_char -> Stores last character, since white characters have to be
    8 @2 T3 Y9 P* }! j
  405.                      overwritten with the same one in green one.
    0 n: z) f2 O& x, k* l7 H
  406.     expired   -> Bool. If True, node is marked for deletion0 g$ E, X' ~9 X% Q( {+ x% ]$ f) f
  407.     """
    ! a) R  P% S1 B
  408. ) I( _" z9 W6 ]! N
  409.     def __init__(self, x_coord, n_type, async_speed, white=False):
    6 i; I+ y( a# }8 x2 J- k
  410.         self.x_coord = x_coord
    , S% k$ o7 H# t- u5 \$ b% p* d
  411.         self.y_coord = 0
    1 J5 N$ a- ^; U( S; J0 T
  412.         self.n_type = n_type2 k3 q4 a  I. u+ A- S( \, B! E& }
  413.         self.white = white
    - y8 `+ U+ F; T# h1 u* f) j2 @4 U
  414.         self.last_char = None
    / H$ C, |2 ^. ^, E( b3 w, P  k
  415.         self.expired = False  E! E% @, ]) O" e/ p$ {& X) @% E  T
  416.         self.async_speed = async_speed
    - {: p9 a& I% l. l
  417. 8 U3 R5 m+ p: Y+ p  ~
  418. * U/ `% c+ M" a" E- ?, U/ G
  419. class KeyHandler:
    # Q* j0 n, o! Y" r2 L9 g( u
  420.     """! D% h/ J, U& B9 e
  421.     Handles keyboard input." |7 l: A8 n- e7 T) c8 X
  422.     """
    ; I$ N5 |" f+ A) ~7 k
  423. ' ], ^, Q1 N6 q  f) T
  424.     def __init__(self, screen, stat):
    2 [7 J8 b" J. h& f* A
  425.         self.screen = screen, K7 P1 U: d, N! o+ m
  426.         self.stat = stat% ~: k. ]! o4 a2 S6 y' ?
  427.         self.screen.nodelay(True)( H4 @- D8 L* ~* a
  428.         self.delay = start_delay
    4 n: w4 g3 |0 o6 O
  429.         self.fg = start_color! C3 ^" o+ K2 ?4 ]
  430.         self.bg = start_bg  E2 E" f. o2 l2 w& y

  431. 4 G; A1 x  ?9 T: Z. l" k5 \! `
  432.     def cycle_bold(self):* I) B# s2 p9 O) x' a! {! w
  433.         """
    . C0 E) m7 I: r) t
  434.         Called on 'b' press. Cycles though Bold options:  P; c8 \- t6 d
  435.         off -> on -> all bold  `1 T4 I% D0 [
  436.         """
    : u, y2 R  C8 u5 r1 h0 l
  437.         if args.all_bold:3 I6 I8 E2 x4 O" o% C/ ]+ E
  438.             args.no_bold = True, S9 `% g+ e$ o, ~/ s
  439.             args.all_bold = False
    3 I9 r3 b( w9 s/ {4 b2 m( H
  440.             self.stat.update('Bold: off', self.delay)) j( ]8 A. f: {4 `7 ]: I
  441.         elif args.no_bold:
    & ]* Y' z4 [- G' _: J9 D9 V9 `
  442.             args.no_bold = False5 w& i+ ?* A/ E7 X. y
  443.             args.all_bold = False
    $ g$ ^% l+ T0 |& n1 U
  444.             self.stat.update('Bold: on', self.delay)
    ) G1 K" J0 d5 Z/ J
  445.         else:
    ) w; C0 P0 |4 d3 U
  446.             args.no_bold = False
    ! I+ @" ~" q6 @, ~: ]7 V
  447.             args.all_bold = True
    4 F, a% z! e, q5 n- f/ _' R. D
  448.             self.stat.update('Bold: all', self.delay)# n. U0 Q6 j1 N/ i3 B

  449. # O2 w& F% _# g( |3 U! U- `
  450.     def get(self):
    3 l4 f+ K4 u' y  [; G( f
  451.         """
    ! U# a5 ]- R% s$ [
  452.         Handles key presses. Returns True if a key was found, False otherwise.
    " _$ Q& h+ t* @
  453.         """
    & {; A( J  B, W& B
  454.         kp = self.screen.getch()
    + e% W3 m0 S7 E+ E' a

  455. 2 s( n# R  [! f% m6 _; b
  456.         if kp == -1:5 e( }: l: B' y5 d% M% y7 m3 p3 w
  457.             return False
    2 R; C9 W) n/ E+ L! X
  458.         elif kp == ord(" ") or kp == ord("q") or kp == 27:  # 27 = ESC
    : \; U$ h# k9 d1 X, o0 q, ]. s
  459.             exit()
      X* A1 P9 J3 [9 W* l! [
  460.         elif kp == ord('a'):8 p, L+ J% L. p9 B! e& Y# V9 p' c
  461.             args.asynchronous = not args.asynchronous/ A2 n" p. S* O. y. }. `* z
  462.             on_off = 'on' if args.asynchronous else 'off'
    1 A" n: @8 S& \! {% k( I
  463.             self.stat.update('Async: %s' % on_off, self.delay)
    $ x6 c1 i4 Y$ o1 k' S
  464.         elif kp == ord('b'):2 B8 g* u$ k' c7 e" y. [* F8 f$ b
  465.             self.cycle_bold()
    % ]- ]( c1 |; ]4 x$ r4 m
  466.         elif kp == ord('f'):( I# S% c; y2 r. m1 ]4 C! ?+ X
  467.             args.flashers = not args.flashers
    8 \4 X; Q: q7 H
  468.             on_off = 'on' if args.flashers else 'off'
    ; F% L% H+ }5 |/ `
  469.             self.stat.update('Flash: %s' % on_off, self.delay)' U4 G: B4 a5 E8 K8 f
  470.         elif kp == ord('o'):/ ~4 v8 N0 z: I# A
  471.             self.toggle_status()
    1 V, z3 v8 X' R$ L4 I/ r
  472. 5 J) n) F  C/ f# _/ @
  473.         # Speed control
    ' {) O' B! J: M7 C, Z
  474.         elif kp == ord('-') or kp == ord('_') or kp == curses.KEY_LEFT:' X& f$ a$ P/ C# G& Z# q. B
  475.             self.delay = min(self.delay + 10, 10990)9 _9 w) K9 z/ w$ R' M- v( u7 k
  476.             self.show_speed()
    # ]0 F7 J$ Y# f4 O) O9 P9 Y% q
  477.         elif kp == ord('=') or kp == ord('+') or kp == curses.KEY_RIGHT:
    " j# Q3 y) H6 ]/ y
  478.             self.delay = max(self.delay - 10, 0)
    0 u) f2 }( C6 |
  479.             self.show_speed()5 b/ k& m( A% t6 H
  480.         elif kp == ord('[') or kp == curses.KEY_DOWN:. \% A& E: _  |8 z3 E) j# f
  481.             self.delay = min(self.delay + 100, 10990)
    $ o" @, B9 q- D7 V/ |
  482.             self.show_speed()
    8 l% v) o8 u. c1 X( h
  483.         elif kp == ord(']') or kp == curses.KEY_UP:
    5 n) `" x6 ~3 _/ R9 A( I
  484.             self.delay = max(self.delay - 100, 0)
    ; G# J: O  i+ G0 y; R  k
  485.             self.show_speed()6 E2 G+ H& |' Z) j* K

  486. ( U  \* ]+ ^0 C) `
  487.         # Foreground color control
    . n+ c/ A+ \  G& ]% u
  488.         elif kp == ord('1'):
    8 `6 `" Z9 e2 }/ o! X4 l  @+ G
  489.             self.set_fg_color('Green')
    ) t: ?; E7 t4 \/ ^% B+ f
  490.         elif kp == ord('2'):% Q: c* F+ ~: A7 v, O
  491.             self.set_fg_color('Red')2 H. z7 q$ s* O# }# X9 J
  492.         elif kp == ord('3'):
    : t+ S4 Y1 W7 n" @; @2 E
  493.             self.set_fg_color('Blue')
    - v" w: T0 j3 B0 o
  494.         elif kp == ord('4'):& T* \6 n# @  m/ s1 D
  495.             self.set_fg_color('White')
    * e) H( J, \# Y/ J2 O/ b
  496.         elif kp == ord('5'):5 o6 q2 {9 _% W7 g5 ~3 {5 f9 ]
  497.             self.set_fg_color('Yellow')
    ) U9 C; h& w' w% O, `' n0 L, L9 \
  498.         elif kp == ord('6'):
    4 `5 H& q, x1 U; p$ h1 e4 p
  499.             self.set_fg_color('Cyan')+ e0 N" w0 T9 u" C8 u( b8 a
  500.         elif kp == ord('7'):9 @3 e- q- u6 F7 s. p4 i0 [
  501.             self.set_fg_color('Magenta'), d2 F4 t$ w7 Z* }/ D2 v
  502.         elif kp == ord('8'):
    1 u# U! e1 e5 c# N
  503.             self.set_fg_color('Black'): m3 ~5 R; O6 H" U: [1 F. |
  504.         elif kp == ord('9'):
    . ?4 v* F: N# b. ^8 }5 w
  505.             self.set_fg_color('default')
    7 k, V+ A3 Z2 P2 `# {% l6 B
  506. " J5 {7 f+ i  l+ L, f
  507.         # Background color control
    9 ?9 K. i/ I, ?+ b4 C2 A/ ^; `) _
  508.         elif kp == ord('!'):
    , P% K; s) I. [0 j
  509.             self.set_bg_color('Green')
    1 `: T0 N7 j* B8 m/ q- g  |
  510.         elif kp == ord('@'):% T- b+ |4 W. T4 Z! j" F5 I( f
  511.             self.set_bg_color('Red')
    / `' P4 j" R  v$ j- y9 U
  512.         elif kp == ord('#'):7 B. k6 c/ Y# p9 ]* G6 _5 j
  513.             self.set_bg_color('Blue')
    ! c, `% z9 u9 Z, H) U- k
  514.         elif kp == ord('$'):
    + j! ], a: {( Y4 A  v
  515.             self.set_bg_color('White')
    ' U: A' o8 I& c' t4 Q4 L1 Z7 l
  516.         elif kp == ord('%'):
    0 g! P- W  G! K# W8 {1 \
  517.             self.set_bg_color('Yellow')
    2 I  T: d- K5 N0 T! Y. m! m. @9 o1 D
  518.         elif kp == ord('^'):
    8 o8 @5 J: [) g6 M! H6 i# X
  519.             self.set_bg_color('Cyan')( c% z& [, W+ z+ ?9 V; Z  @) A1 q
  520.         elif kp == ord('&'):
    - S, ]4 K2 l1 _. f9 y0 n
  521.             self.set_bg_color('Magenta')
    . Z9 d% v, J; h% B( l, a: J
  522.         elif kp == ord('*'):
    " }! f% c9 a/ D/ ~" a2 T8 j0 V+ H
  523.             self.set_bg_color('Black')9 s3 J" }& A: t9 x. d
  524.         elif kp == ord('('):9 A% ?  S5 ?# `1 _$ i
  525.             self.set_bg_color('default')' p/ }8 v. b  `

  526. ! O2 N6 V3 Y9 n, z7 Y2 F% [
  527.         return True& E3 Y2 g5 k2 v" e, D+ u+ V4 }
  528. 5 T" i; \* r7 K7 Y
  529.     def set_fg_color(self, name):
    1 t( `9 ^6 A9 w2 {% I5 q/ B
  530.         """% w+ p. [; g, k4 Y$ @8 T8 E
  531.         Set foreground color
    ' S9 {( e" U: {! @; m7 q
  532.         """
    * k5 Z9 u' _- H3 {
  533.         self.fg = colors_str[name.lower()]
    ! I" X) m4 q, i" E: s2 \/ Z6 Y9 \* I
  534.         curses.init_pair(1, self.fg, self.bg), L' L8 E: b/ j; l  \% {) U5 k
  535.         if name == 'default':
    0 I' S4 I1 |- l+ V
  536.             name = "Def't color"; w( Y6 v7 i- [0 I5 d
  537.         self.stat.update(name, self.delay)# Z. v4 Y( F2 f4 `

  538. $ b! w/ p& k( ^
  539.     def set_bg_color(self, name):
    " d; i4 L8 K" v7 u' p0 e5 x
  540.         """
    ; [% r( `, [  g* L0 e8 J
  541.         Set background color
    - r  b6 p* w# o2 C% k8 N5 E& x" y
  542.         """
    # G% A( g; O" R
  543.         self.bg = colors_str[name.lower()]* ]! `+ q4 A! L- y. t/ `
  544.         curses.init_pair(1, self.fg, self.bg)) r9 i* M) u$ Q
  545.         curses.init_pair(2, curses.COLOR_WHITE, self.bg)( y3 Y$ @* E( E- ~( S9 a
  546.         self.stat.update('BG: %s' % name, self.delay)# e2 d9 V. t0 f
  547.   T4 @# E9 \( u% Z
  548.     def show_speed(self):8 H2 Y  G$ F) |/ |9 {/ H  h
  549.         """
    " e" g- H: ]# P
  550.         Display current speed (-999 to 100) when it is changed by keypress
    2 q1 s+ B' U% u% x" E" U6 t
  551.         """
    ) I% X0 v' I5 A9 Z$ X* D$ M
  552.         self.stat.update('Speed: %d' % (100 - self.delay // 10), self.delay)( g4 R0 r! q) V
  553. " T( S9 A# k% D/ P2 L- d, c
  554.     def toggle_status(self):
    ( w$ s% A4 K# u% t5 N' H0 L
  555.         """( g# s7 ^+ H) [2 _( C) ~
  556.         On 'o' keypress, turn status display on or off" @6 ]& t$ x7 y$ c/ I, O+ j0 P/ O, W
  557.         """+ h$ A* `5 N' }, C. O0 X9 H
  558.         args.status_off = not args.status_off
    : n2 K1 n  P) V1 T4 @  \2 v
  559.         on_off = 'off' if args.status_off else 'on'1 n& l- O7 i5 r( J, V8 ]0 x9 g
  560.         self.stat.update('Status: %s' % on_off, self.delay)
    6 H! k# t- [8 A1 f6 x
  561. 9 ^( \: h! z" H8 ?1 H- |

  562. * S; B/ _" _" }8 j- }& P
  563. class Writer:) H4 E/ T9 Z- h6 K+ |8 J, w
  564.     """
    % R, N& L% U! e9 s
  565.     Initializes character writing options and contains methods for writing and
    6 y4 l. g# q  ?) g
  566.     erasing characters from the screen.0 T0 `) r) d4 x. L; O$ ~9 S
  567.     """$ o. Y$ ]# l+ |& {
  568. . u( H/ y; ~, l) H* m" E
  569.     def __init__(self, screen):: l. k& J5 g- M4 H2 M7 E: x
  570.         self.screen = screen! a/ y- Y5 _! ~- {* l
  571.         self.screen.scrollok(0)
    0 N4 d) g! k7 v6 q  L" _' N/ p
  572.         curses.curs_set(0)% C. Y& g2 ]- _# n  p
  573.         curses.use_default_colors(): K, m5 K' A" B9 H1 g
  574.         curses.init_pair(1, start_color, start_bg)
    ' h, o3 o2 j2 r
  575.         curses.init_pair(2, curses.COLOR_WHITE, start_bg)
    , F. c% E8 t6 M% O
  576.         curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)$ ^/ B( ^" g& N6 r$ }) C) p( ]
  577.         self.white = curses.color_pair(2)$ C+ \% v# \" ]& @5 |! F
  578. $ T+ i5 j8 M5 K- T3 Z
  579.     @staticmethod
    " z7 L( O$ A9 {* |" w
  580.     def get_char():
    - ]9 U( E" l( Y  A* c5 c% N
  581.         """
    - B9 N# u3 z4 L5 \
  582.         Returns a random character from the active character set
    & O/ C( g% \4 D5 a
  583.         """
    1 L5 [' d: ^$ J% u* k
  584.         return chars[randint(0, chars_len)]
    % R7 }0 a+ I- {. q9 B. h% h

  585. . V$ D6 Y* y& U. u" a
  586.     @staticmethod
    0 Z# F1 K' a: S- F+ O6 M
  587.     def get_attr(node, above=False):
    3 x" C0 l9 k: F( A4 P  [$ }
  588.         """1 `2 r. J' S7 d! t% Q  X
  589.         Returns either A_BOLD attribute or A_NORMAL based on Bold setting0 f8 O) C3 Q( N* y+ G
  590.         "above=True" means it an extra green character used to overwrite the% S- W$ A( h* A
  591.         while head character.
    , ^; O0 L3 M2 [, e
  592.         """, G- u6 x; `# x
  593.         if args.no_bold:
    7 r$ m$ b- P) N* W7 Q1 @
  594.             return curses.A_NORMAL; j8 H3 k, V  r) I  q3 e
  595.         elif args.all_bold:2 I( f( \/ O2 i; b/ w
  596.             return curses.A_BOLD
    0 _# }2 ~8 f! q: w6 z1 k
  597.         else:" E5 R6 D& o4 E/ }; o! `2 y: {1 g
  598.             if node.white and not above:: C& X' x# h3 c
  599.                 return curses.A_BOLD
    3 ]  ^7 Y  b8 n, n. D! v
  600.             else:
    + ~5 U0 Q  ?, u. x
  601.                 return choice([curses.A_BOLD, curses.A_NORMAL])$ h9 J2 i% t. ^- y' Z& J

  602. ( e( i1 f4 e5 M' z9 Y+ ?8 B
  603.     def draw(self, node):$ E6 f4 k# e4 j
  604.         """
    . P$ ^1 E. a3 ^4 a4 x$ H
  605.         Draws characters, included spaces to overwrite/erase characters.
    1 g) n% g9 N5 b0 ~
  606.         """3 |9 E/ H4 P" `! v1 c  X8 r3 H
  607.         y = node.y_coord, D/ }3 K; d4 `7 p3 `5 `
  608.         x = node.x_coord
    9 g5 p4 d: m1 ~
  609.         character = ' '
    0 r; a. `  N( ]" o! o+ \( S+ Q
  610.         attr = self.get_attr(node)% t! |1 M: q6 k' I& C1 L) t$ k4 n
  611.         color = curses.color_pair(1)
    ( Z- q4 g& U5 b, X$ k9 c* C' _! E
  612.         if node.n_type == 'writer':
    0 P  [* a" c4 s4 z7 x/ \
  613.             if not node.white and node.last_char:! S: z* I9 j2 N$ G# n+ V
  614.                 # Special green character for overwriting last white one
    5 S  Z, g! F4 f$ Z2 P
  615.                 # at bottom of column that was not being overwritten.: }2 e/ D, ~: H( j  ~) V: B
  616.                 character = node.last_char
    , v7 ]3 c% M( S, F; j7 G
  617.             else:
    % q; I. X2 b( `2 a/ [' a  Y
  618.                 character = self.get_char()
    / {3 q5 F' L: Q- |
  619.             if node.white:
    # T4 L# L. t: _. c0 ^( L
  620.                 color = curses.color_pair(2)3 `; f7 f  d4 ]" H5 z0 M1 X
  621. 6 D0 L$ o+ y2 _! Q4 s' Y7 T& e
  622.         try:. R  W7 H" Y4 j9 g8 @: z9 j7 U
  623.             # Draw the character
    # m7 v, S  n0 q4 R% [7 G, Q8 N
  624.             self.screen.addstr(y, x, character, color | attr)
    0 a. \( w2 M5 {% a* s3 o
  625.             if node.white:
    % p$ u- b+ T' F4 k7 ?8 |% S' i7 v1 H
  626.                 if node.last_char:
    # z8 L1 F0 C8 ^1 p: r/ D6 f
  627.                     # If it's a white node, also write a green character above  m2 B/ z  t' d8 p2 ^0 o* L! z- u
  628.                     # to overwrite last white character
    1 Z; n% f4 `  B- ?2 y: q
  629.                     attr = self.get_attr(node, above=True)6 W% s7 J; }2 k
  630.                     self.screen.addstr(y - 1, x, node.last_char,
    8 U3 J4 Z; i) ~2 W
  631.                                        curses.color_pair(1) | attr)
    % C* l8 e9 @' `
  632.                 node.last_char = character
    / b$ C) P1 a3 y6 p# k6 S
  633.         except curses.error:
    . J( S# g: ~  K" T  i6 |/ c
  634.             # Override scrolling error if characters pushed off the screen.% s. _4 V2 g+ \, r2 e* `5 \
  635.             pass
    . X+ I1 G$ v8 A1 o) K
  636. , X+ Y0 v0 d! z; n  X/ W
  637.     def draw_flasher(self, flasher):
    , H: d6 N6 d3 y
  638.         """
    1 X6 }' H, ?. _* r. Q# A
  639.         Draws characters, included spaces to overwrite/erase characters.
    6 j( _0 n0 s- S# a
  640.         """% \  F; o% m8 ?( y
  641.         color = curses.color_pair(1)
    : e8 A# @& ~' ?4 f, I
  642.         attr = choice([curses.A_BOLD, curses.A_NORMAL])
    ; Q; I' q) x! k0 u
  643.         y = flasher[0]
    2 h4 A3 G9 K' {) ^- S" R/ {2 O) C4 a5 c
  644.         x = flasher[1]
    + u/ R# \: T8 Q3 Q' R3 C. N
  645.         try:" z" p# w, r$ a7 v5 u) u7 x
  646.             self.screen.addstr(y, x, self.get_char(), color | attr)
    $ k! y. a! P  ^
  647.         except curses.error:
    ) i- F' }! |" G2 X: ^
  648.             pass1 V7 m/ ]3 i9 c( T4 ~
  649. 8 @3 ^0 E1 x. u% `, }1 ?& r
  650. 9 `  }( S& w3 b( W& }& H
  651. ### Main loop* T+ g. k) w7 U  E, F+ S9 t. i
  652. % \3 J& z' j/ T5 n! t
  653. def _main(screen):
    9 Z+ W; d, a! E( ^4 _9 S
  654.     writer = Writer(screen)9 ]- O% t" B% S/ c9 j# X: h8 q
  655.     stat = Status(screen)
    / i0 r6 \% y: ?( L) T! P7 a2 G
  656.     key = KeyHandler(screen, stat)
    - D( o! b' F$ W) f$ k
  657.     # Prevent single_wave mode from shutting down too early:
    6 h# l6 W1 a$ n6 H% ~8 f) L
  658.     if args.single_wave:
    , L  ?) M" o, J- T7 Z" r
  659.         wave_delay = 108 @6 b( V8 {9 O1 j. @# X" B
  660.     else:
    - V. s7 U; H7 f
  661.         wave_delay = 0
    0 q9 W% J2 z0 M4 D

  662. 8 h; H) L8 I  _6 {* d# L; m' s
  663.     starttime = time.time()3 k) p$ y% f% n- I& K* m" B2 X

  664. 7 M( |& K' B. u! ], S4 I9 ?
  665.     # Keep restarting however many times the screen resizes) p. N! f- {' P$ o7 ^
  666.     while True:4 d+ q% S( x. Q8 B2 y3 w# \
  667.         canvas = Canvas(screen)) Z2 l" R2 a# v) {2 ~
  668.         # Set a rhythm for asynchronous movement
    + T" w$ v* E' ^* i/ Z! ^% j
  669.         async_clock = 5
    ( z% `/ M& b+ o8 l
  670.         # Loop to draw the green rain
    ( H" ^2 |! ]: I! O" l9 Q
  671.         while not canvas.size_changed:
      R2 Z# |3 _  C! @. ]' L
  672.             if runtime and time.time() - starttime > runtime:
    % ?: Q: r4 x6 Q  P0 _6 a5 X7 O
  673.                 exit()$ |/ {- `+ k- T4 _4 j3 Z
  674.             # Catch keypress
    - r; B% [3 I; Z: v: J* b( A
  675.             if key.get():9 \% }2 n! p! k) v" N
  676.                 continue7 _( p$ ?& J% \1 K* ]7 |
  677.             # Spawn new nodes* R( O' J5 f4 W0 W( s
  678.             for col in canvas.columns:
    5 }  g7 [3 Y" \; S* h3 n
  679.                 if col.timer == 0:
      p  H) _6 i& Y6 y  P
  680.                     col.spawn_node(canvas)+ X" x3 h( S+ m$ M9 j- @
  681.                 col.timer -= 1
    0 `& ~7 ^6 h: x
  682. 7 R# u5 E3 g8 }0 o$ \
  683.             for node in canvas.nodes:( z# [/ G/ K8 f! G6 c

  684. 2 d% W4 \0 [, A' Z/ D  J
  685.                 if args.flashers:+ |8 K; L) q& Q; K
  686.                     if node.n_type == 'writer' and not randint(0, 9):6 \) J; n) l5 z3 ?$ U9 C
  687.                         canvas.flashers.add((node.y_coord, node.x_coord))
    6 A) `5 F8 N+ H/ Q6 k* q
  688.                     elif node.n_type == 'eraser':2 o9 o3 ]5 [/ Y$ q) j
  689.                         try:
    ! i# n! r2 F- o2 P; B: c2 J9 p1 e4 b
  690.                             canvas.flashers.remove((node.y_coord, node.x_coord)): Q5 z" f8 ~  J) W5 f6 k! o
  691.                         except KeyError:, Z8 J3 j- p' q, }+ s
  692.                             pass  U6 S1 _- [- W1 |6 e

  693. 5 x9 Z1 L- ^3 m7 y1 `( l* }
  694.                 if args.asynchronous:
    ) `2 C% e0 J! A4 k1 [) J) k. K' j
  695.                     if async_clock % node.async_speed == 0:
    4 ?) k4 ~& j9 R* d
  696.                         writer.draw(node): K7 {) h4 n$ @2 R7 T  |3 @! G
  697.                         node.y_coord += 18 w6 \% A; Q! r# p" q: t$ B
  698.                 else:% f  h. P, r( f0 A
  699.                     writer.draw(node), s! E1 H- w8 Y# R
  700.                     node.y_coord += 1
    : W$ s- Z8 X$ V+ {
  701. 6 p, O* r/ R+ U! A' z
  702.                 # Mark old nodes for deletion
    " L' g6 |3 Y  D3 Z& [% M
  703.                 if node.y_coord >= canvas.row_count:) A5 O# F; b! C5 k
  704.                     if node.white:7 l% k$ o: K9 {; u4 q
  705.                         # Stop white nodes from staying 'stuck' on last row.
    , G  W* d2 I/ P* t* u: |3 n0 L
  706.                         # Creates a special green node with a last_char; d: \: ?0 T& b# j8 g* }2 k7 l
  707.                         # attribute to overwrite last white node.% _) R! X- T4 W* e# H
  708.                         node.white = False
    3 X, d7 W5 M# x- D9 X
  709.                         node.y_coord -= 1+ r# h0 t% ~7 [& E% G  D; i" }2 J
  710.                     else:, Z+ t2 [7 L# X# S  ]
  711.                         node.expired = True( O% e- X$ V2 z5 ~; i/ L7 X& v
  712. / ?4 A; \+ D8 h6 l% }
  713.             if args.flashers and (not async_clock % 3):
      s9 Q; c! [# s% D6 S, t4 w# K
  714.                 for f in canvas.flashers:
      v6 _( j- i9 [! N0 P# G2 ^& |) p& Q8 p
  715.                     writer.draw_flasher(f)) G( H8 B2 e2 U
  716. & D7 d2 g+ X- l  b! K0 G& J8 e' t' I
  717.             # Rewrite nodes list without expired nodes5 I( n% l0 K; I9 S
  718.             canvas.nodes = [node for node in canvas.nodes if not node.expired]8 r6 B. r+ N9 r4 d8 `

  719. - _, y* h8 d" o9 w0 n* ?/ r7 K
  720.             if args.single_wave:
    0 s3 M8 B( Q9 J& M
  721.                 if len(canvas.nodes) == 0 and wave_delay < 0:2 e5 y' J9 f- ?6 _: \7 a$ a5 A9 s
  722.                     exit()! d% u4 M3 z6 ]- X/ E% X
  723.                 wave_delay -= 1
    2 Z3 L8 i& R" r, ^( w
  724. : G9 S# y8 s7 t: b- [( y
  725.             # End of loop, refresh screen$ I  n( S$ \8 V/ y/ ~
  726.             if stat.countdown > 0:! a( |; Z7 u. H0 ]
  727.                 if stat.countdown == 1:& b1 c7 b1 ?) D- ?) |% y* e
  728.                     stat.clear()
    9 H- K0 P0 Z+ g# P1 J
  729.                 else:
    ! I1 ~, ?& F$ w' K( A, v, V6 v5 r- d* l. h
  730.                     stat.refresh()
    - [9 Y$ q, w6 m0 D4 u
  731.                 stat.countdown -= 1
    ) `" O( k' g) ^: W
  732.             screen.refresh()
      r; T7 i" P  ~5 V. m. f* ]% ]
  733. : i/ q. X/ U& u9 U8 r. E! v$ j/ ^+ k
  734.             # Check for screen resize
    8 U" t* G4 x- }+ a, r" |. w8 q
  735.             if screen.getmaxyx() != (canvas.row_count, canvas.col_count):7 k7 n. _! [- O* X
  736.                 canvas.size_changed = True& b! r) L( G+ Q- v! e. W' R

  737. + W  C- ^4 ~3 v: N3 u9 {6 e% F
  738.             # Add delay before next loop
    . c- y  q7 d5 F: N; j7 n
  739.             curses.napms(key.delay)
    ( c2 o! V. \' ~/ k, ?. {0 e% m

  740. 7 y/ H1 i! j1 e/ y/ V" U' F
  741.             # update async clock8 T5 J  H+ E2 o
  742.             if async_clock:4 P; Q2 A6 l$ m
  743.                 async_clock -= 10 c- T" r5 G4 H3 t) ~5 y
  744.             else:
    + b: f* V0 a6 Y1 M. M2 s
  745.                 async_clock = 5; E% ?& A9 p/ i) A

  746. + a* \4 q3 \' s4 \  Y# J* k% y
  747. 7 x0 l! [( f! F- I, A4 u% Q
  748. def main():
    % N8 M/ W% M2 f
  749.     # Wrapper to allow CTRL-C to exit smoothly:
    . M/ k% r  Y0 X8 \0 U  F
  750.     try:
    ) `. e. H5 v: l
  751.         curses.wrapper(_main)( G! b* n: ]' {1 e
  752.     except KeyboardInterrupt:! c/ [" C+ A, t/ e6 i
  753.         pass4 S4 Q6 Q/ ?" N

  754. 4 @1 c) N: E- K% W5 D+ S+ ~9 M

  755. 2 J9 Y. D+ f! H4 o0 j" d
  756. if __name__ == '__main__':2 _! M/ }, A4 a; k0 a- X, c. i
  757.     main()6 A8 S# L3 E* `1 |+ Q
复制代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|星空社区 |网站地图

GMT+8, 2024-4-28 10:48 , Processed in 0.061714 second(s), 32 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表