Search code examples
python-3.xrandompygamereadlines

Trying to add text from a random line from a text file


I am making a game in pygame for my sister for practising in pygame and I am trying to add a random line from a text file in to window name:

import 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

I have all the rest of the code in case anyone says that I haven't done any other code to make the window or anything. I want it to say: Dream Land: {} then in the braces add a random line from the file.


Solution

  • You're looking for readlines() and 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))