隐藏非标准 python 用户输入

Hide non-standard python user input

我正在创建一个需要用户按键的主机游戏。

仅仅因为用户按下了按钮,我就无法隐藏随后散布在屏幕上的字母。

它不适用于 getpass 这样的模块,我已经尝试了各种 ANSI 代码来尝试隐藏文本。背景也充满了文本字符和符号,这样一来,一个完整的 ANSI 字符就消失了。我也不想每一帧都调用 os.system("clear"),因为即使每秒调用一次,终端也会出错。

我想知道的是,是否有一种方法可以在控制台上不显示按键的情况下捕获按键

这是我正在使用的开发板class,里面的draw()方法是我如何将它绘制到终端的:

class board:
  def __init__(self,length):
    import random
    self.random=random
    self.characters=[" ","░","▒","▓","█"]
    self.length=length
    self.dithering=False
    self.board=[[self.random.choice(self.characters) for y in range(self.length)] for x in range(self.length)]
  def draw(self,colour=None):
    if colour==None:
      colour=RGB(0,1,0)
    for x in range(len(self.board)):
      for y in range(len(self.board)):
        if self.board[y][x]==None:
          continue
        f=1
        if self.dithering==True:
          f=self.random.random()+0.5 # faintness
        print(f"\u001b[{y};{x*2+1}H\x1b[38;2;{int(colour.r*f)};{int(colour.g*f)};{int(colour.b*f)}m{str(self.board[y][x])*2}",end="")
    print("\x1b[0m")
  def redecorate(self,characters=None):
    if characters==None:
      characters=self.characters
    self.board=[[self.random.choice(characters) for y in range(self.length)] for x in range(self.length)]
  def empty(self):
    self.board=[[None for y in range(self.length)] for x in range(self.length)]

class RGB:
  def __init__(self,r,g,b):
    self.r=r*255
    self.g=g*255
    self.b=b*255

要捕获按键而不显示它们,您需要 getch 函数。在 Windows 你可以使用 msvcrt 模块来捕获它,而在 Unix-like Linux平台需要自己实现,虽然很简单

这是 Windows 的代码:

from msvcrt import getch

对于Linux类Unix平台:

import sys
import termios
import tty
def getch() -> str:
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

NOTE: some keys are more than one char long (like arrow keys which are 3 char long) so you will need to run getch few times to fully capture it.