GhostFrag1
GhostFrag1

Reputation: 1037

Pygame: Writing Multiple Lines

I am working on a scoreboard function for my game in which the player inputs there name and then that is written to a text file as the scores. I have managed write to the file and display it again. But it only writes one name which currently gets overwritten every time a new name is entered. So how would I fix this? I have tried doing:

f = open('names.txt')
f.writeline(str(name))
f.close()

Here is what I am trying to get:

Name1
Name2
Name3

So how would I do a different line for each name? Thank you

I can add in multiple names but here is what happens: enter image description here The text file appears correctly but in pygame it appears incorrectly. I want it to be on separate lines like the text file.

Upvotes: 0

Views: 3716

Answers (2)

macfij
macfij

Reputation: 3209

@Maxime Lorant answer is what you want. Suppose you have a list with your names.

names = ["Name1", "Name2", "Name3"]
f = open("names.txt", "a")
for i in names:
    f.write(i + "\n")
f.close()

If names.txt was a blank file, now the content of it should like:

Name1
Name2
Name3

EDIT

Now I see what you are trying to achieve. Please see this link : http://sivasantosh.wordpress.com/2012/07/18/displaying-text-in-pygame/

Basically, the newline character won't work in pygame - you have to change the coordinates of your text rectangle. I am kinda new to pygame but I managed to do what you want and here's my naive approach (I edited code from the link above):

#...
f = open("t.txt")
lines = f.readlines()
f.close()

basicfont = pygame.font.SysFont(None, 48)
text = basicfont.render('Hello World!', True, (255, 0, 0), (255, 255, 255))
textrect = text.get_rect()
textrect.centerx = screen.get_rect().centerx
textrect.centery = screen.get_rect().centery

screen.fill((255, 255, 255))
for i in lines:
    # each i has a newline character, so by i[:-1] we will get rid of it
    text = basicfont.render(i[:-1], True, (255, 0, 0), (255, 255, 255))
    # by changing the y coordinate each i from lines will appear just
    # below the previous i
    textrect.centery += 50
    screen.blit(text, textrect)
#...

Here's the result:

Upvotes: 2

Maxime Lorant
Maxime Lorant

Reputation: 36161

As in many programming language, you can open the file in append mode, to write at the end of the current file. This can be achieve by adding a second parameter in open which is the mode:

f = open('names.txt', 'a')
f.write(str(name) + '\n')
f.close()

Upvotes: 1

Related Questions