简体   繁体   English

sys.stdout.write()和.flush()带变量

[英]sys.stdout.write() and .flush() with variables

I've been working on an RPG game and I like how the sys.stdout.write() and .flush() give it the effect of typing out the letters. 我一直在从事RPG游戏,我喜欢sys.stdout.write()和.flush()如何使其具有键入字母的效果。 But when I put a variable into to the sentence I want to type out, it doesn't type out any bit of the sentence, not even the parts I have in quotes (non variables). 但是,当我在要键入的句子中添加变量时,它不会键入句子的任何部分,甚至连引号中包含的部分(非变量)也没有。 I was wondering if there was a way around this that didn't include me writing seperate code blocks for the variables and what's in quotes, and maybe make it type out the variable. 我想知道是否有一种解决方法,其中不包括我为变量以及引号中的内容编写单独的代码块,或者使它键入变量。

if girl1 == True:
   t="You and",girl1realname,"have found a sandy beach while looking for a 
   place of shelter. \nWhether you look left or right, the beach ranges for 
   miles.\n"
   y=girl1realname+": 'Hey, I guess I always wanted a house on the beach...I 
   think. I can't really remember.'\n"
   for char in (t):
       time.sleep(0.05)
       sys.stdout.write(char)
       sys.stdout.flush()
   time.sleep(1)
   for char in (y):
       time.sleep(0.05)
       sys.stdout.write(char)
       sys.stdout.flush()

In your definition of t , the commas will make it a tuple. t的定义中,逗号将使其成为一个元组。 Iterating that should then write each chunk ( "You and" , girl1realname , and "have found..." ) at a time instead of each char in each chunk. 然后进行迭代,应一次写入每个块( "You and"girl1realname"have found..." ),而不是每个块中的每个char。 Replace the commas with + . +替换逗号。

Your definition of y appears to be fine. 您对y定义似乎不错。

As for reusing, you can define a function like: 至于重用,您可以定义一个函数,例如:

def typeout(x):
  for char in x:
    time.sleep(0.05)
    sys.stdout.write(char)
    sys.stdout.flush()

Used like: 像这样使用:

typeout(t)
time.sleep(1)
typeout(y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM