2017-04-02 7 views
1

Je fais un jeu pygame pour ma soeur pour la pratique dans pygame et je suis en train d'ajouter une ligne au hasard dans un fichier texte pour le nom de la fenêtre:Essayer d'ajouter du texte à partir d'une ligne au hasard dans un fichier texte

pygame importation, aléatoire, 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 

J'ai tout le reste du code au cas où quelqu'un dit que je ne l'ai pas fait tout autre code pour que la fenêtre ou quoi que ce soit. Je veux qu'il dise: Dream Land: {} alors dans les accolades, ajoutez une ligne aléatoire du fichier.

Répondre

1

Vous êtes à la recherche de readlines() et 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))