Python 使用 space 键从输入继续
Python continue from input with the space key
我正在制作一个打字速度测试游戏,并试图让它在用户输入 python input() 时,可以由他们按 space 而不是提交不仅仅是在 Windows 上输入。
我的代码类似于以下内容:
score = 0
start_time = int(time.time())
characters = 0
words = 0
current_word = random.choice(WORDS)
next_word = random.choice(WORDS)
while (int(time.time()) - start_time) <= TIME_LIMIT:
os.system('cls')
print(f"Your word is {current_word}")
print(f"The next word will be {next_word}")
print(f"Your current score is {score}")
attempt = input("> ")
if attempt.lower() == current_word.lower():
score = score + 1
words = words + 1
characters = characters + len(current_word)
current_word = next_word
next_word = random.choice(WORDS)
有什么方法可以让它工作,还是最好创建我自己的输入函数?
通过创建我自己的输入函数解决了这个问题,如下所示:
def custom_input(prefix=""):
"""Custom string input that submits with space rather than enter"""
concatenated_string = ""
sys.stdout.write(prefix)
sys.stdout.flush()
while True:
key = ord(getch())
# If the key is enter or space
if key == 32 or key == 13:
break
concatenated_string = concatenated_string + chr(key)
# Print the characters as they're entered
sys.stdout.write(chr(key))
sys.stdout.flush()
return concatenated_string
以下代码根据@gandi给出的答案How to code autocompletion in python?修改而来
它可以实时获取用户的输入。 Backspace 将光标向后移动一个字符。
一些其他好的参考资料
Python read a single character from the user
import termios, os, sys
def flush_to_stdout(c):
if c == b'\x7f':
sys.stdout.write("\b \b")
else:
sys.stdout.write(c.decode("utf-8"))
sys.stdout.flush()
def getkey():
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
new[6][termios.VMIN] = 1
new[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, new)
c = None
try:
c = os.read(fd, 1)
flush_to_stdout(c)
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, old)
if c == b'\x7f': # Backspace/delete is hit
return "delete"
return c.decode("utf-8")
def get_word():
s = ""
while True:
a = getkey()
# if ENTER or SPACE is hit
if a == " " or a == "\n":
return s
elif a == "delete":
s = s[:-1]
else:
s += a
if __name__ == "__main__":
while True:
print(get_word())
我正在制作一个打字速度测试游戏,并试图让它在用户输入 python input() 时,可以由他们按 space 而不是提交不仅仅是在 Windows 上输入。 我的代码类似于以下内容:
score = 0
start_time = int(time.time())
characters = 0
words = 0
current_word = random.choice(WORDS)
next_word = random.choice(WORDS)
while (int(time.time()) - start_time) <= TIME_LIMIT:
os.system('cls')
print(f"Your word is {current_word}")
print(f"The next word will be {next_word}")
print(f"Your current score is {score}")
attempt = input("> ")
if attempt.lower() == current_word.lower():
score = score + 1
words = words + 1
characters = characters + len(current_word)
current_word = next_word
next_word = random.choice(WORDS)
有什么方法可以让它工作,还是最好创建我自己的输入函数?
通过创建我自己的输入函数解决了这个问题,如下所示:
def custom_input(prefix=""):
"""Custom string input that submits with space rather than enter"""
concatenated_string = ""
sys.stdout.write(prefix)
sys.stdout.flush()
while True:
key = ord(getch())
# If the key is enter or space
if key == 32 or key == 13:
break
concatenated_string = concatenated_string + chr(key)
# Print the characters as they're entered
sys.stdout.write(chr(key))
sys.stdout.flush()
return concatenated_string
以下代码根据@gandi给出的答案How to code autocompletion in python?修改而来
它可以实时获取用户的输入。 Backspace 将光标向后移动一个字符。
一些其他好的参考资料
Python read a single character from the user
import termios, os, sys
def flush_to_stdout(c):
if c == b'\x7f':
sys.stdout.write("\b \b")
else:
sys.stdout.write(c.decode("utf-8"))
sys.stdout.flush()
def getkey():
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
new[6][termios.VMIN] = 1
new[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, new)
c = None
try:
c = os.read(fd, 1)
flush_to_stdout(c)
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, old)
if c == b'\x7f': # Backspace/delete is hit
return "delete"
return c.decode("utf-8")
def get_word():
s = ""
while True:
a = getkey()
# if ENTER or SPACE is hit
if a == " " or a == "\n":
return s
elif a == "delete":
s = s[:-1]
else:
s += a
if __name__ == "__main__":
while True:
print(get_word())