这是一个程序,它显示一个简单的动画,向用户显示程序正在等待输入,或正在做某事,并且它没有崩溃:
require "curses"
include Curses
chars = [" ","* ","** ","***","***","** ","* "," "]
four = Window.new(3,20,10,30)
four.box('|', '-')
four.setpos 1, 1
four.addstr "Hello"
while ( true )
four.setpos 1, 6
four.addstr chars[0]
four.refresh
sleep 0.1
chars.push chars.shift
end
在while循环中,光标每回合一圈就重新定位到第1行第6列。这样就可以用空格覆盖星星,这一切都很完美。
但是,请尝试将“Hello”字符串更改为“Hello Everyone”
如您所见,星形动画现在出现在此字符串的中间。动画还没有被“分流”。有没有办法自动将动画附加到字符串的末尾?
或者我需要以编程方式定位它吗?找到hello字符串的长度并向其添加1,并使用它来定位col坐标?
答案 0 :(得分:1)
Ruby Curses module未提供getyx
。所以你应该自己计算一下这个位置。
另一种选择是在内部循环中编写"Hello"
或"Hello Everyone"
后跟chars[0]
。
require "curses"
include Curses
chars = [" ","* ","** ","***","***","** ","* "," "]
four = Window.new(3,20,10,30)
four.box('|', '-')
loop do
four.setpos 1, 1
four.addstr 'Hello'
four.addstr chars[0]
four.refresh
sleep 0.1
chars.push chars.shift
end
参考:以下是使用getyx
的Python版本。
import curses
import itertools
import time
chars = itertools.cycle([" ", "* ", "** ", "***", "***", "** ", "* ", " "])
curses.initscr()
four = curses.newwin(3, 20, 10, 30)
four.box()
four.addstr(1, 1, 'Hello Everyone')
y, x = four.getyx()
while True:
four.addstr(1, x, next(chars))
four.refresh()
time.sleep(0.1)