我想做的是用 Python 制作一个简单的圆周率内存游戏。我需要的是一种无需在每个字符后按“输入”即可从用户那里获取输入的方法。听起来我需要像 getch 这样的东西,但我无法让它工作。我从这里得到了一个类似 getch 的函数:https://gist.github.com/chao787/2652257#file-getch-py .我真的不明白里面的任何东西。当我执行“x = getch.getch()
”时,它显示“AttributeError:‘_Getch’对象没有属性‘getch’
”。看起来 msvcrt 可以为 Windows 做到这一点,但我有一台 Mac。看起来 curses 是一个有 getch 的东西,但它说我需要先执行 initscr,但随后我收到错误“File”/Library/Frameworks/Python.framework/Versions/3.4/lib/python3 .4/curses/__init__.py”,第 30 行,在 initscr 中
fd=_sys.__stdout__.fileno())
_curses.error: setupterm: 找不到终端
"。
这是我的文件,只使用输入,你每次都必须按回车键(我实际上输入了 1000 位数字,而不是省略号)。
pi = '3.1415926535...'
def main():
print('Welcome to PiGame!')
pigame()
while True:
yn = input('Play again? y/n ')
if yn == 'y':
pigame()
else: return
def pigame():
n=0
print('Go!')
while n<=1000:
x = input()
if x == pi[n]:
n += 1
else:
print('I\'m sorry. The next digit was '+pi[n]+'.')
print('You got to '+str(n)+' digits!')
return
print('You got to 1000! Hooray!')
最佳答案
您可以使用 termios
、sys
和 tty
包定义您自己的 getch
版本:
def getch():
import termios
import sys, tty
def _getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
return _getch()
关于Python输入单个字符不用回车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27750536/