【发布时间】:2022-01-02 19:58:22
【问题描述】:
这里的目的是在按下转义键后退出脚本,而不必先猜测字母。我认为问题在于 input() 没有将“esc”检测为按键。所以此刻我要猜一个字母,按'enter',然后按'esc'键退出脚本。
def main():
import random
import keyboard
import sys
# Main program code....
# Keep asking the player until all letters are guessed
while display != wordChosen:
guess = input(str("Please enter a guess for the {} ".format(len(display)) + "letter word: "))[0]
guess = guess.lower()
#Add the players guess to the list of used letters
used.extend(guess)
print ("Attempts: ")
print (attempts)
while True:
if keyboard.read_key() == 'esc':
print("Exiting...")
sys.exit(0) # this exits your program with exit code 0
# Search through the letters in answer
for i in range(len(wordChosen)):
if wordChosen[i] == guess:
display = display[0:i] + guess + display[i+1:]
print("Used letters: ")
print(used)
# Search through the letters in answer
for i in range(len(wordChosen)):
if wordChosen[i] == guess:
display = display[0:i] + guess + display[i+1:]
print("Used letters: ")
print(used)
# Print the string with guessed letters (with spaces in between))
print(" ".join(display))
# more code....
这是下面的终端输出,我认为问题是让“.guess”的输入()来确认“esc”的键盘按下,但我不知道该怎么做?如您所见,'^[' 被拾取但不会立即退出脚本,除非我按'enter'。抱歉,不知道如何从终端正确粘贴文本。
Please enter a guess for the 5 letter word: ^[
Attempts:
0
Exiting...
^[%
【问题讨论】: