Попытка добавить текст из случайной строки из текстового файла

Я делаю игру в 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

У меня есть весь остальной код на случай, если кто-то скажет, что я не делал другого кода для создания окна или чего-то еще. Я хочу, чтобы он сказал: Страна грез: {} затем в фигурных скобках добавьте случайную строку из файла.


person tygzy    schedule 02.04.2017    source источник


Ответы (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))
person rptynan    schedule 02.04.2017