Python 全程序打字效果
我正在用Python 3制作一个文本冒险游戏。有没有办法在打印的任何文本中添加打字效果,而不必在每行后面重复命令?假设“打字效果”意味着消息应该一次缓慢显示一个字符,您可以定义一个函数,该函数迭代给定的消息并一次打印一个字符,在两者之间使用Python 全程序打字效果,python,Python,我正在用Python 3制作一个文本冒险游戏。有没有办法在打印的任何文本中添加打字效果,而不必在每行后面重复命令?假设“打字效果”意味着消息应该一次缓慢显示一个字符,您可以定义一个函数,该函数迭代给定的消息并一次打印一个字符,在两者之间使用time.sleep等待一段时间。确保在每个字符后刷新缓冲区 import time def slow_print(msg): for c in msg: print(c, end="", flush=True) tim
time.sleep
等待一段时间。确保在每个字符后刷新缓冲区
import time
def slow_print(msg):
for c in msg:
print(c, end="", flush=True)
time.sleep(0.1)
print()
slow_print("Hello World!")
如果你真的想在游戏中的每一个输出中都应用这个功能(我不推荐这样做),你可以覆盖print
函数,保留对原始print
函数的引用,以便在新的slowprint
函数中使用
original_print = print
def slow_print(msg):
# same as above, but using original_print instead of print
print = slow_print
print("Hello World!")
您也可以直接
def print(…)
,但我建议将其定义为一个单独的函数,然后将其分配给print
。这样,您仍然可以将其设置为可选,因为这很可能会在最初几分钟后让玩家感到恼火 我假设您希望字符看起来像是有人在键入它们,所以我假设
导入模块
import os
import sys
import time
from colr import color
定义您的功能
def function_name(phrase,speed,r_value,g_value,b_value):
for char in phrase:
sys.stdout.write(color(char, fore=(r_value,g_value,b_value)))
sys.stdout.flush()
time.sleep(speed)
function_name("Hello",0.05,0,255,0)
#prints the phrase "Hello" in green text
测试功能
def function_name(phrase,speed,r_value,g_value,b_value):
for char in phrase:
sys.stdout.write(color(char, fore=(r_value,g_value,b_value)))
sys.stdout.flush()
time.sleep(speed)
function_name("Hello",0.05,0,255,0)
#prints the phrase "Hello" in green text
或者,您可以使用线程库编写函数,这将允许用户跳过键入效果,如果他们愿意的话
import time, threading, os, sys, tty, termios
from colr import color
def slow_type_interrupt(phrase,speed,r_value,g_value,b_value):
done = False # this acts as the kill switch, using if statements, you can make certain button presses stop the message printing and outright display it
def type_out():
for char in phrase:
if done:
break
sys.stdout.write(color(char,fore=(r_value,g_value,b_value)))
sys.stdout.flush()
time.sleep(speed)
os.system('clear')
print(color(phrase,fore=(r_value,g_value,b_value)))
t = threading.Thread(target=type_out)
t.start()
def getkey():
ky = sys.stdin.fileno()
Ab = termios.tcgetattr(ky)
try:
tty.setraw(sys.stdin.fileno())
key = sys.stdin.read(1)
finally:
termios.tcsetattr(ky, termios.TCSADRAIN, Ab)
return key
while not done:
key_press = getkey()
if key_press == 'a': #You can replace a with whatever key you want to act as the "kill key"
done = True
os.system('clear')
print(color(phrase,fore=(r_value,g_value,b_value)))
slow_type_interrupt("Hello this is a test. Pressing 'a' will end this and immediatley display the message",.05,0,255,0)
正如我在代码注释中提到的,a可以被您想要的任何东西替换。我之所以使用这个特殊的方法来检索按键,是因为它几乎适用于任何运行Python的东西。我建议大家阅读一些其他检索键盘输入的方法
希望我能提供帮助:)什么是“打字效果”?OP可能意味着一次显示一个字符,这肯定会在5分钟后让用户感到厌烦。如果你知道如何对给定文本执行此操作,请为其编写一个函数并调用该函数,而不是调用
print
。(我肯定记得不久前回答过这样一个问题,但不知道该搜索什么…)