1

I'm creating a typing game, and I'm trying to display a random line of text from a .txt file, the only problem, when it shows up on the pygame window, it has this at the end: []. Any suggestions? Any questions on other code that isn't showed can be answered. I didn't want to post the entire thing, it's a huge mess. The words in the text file are on their own line. Here is the code that is being used:

import random
import pygame


gameDisplay = pygame.display.set_mode((display_width, display_height))

vSmallFont = pygame.font.SysFont("Comicsansms", 10)
smallFont = pygame.font.SysFont("Comicsansms", 20)
medFont = pygame.font.SysFont("Comicsansms", 45)
largeFont = pygame.font.SysFont("Comicsansms", 55)

def text_objects(text, color, size):
    if size == "small":
        textSurf = smallFont.render(text, True, color)
    elif size == "medium":
        textSurf = medFont.render(text, True, color)
    elif size == "large":
        textSurf = largeFont.render(text, True, color)
    elif size == "verySmall":
        textSurf = vSmallFont.render(text, True, color)

    return textSurf, textSurf.get_rect()


def messageToScreen(msg, color, y_displace = 0, size = "small"):
    textSurface, textRect = text_objects(msg, color, size)
    textRect.center = (display_width/2), (display_height/2) + y_displace
    gameDisplay.blit(textSurface, textRect)

#This function is later called
def randWord():
    rand = random.randint(0,1000)
    fp = open("1.txt")
    for i, line in enumerate(fp):
        if i == rand:
            messageToScreen(line,black,-200,size = "large")
    fp.close()
Martin Gergov
  • 1,556
  • 4
  • 20
  • 29
user3814609
  • 33
  • 1
  • 8
  • What happens if you print `line` without writing it to the screen? Does it still have the []? – Amy Teegarden Aug 01 '15 at 21:08
  • no, it doesn't. But when I do add each character from the line into a list,and print the list, this shows up : ['\n'] – user3814609 Aug 01 '15 at 21:10
  • That's a newline. You can use line.strip() to get rid of trailing whitespace characters. Try `messageToScreen(line.strip(),black,-200,size = "large")` – Amy Teegarden Aug 01 '15 at 21:11
  • Yay!!!! It works, thank you – user3814609 Aug 01 '15 at 21:13
  • You don't have to answer this question, but do you know if there is a way to tell if you type the entire word, and then generate a new word? – user3814609 Aug 01 '15 at 21:19
  • That's a somewhat more complicated question. I'd look for guessing games implemented in Python for hints on how to do that kind of thing. Something like https://inventwithpython.com/chapter4.html – Amy Teegarden Aug 01 '15 at 21:22

0 Answers0