I'm currently trying to read text from a .txt file then display it onto a pygame window. The problem I'm facing is that it just displays nothing at all when I try to read through the whole txt file using a readline() loop. When I run the code below, it prints all the lines to the terminal but doesn't display it onto the pygame window.
import pygame
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode([800,600])
red = (255,0,0)
yellow = (255, 191, 0)
file = open('file.txt')
count = 0
while True:
count += 1
# Get next line from file
line = file.readline()
# if line is empty
# end of file is reached
if not line:
break
print("Line{}: {}".format(count, line.strip()))
file.close()
centerx, centery = screen.get_rect().centerx, screen.get_rect().centery
deltaY = centery + 50 # adjust so it goes below screen start
running =True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
screen.fill(0)
deltaY-= 1
i=0
msg_list=[]
pos_list=[]
pygame.time.delay(10)
font = pygame.font.SysFont('impact', 30)
for line in line.split('\n'):
msg=font.render(line, True, yellow)
msg_list.append(msg)
pos= msg.get_rect(center=(centerx, centery+deltaY+30*i))
pos_list.append(pos)
i=i+1
for j in range(i):
screen.blit(msg_list[j], pos_list[j])
pygame.display.update()
pygame.quit()`
What I've tried to do is use a different way to read all the text from the file but this just ends up printing the very last line in the .txt file opposed to displaying the whole thing. I believe using the readline() method would be much more effiecent as that reads the file line by line and then displays it onto the pygame window. It also might be helpful to know I am trying to display the text line by line on the window such as:
hello
bonjour
hola
welcome
file = open('file.txt')
for line in file:
movie_credits = line
file.close()
centerx, centery = screen.get_rect().centerx, screen.get_rect().centery
deltaY = centery + 50 # adjust so it goes below screen start
running =True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
screen.fill(0)
deltaY-= 1
i=0
msg_list=[]
pos_list=[]
pygame.time.delay(10)
font = pygame.font.SysFont('impact', 30)
for line in movie_credits.split('\n'):
msg=font.render(line, True, yellow)
msg_list.append(msg)
pos= msg.get_rect(center=(centerx, centery+deltaY+30*i))
pos_list.append(pos)
i=i+1
for j in range(i):
screen.blit(msg_list[j], pos_list[j])
pygame.display.update()
pygame.quit()