【问题标题】:Trying to add text from a random line from a text file尝试从文本文件中的随机行添加文本
【发布时间】:2017-08-27 09:33:25
【问题描述】:

我正在为我姐姐在 pygame 中练习制作一个 pygame 游戏,我正在尝试将文本文件中的随机行添加到窗口名称中:

导入 pygame,random,sys

RandomMess = open('GameText.txt')
pygame.display.set_caption('Dream Land: {}').
#The .txt file currently has 4 lines but will be a lot more in the future... 
#These are the test lines: This is in beta, hi :), hello, hi

如果有人说我没有编写任何其他代码来制作窗口或其他任何东西,我拥有所有其余的代码。 我想说:Dream Land: {} 然后在大括号中添加文件中的随机行。

【问题讨论】:

    标签: python-3.x random pygame readlines


    【解决方案1】:

    您正在寻找 readlines() 和 random.choice()。

    import random,sys
    
    RandomMess = open('GameText.txt')
    
    # .readlines() will create a list of the lines in the file.
    # So in our case ['This is in beta', 'hi :)', 'hello', 'hi']
    # random.choice() then picks one item from this list.
    line = random.choice(RandomMess.readlines())
    
    # Then use .format() to add the line into the caption
    pygame.display.set_caption('Dream Land: {}'.format(line))
    

    【讨论】:

      猜你喜欢
      • 2016-11-25
      • 2017-10-20
      • 1970-01-01
      • 2017-09-27
      • 2015-11-26
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多