python - 我可以在没有 getch() 函数的情况下在 ncurses 屏幕上显示字符串吗?

标签 python ncurses

目前,我只知道使用 ncurses 库显示字符串的一种方法,如下所示:

import curses

stdscr = curses.initscr()
stdscr.addch(0,0,'x')
stdscr.getch()

但是当我想要制作一个字符串的下降函数时,我遇到了一个问题。

import curses
import time

stdscr = curses.initscr()
y=1
def fall():
    global y
    stdscr.addstr(y,0,'x')
    stdscr.move(y-1,0)
    stdscr.clrtoeol()
    y += 1 
    stdscr.getch()

while True:
    time.sleep(0.2)
    fall()

如果我删除此 getch() 函数,我将看不到 ncurses 屏幕。但如果我把它放进去。我必须触摸键盘上的某个键,然后绳子可能会掉下来。

有没有办法让绳子自动落下而不用敲击键盘或鼠标?

最佳答案

在您想要在屏幕上反射(reflect)更改的位置刷新。 我不是纠正而是修改my draw square code在之前的答案中,在我自己使用curses库的代码下面(添加了注释,以便对新人有帮助):

from curses import *
import random, time 
def main(stdscr):
  start_color() # call after initscr(), to use color, not needed with wrapper 
  stdscr.clear() # clear above line. 
  stdscr.addstr(1, 3, "Fig: RAINING", A_UNDERLINE|A_BOLD)
  # init some color pairs:    
  init_pair(10, COLOR_WHITE, COLOR_WHITE) # BG color
  init_pair(1, COLOR_RED, COLOR_WHITE)
  init_pair(2, COLOR_BLUE, COLOR_WHITE)
  init_pair(3, COLOR_YELLOW, COLOR_WHITE)
  init_pair(4, COLOR_MAGENTA, COLOR_WHITE)
  init_pair(5, COLOR_CYAN, COLOR_WHITE)
  # First draw a white square as 'background'
  bg  = ' '  # background is blank 
  for x in range(3, 3 + 75): # horizontal c: x-axis
    for y in range(4, 4 + 20): # vertical r: y-axis
      stdscr.addstr(y, x, bg, color_pair(10))
  stdscr.refresh()  # refresh screen to reflect 
  stdscr.addstr(28, 0, 'Press Key to exit: ')
  # Raining   
  drop = '#' # drop is # 
  while True: # runs infinitely 
    xl = random.sample(range(3, 3+75), 25) # generate 25 random x-positions
    for y in range(5, 4 + 20): # vertical 
      for x in xl:
        stdscr.addstr(y-1, x, bg, color_pair(10)) #clear drops @previous row
        stdscr.addstr(y, x, drop, color_pair(random.randint(1, 5)))
      stdscr.refresh() # refresh each time,  # ^^ add drops at next row
      time.sleep(0.5)  #sleep for moving.. 
    for x in xl: # clear last row, make blank  
      stdscr.addstr(23, x, ' ', color_pair(10))
  stdscr.getkey() # it doesn't work in this code
wrapper(main) #Initialize curses and call another callable object, func,

一次迭代的快照排序:

rain

两次迭代:http://s1.postimg.org/ehnvucp1p/rain.gif

关于python - 我可以在没有 getch() 函数的情况下在 ncurses 屏幕上显示字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21678036/

相关文章:

c++ - ncurses 不能与 -lncurses 一起使用

python - 如何正确移动焊盘?

python - 从批处理文件运行交互式 Python 脚本

python - Pymongo 在 27017 一直拒绝连接

python - 增加辅助 y 轴和 x 轴之间的间距?

c - Ncurses 无输出

python - 将列表中的字符串插入数据框公式以在 Pandas 中循环计算

python - Python 中的 Hangman - 辅音猜测编码

c++ - 诅咒填充 block

select - ncurses和stdin阻止