Trying to make the text to my pygame program scroll up

  • (2 Pages)
  • +
  • 1
  • 2

23 Replies - 2302 Views - Last Post: 26 December 2016 - 04:45 PM Rate Topic: -----

#1 albert003   User is online

  • D.I.C Addict

Reputation: 37
  • View blog
  • Posts: 779
  • Joined: 15-December 14

Trying to make the text to my pygame program scroll up

Posted 18 December 2016 - 05:27 PM

Ok, I'm trying to make a program as a joke for my wife for the holiday season based on the Christmas poem T'was the night before Christmas. I want to make the text scroll up kind of like the introduction to the star wars movies. I know how to make the text scroll up when I use python. But when I use pyagme I can't figure out how to have the first text scroll but and then have the following text scroll up right behind it at the same speed. I honestly can't figure out how to do this using pygame. You see, if I was using just python, that would be easy. I could do this....

def string():
	import time
	text=[]
	text.append("T'was the night before maintenance")
	text.append("when all through the data centre,")
	text.append("not a server was amber which was")
	text.append("all for the better.")
	for i in range(len(text)):
		print text[i]
		time.sleep(.5)


I cant figure how to make this work the only other way would be to have pygame render each text one after another and that to me seems like a waste of time and space.This is my program so far. I've only been able to have one line scroll up, when I try to add a second line, they write over each other. So my two questions are: How to make the text scroll up without writing one ontop of another and how to make it happen using a list?.I left it with the function that I tried to make a list and with the program calling each text without using a list on it (calling each text one by one and then to blit it). Any and all help would be greatly appreciated.

import pygame
 
# Define some colors
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
 
pygame.init()
 
# Set the width and height of the screen [width, height]
size = (700,600)
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("scrolling message")
 
# Loop until the user clicks the close button.
done = False
 
# Used to manage how fast the screen updates
clock = pygame.time.Clock()

def poem():
    text=[]
    text.append("T'was the night before maintenance")
    text.append("when all through the data centre,")
    text.append("not a server was amber which was")
    text.append("all for the better.")#My line I put in
    text.append("The fibre was hung")
    text.append("on the racks with care,")
    text.append("in the hopes that there were no finger")
    text.append("prints hither or there.")
    text.append("The operators were nestled")
    text.append("all snug in the war room,")
    text.append("staring at their monitors with")
    text.append("the sense of impending doom.")
    text.append("The linux admin with a beard")
    text.append("and a stocking cap,")
    text.append("was huddled in the corner")
    text.append("working on Nmap.")
    text.append("When out from our cell phones")
    text.append("arose such a clatter,")
    text.append("we sprung to our feet to")
    text.append("see what was the matter.")
    text.append("Into the data centre we ran like a dash,")
    text.append("set up KVM and cleared the cache.")
    text.append("Coming a breast to the blue screen")
    text.append("of death, ")
    text.append("I scribbled the hex stop code")
    text.append("in one single breath.")
    text.append("PowerShell I wrote from my,")
    text.append("keyboard below,")#my line
    text.append("prevented the problem")
    text.append("that was there a moment ago.")#my line
    text.append("But what should appear by the curser")#my line
    text.append("of my screen,")
    text.append("pop up chat window from the manager")
    text.append("of my team.")#my line
    text.append("Reset all the servers that are down,")#my line
    text.append("to fix the problems so customers")
    text.append("won't frown.")#my line
    text.append("Away the servers turned on in the war")
    text.append("room mainframe,")
    text.append("As they turned on I called")#my line
    text.append("them all by their name.")
    text.append("on IRC, on FTP,on Windows server,")
    text.append("on Red Hat, on Proxy, on Mail,")
    text.append("on application, ")
    text.append("I called out with such fervor.")
    return (text)
text1="T'was the night before maintenance"
font = pygame.font.Font(None,30)

recty = 580
# -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
 
    # --- Game logic should go here
 
    # --- Screen-clearing code goes here
 
    # Here, we clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
 
    # If you want a background image, replace this clear with blit'ing the
    # background image.
    screen.fill(black)
    text = font.render(text1,True,green)
    screen.blit(text,[0,recty])
    recty -=1
    
    # --- Drawing code should go here
 
    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
    clock.tick(60)
 
# Close the window and quit.
pygame.quit()



Is This A Good Question/Topic? 0
  • +

Replies To: Trying to make the text to my pygame program scroll up

#2 DK3250   User is online

  • Pythonian
  • member icon

Reputation: 560
  • View blog
  • Posts: 1,765
  • Joined: 27-December 13

Re: Trying to make the text to my pygame program scroll up

Posted 19 December 2016 - 12:46 AM

You can assign positions outside the size of 'screen'.
Then just shift the y-value in a loop; here, only the backbone is shown:
y_pos = 0
while True:
    screen.fill(black)
    for num, line in enumerate(text):
        screen.blit(line, (0, num*20+y_pos))  # assuming a line distance of 20
    pygame.display.flip()
    y_pos -= 20  # this will make the text scroll upward
This requires that the list 'text' holds rendered versions of the individual lines.
Essentially, you blit all lines in every pass, but some lines will be located outside the screen.

This post has been edited by DK3250: 19 December 2016 - 12:47 AM

Was This Post Helpful? 1
  • +
  • -

#3 DK3250   User is online

  • Pythonian
  • member icon

Reputation: 560
  • View blog
  • Posts: 1,765
  • Joined: 27-December 13

Re: Trying to make the text to my pygame program scroll up

Posted 20 December 2016 - 12:12 PM

I guess that you have now solved the scroll issue.
Maybe I can challenge you to make the text appear to flow into the screen, like in the Starwars opening scene.

For inspiration, a have uploaded this small video (.AVI file): https://www.mediafir...c64clhbo8j505n0
It is a quite large file, it downloads in a minut via broadband, but requires 30 minutes using DSL.

Attached File  image0002.bmp (1.2MB)
Number of downloads: 55

EDIT: A single picture is attached here.

This post has been edited by DK3250: 20 December 2016 - 12:25 PM

Was This Post Helpful? 0
  • +
  • -

#4 albert003   User is online

  • D.I.C Addict

Reputation: 37
  • View blog
  • Posts: 779
  • Joined: 15-December 14

Re: Trying to make the text to my pygame program scroll up

Posted 20 December 2016 - 02:42 PM

Actually, I haven't I'll be honest with you, I looked at your suggestion and I drew a blank. I was playing around with the program trying to figure out whether I was suppose to put that while loop in the game loop or in a separate loop within a function and then call it (like I did in a previous program you helped me work on). I still haven't had any luck with it and I don't want you to feel like you have to hold my hand and give me the answers each time I have a question. I really do appreciate your help and believe me your hints or ideas have paved the way to brain storms of programs I haven't posted here. And that video link just gave me an idea on how to make it work.
Was This Post Helpful? 1
  • +
  • -

#5 DK3250   User is online

  • Pythonian
  • member icon

Reputation: 560
  • View blog
  • Posts: 1,765
  • Joined: 27-December 13

Re: Trying to make the text to my pygame program scroll up

Posted 21 December 2016 - 02:25 AM

Don't be afraid or reluctant to ask!!
I and others here on DIC are just happy to help - as long as we see some effort from the OP (you).
I have up-voted you for your honesty.

The while-loop in my post #2 is the same as yours in line 76 of post #1
My line 3 is your line 91.

I suggest you update the list 'text' with rendered versions of the individual lines.
Then you don't need to render over and over again in each pass of the loop.

Then, try to substitute your line 92-94 with my line 4-5, and add my line 7 in an appropriate position (change the increment value from 20 to 2).

And finally: Don't hesitate to ask!
Was This Post Helpful? 1
  • +
  • -

#6 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7492
  • View blog
  • Posts: 15,527
  • Joined: 16-October 07

Re: Trying to make the text to my pygame program scroll up

Posted 21 December 2016 - 05:34 AM

I thought I'd play with this a bit.

First pass:
import pygame

# globals... for the colors, ok, for the code, not good
# however, rather than color names, use purpose names
C_BACKGROUND = (0, 0, 0)
C_TEXT = (0, 255, 0)

def render_text(screen, font, text, x, y):
    img = font.render(text, True, C_TEXT)
    screen.blit(img,[x,y])

def render(screen, font,  text, x, y):
    screen.fill(C_BACKGROUND)
    render_text(screen, font, text, x, y)


def main():
    # Define some colors
    # black = (0, 0, 0)
    # white = (255, 255, 255)
    # green = (0, 255, 0)
    # red = (255, 0, 0)
    
    pygame.init()
    
    # Set the width and height of the screen [width, height]
    size = (700,600)
    screen = pygame.display.set_mode(size)
    
    pygame.display.set_caption("scrolling message")
    
    # Loop until the user clicks the close button.
    done = False
    
    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()


    text1="T'was the night before maintenance"
    font = pygame.font.Font(None,30)

    recty = 580
    # -------- Main Program Loop -----------
    while not done:
        # --- Main event loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
    
        render(screen, font, text1, 0, recty)
        recty -=1

        pygame.display.flip()
        clock.tick(60)
    
    # Close the window and quit.
    pygame.quit()


# all that append made me sad
def poem():
    return [
        "T'was the night before maintenance",
        "when all through the data centre,",
        "not a server was amber which was",
        "all for the better.",
        "The fibre was hung",
        "on the racks with care,",
        "in the hopes that there were no finger",
        "prints hither or there.",
        "The operators were nestled",
        "all snug in the war room,",
        "staring at their monitors with",
        "the sense of impending doom.",
        "The linux admin with a beard",
        "and a stocking cap,",
        "was huddled in the corner",
        "working on Nmap.",
        "When out from our cell phones",
        "arose such a clatter,",
        "we sprung to our feet to",
        "see what was the matter.",
        "Into the data centre we ran like a dash,",
        "set up KVM and cleared the cache.",
        "Coming a breast to the blue screen",
        "of death, ",
        "I scribbled the hex stop code",
        "in one single breath.",
        "PowerShell I wrote from my,",
        "keyboard below,",
        "prevented the problem",
        "that was there a moment ago.",
        "But what should appear by the curser",
        "of my screen,",
        "pop up chat window from the manager",
        "of my team.",
        "Reset all the servers that are down,",
        "to fix the problems so customers",
        "won't frown.",
        "Away the servers turned on in the war",
        "room mainframe,",
        "As they turned on I called",
        "them all by their name.",
        "on IRC, on FTP,on Windows server,",
        "on Red Hat, on Proxy, on Mail,",
        "on application, ",
        "I called out with such fervor.",
    ]

main()



So, I've done nothing new here, other than isolate my render logic and remove extra junk.

Let's render two lines.
import pygame

C_BACKGROUND = (0, 0, 0)
C_TEXT = (0, 255, 0)

def render_lines(screen, font, lines, x, y):
    for line in lines:
        img = font.render(line, True, C_TEXT)
        screen.blit(img,[x,y])
        y += 30 # just some number, this could be worked out

def main(lines):
    pygame.init()
    
    size = (700,600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("scrolling message")
    clock = pygame.time.Clock()
    font = pygame.font.Font(None,30)

    recty = 580
    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
        screen.fill(C_BACKGROUND)
        render_lines(screen, font, lines, 0, recty)
        recty -=1

        pygame.display.flip()
        clock.tick(60)
    pygame.quit()

main([
    "T'was the night before maintenance",
    "when all through the data centre,",
])



Ok, so that's basically an answer. You can see I changed the functions around a little, upon further consideration. I don't like just throwing answers, so if you have any questions about it, please ask.

Improvements I would make include figuring out the proper y increment from font size and stopping when the entire message scrolls off the screen.

Enjoy.
Was This Post Helpful? 0
  • +
  • -

#7 DK3250   User is online

  • Pythonian
  • member icon

Reputation: 560
  • View blog
  • Posts: 1,765
  • Joined: 27-December 13

Re: Trying to make the text to my pygame program scroll up

Posted 22 December 2016 - 01:07 AM

I am not so happy about doing the render inside the loop. This will lead to a lot of repetitive rendering. I have modified baavgai's solution to avoid this.
import pygame

C_BACKGROUND = (0, 0, 0)
C_TEXT = (0, 255, 0)

def render_lines(font, lines):
    pics = []
    for line in lines:
        pics.append(font.render(line, True, C_TEXT))
    return pics

def draw(screen, lines, y):
    for line in lines:
        screen.blit(line, (0, y))
        y += 20

def main(lines):
    pygame.init()
    
    size = (700,600)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("scrolling message")
    clock = pygame.time.Clock()
    font = pygame.font.Font(None,30)
    
    text = render_lines(font, lines)
    
    recty = 580
    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
        screen.fill(C_BACKGROUND)
        draw(screen, text, recty)
        recty -=1

        pygame.display.flip()
        clock.tick(60)
    pygame.quit()

main([
    "T'was the night before maintenance",
    "when all through the data centre,",
])

Usually I place the variables that don't change in the true main such that they are available as constants.
Line 18-24 I would place below line 4 and reduce the arguments in the function calls (font and screen).
Was This Post Helpful? 0
  • +
  • -

#8 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7492
  • View blog
  • Posts: 15,527
  • Joined: 16-October 07

Re: Trying to make the text to my pygame program scroll up

Posted 22 December 2016 - 06:13 AM

@DK3250: I was confused by "render inside the loop." I had to look at the code.

So, you feel that a surface shouldn't be generated more than once? That makes sense. Seemed beyond the scope here, but as we're already down the rabbit hole...

I'll take it a step further; an object shouldn't be initialized until needed. That is, lazy loading. Not a big deal at this scale, but could be useful. I played around with doing this strictly function based. It can be done, but Python closures make things messy; easier just to use a proper object.

My overly worried out solution:
import pygame

class TextScroller(object):
    def __init__(self, lines, step, font, color, x = 0):
        self.step, self.font, self.color, self.x = step, font, color, x
        self.lines = [ (None, x) for x in lines]
        self.offset = 0
        self.running = True

    def get_img(self, idx):
        img, txt = self.lines[idx]
        if not img:
            print("render", idx, txt)
            img = self.font.render(txt, True, self.color)
            self.lines[idx] = img, txt
        return img
    
    def render(self, screen):
        _, screen_y = screen.get_size()
        y = screen_y - self.offset
        for i in range(len(self.lines)):
            img = self.get_img(i)
            h = img.get_height()
            if y + h > 0:
                screen.blit(img, (0, y))
            y += h
            if y>screen_y:
                break
        self.offset += self.step
        self.running = y > 0
        return self.running


def get_scroller():
    lines = [
        "Tomorrow, and tomorrow, and tomorrow,",
        "Creeps in this petty pace from day to day,",
        "To the last syllable of recorded time;",
        "And all our yesterdays have lighted fools",
        "The way to dusty death. Out, out, brief candle!",
        "Life's but a walking shadow, a poor player,",
        "That struts and frets his hour upon the stage,",
        "And then is heard no more. It is a tale",
        "Told by an idiot, full of sound and fury,",
        "Signifying nothing."
        ]
    return TextScroller(lines, 1, pygame.font.Font(None,30), (0, 255, 0))

def main():
    def events():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
        return True

    pygame.init()
    screen = pygame.display.set_mode((700,600))
    pygame.display.set_caption("scrolling message")
    scroller = get_scroller()

    running, clock = True, pygame.time.Clock()
    while running:
        running = events()
        if running:
            screen.fill((0, 0, 0))
            running = scroller.render(screen)
        if running:
            pygame.display.flip()
            clock.tick(20)
    pygame.quit()

main()



I slowed it down and left my test print in so it can be seen in action. This also include a flag for when nothing is showing, or will be showing, so you know you can leave. It bases it's position as an offset from the bottom of the screen, meaning the superfluous value needn't be defined. Also, cleaner exit.
Was This Post Helpful? 0
  • +
  • -

#9 DK3250   User is online

  • Pythonian
  • member icon

Reputation: 560
  • View blog
  • Posts: 1,765
  • Joined: 27-December 13

Re: Trying to make the text to my pygame program scroll up

Posted 22 December 2016 - 09:08 AM

@baavgai: I really appreciate the coding pattern.

Couldn't resist a few changes:
I wanted to get rid of the repetitive 'get_height()' and 'get_size' in the render method.
To this I added the image height in the img tuple and a Game class to handle the basic pygame components.
Then I moved the basic game loop to the Game class and sanitized a bit.

I know we are discussing small differences (the two versions do the same), but optimizing a code pattern is often in the details.
import pygame

class TextScroller(object):
    def __init__(self, lines, step, font, color, x = 0):
        self.step, self.font, self.color, self.x = step, font, color, x
        self.lines = [ (None, 0, line) for line in lines]
        self.offset = 0
        self.running = True

    def get_img(self, idx):
        img, height, txt = self.lines[idx]
        if not img:
            #print("render", idx, txt)
            img = self.font.render(txt, True, self.color)
            self.lines[idx] = img, img.get_height(), txt
        return img, height
    
    def render(self, game):
        y = game.y - self.offset
        for i in range(len(self.lines)):
            img, h = self.get_img(i)
            if y + h > 0:
                game.screen.blit(img, (0, y))
            y += h
            if y > game.y:
                break
        self.offset += self.step
        self.running = y > 0
        return self.running


class Game(object):
    def __init__(self, x_size, y_size):
        pygame.init()
        self.screen = pygame.display.set_mode((x_size, y_size))
        pygame.display.set_caption("scrolling message")
        self.x = x_size  # self.x is currently not in use 
        self.y = y_size
        self.clock = pygame.time.Clock()
        self.running = True

    def events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
        return True

    def loop(self, scroller):
        while self.running:
            self.running = self.events()
            if self.running:
                self.screen.fill((0, 0, 0))
                self.running = scroller.render(self)
                pygame.display.flip()
            self.clock.tick(60)
        


def get_scroller():
    lines = [
        "Tomorrow, and tomorrow, and tomorrow,",
        "Creeps in this petty pace from day to day,",
        "To the last syllable of recorded time;",
        "And all our yesterdays have lighted fools",
        "The way to dusty death. Out, out, brief candle!",
        "Life's but a walking shadow, a poor player,",
        "That struts and frets his hour upon the stage,",
        "And then is heard no more. It is a tale",
        "Told by an idiot, full of sound and fury,",
        "Signifying nothing."
        ]
    return TextScroller(lines, 1, pygame.font.Font(None,30), (0, 255, 0))


def main():
    game = Game(700, 600)
    scroller = get_scroller()
    
    game.loop(scroller)
    pygame.quit()


main()


Was This Post Helpful? 0
  • +
  • -

#10 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7492
  • View blog
  • Posts: 15,527
  • Joined: 16-October 07

Re: Trying to make the text to my pygame program scroll up

Posted 22 December 2016 - 10:02 AM

View PostDK3250, on 22 December 2016 - 11:08 AM, said:

I wanted to get rid of the repetitive 'get_height()' and 'get_size' in the render method.


Ok, get_height() isn't repetitive, it's simply asking for a property of the object. Caching it elsewhere seems more redundant. To be fair, I did briefly consider it. ;)

While get_size is also just a property. However, here it cannot be stored: because it can change!

Having a Game object to control global state can make sense, but I find life is easier if I can keep to functions. Also, if you're going to do that, I'm not sure the logic of passing the scroller in rather that just creating an instance on init.

Here's a version that allows the screen to change and adapts accordingly:
import pygame

class TextScroller(object):
    def __init__(self, lines, step, font, color, x = 0):
        self.step, self.font, self.color, self.x = step, font, color, x
        self.lines = [ (None, x) for x in lines]
        self.offset = 0
        self.running = True

    def get_img(self, idx):
        img, txt = self.lines[idx]
        if not img:
            # print("render", idx, txt)
            img = self.font.render(txt, True, self.color)
            self.lines[idx] = img, txt
        return img
    
    def render(self, screen):
        _, screen_y = screen.get_size()
        y = screen_y - self.offset
        for i in range(len(self.lines)):
            img = self.get_img(i)
            h = img.get_height()
            if y + h > 0:
                screen.blit(img, (0, y))
            y += h
            if y>screen_y:
                break
        self.offset += self.step
        self.running = y > 0
        return self.running


def get_scroller():
    lines = [
        "Tomorrow, and tomorrow, and tomorrow,",
        "Creeps in this petty pace from day to day,",
        "To the last syllable of recorded time;",
        "And all our yesterdays have lighted fools",
        "The way to dusty death. Out, out, brief candle!",
        "Life's but a walking shadow, a poor player,",
        "That struts and frets his hour upon the stage,",
        "And then is heard no more. It is a tale",
        "Told by an idiot, full of sound and fury,",
        "Signifying nothing."
        ]
    return TextScroller(lines, 1, pygame.font.Font(None,30), (0, 255, 0))

def get_screen(w,h):
    return pygame.display.set_mode((w,h), pygame.RESIZABLE)

def main():
    pygame.init()
    pygame.display.set_caption("scrolling message")
    SCROLL_EVENT = pygame.USEREVENT + 1
    scroller = get_scroller()
    pygame.time.set_timer(SCROLL_EVENT, 20)
    screen = get_screen(700,600)
    while screen:
        event = pygame.event.wait()
        if event.type == pygame.QUIT:
            screen = None
        elif event.type == pygame.VIDEORESIZE:
            screen = get_screen(event.w, event.h)
        elif event.type == SCROLL_EVENT:
            screen.fill((0, 0, 0))
            running = scroller.render(screen)
            pygame.display.flip()
    pygame.quit()

main()



Note, I got tired of the clock.tick wait thingy, which seems super cludgy to me. I instead changed to a pure event model.
Was This Post Helpful? 0
  • +
  • -

#11 DK3250   User is online

  • Pythonian
  • member icon

Reputation: 560
  • View blog
  • Posts: 1,765
  • Joined: 27-December 13

Re: Trying to make the text to my pygame program scroll up

Posted 22 December 2016 - 10:26 AM

Ok, - points taken!
You have a small error preventing the proper ending when the text is out.
I've rectified - and updated the poem :rolleyes:
import pygame

class TextScroller(object):
    def __init__(self, lines, step, font, color, x = 0):
        self.step, self.font, self.color, self.x = step, font, color, x
        self.lines = [ (None, x) for x in lines]
        self.offset = 0
        self.running = True

    def get_img(self, idx):
        img, txt = self.lines[idx]
        if not img:
            # print("render", idx, txt)
            img = self.font.render(txt, True, self.color)
            self.lines[idx] = img, txt
        return img
    
    def render(self, screen):
        _, screen_y = screen.get_size()
        y = screen_y - self.offset
        for i in range(len(self.lines)):
            img = self.get_img(i)
            h = img.get_height()
            if y + h > 0:
                screen.blit(img, (0, y))
            y += h
            if y>screen_y:
                break
        self.offset += self.step
        self.running = y > 0
        return self.running


def get_scroller():
    lines = ["Go on a starlit night,",
             "stand on your head,",
             "leave your feet dangling",
             "outwards into space,",
             "and let the starry",
             "firmament you tread",
             "be, for the moment,",
             "your elected base.",
             " ",
             "Feel Earth's colossal weight",
             "of ice and granite,",
             "of molten magma,",
             "water, iron, and lead;",
             "and briefly hold",
             "this strangely solid planet",
             "balanced upon",
             "your strangely solid head."]
    return TextScroller(lines, 1, pygame.font.Font(None,30), (0, 255, 0))

def get_screen(w,h):
    return pygame.display.set_mode((w,h), pygame.RESIZABLE)

def main():
    pygame.init()
    pygame.display.set_caption("scrolling message")
    SCROLL_EVENT = pygame.USEREVENT + 1
    scroller = get_scroller()
    pygame.time.set_timer(SCROLL_EVENT, 20)
    screen = get_screen(700,600)
    running = True
    while running:
        event = pygame.event.wait()
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.VIDEORESIZE:
            screen = get_screen(event.w, event.h)
        elif event.type == SCROLL_EVENT:
            screen.fill((0, 0, 0))
            running = scroller.render(screen)
            pygame.display.flip()
    pygame.quit()

main()


Was This Post Helpful? 0
  • +
  • -

#12 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7492
  • View blog
  • Posts: 15,527
  • Joined: 16-October 07

Re: Trying to make the text to my pygame program scroll up

Posted 22 December 2016 - 11:09 AM

Nice catch.

Here's the patched version ( I was trying to ditch the running bool ) with new, seasonal, poem.
import pygame

class TextScroller(object):
    def __init__(self, lines, step, font, color, x = 0):
        self.step, self.font, self.color, self.x = step, font, color, x
        self.lines = [ (None, x) for x in lines]
        self.offset = 0
        self.running = True

    def get_img(self, idx):
        img, txt = self.lines[idx]
        if not img:
            # print("render", idx, txt)
            img = self.font.render(txt, True, self.color)
            self.lines[idx] = img, txt
        return img
    
    def render(self, screen):
        _, screen_y = screen.get_size()
        y = screen_y - self.offset
        for i in range(len(self.lines)):
            img = self.get_img(i)
            h = img.get_height()
            if y + h > 0:
                screen.blit(img, (0, y))
            y += h
            if y>screen_y:
                break
        self.offset += self.step
        self.running = y > 0
        return self.running


def get_scroller():
    lines = [
        "i kannizt vi jlakttinn", 
        "- s kttur var griarstr",
        "Flk vissi'ekki hvaan hann kom", 
        "ea hvert hann fr",
        "",
        "Hann glennti upp glyrnurnar sinar", 
        "glandi bar tvr",
        "a var ekki heiglum hent", 
        "a horfa  r",
        ]
    return TextScroller(lines, 1, pygame.font.Font(None,30), (0, 255, 0))

def get_screen(w,h):
    return pygame.display.set_mode((w,h), pygame.RESIZABLE)

def main():
    pygame.init()
    pygame.display.set_caption("scrolling message")
    SCROLL_EVENT = pygame.USEREVENT + 1
    scroller = get_scroller()
    pygame.time.set_timer(SCROLL_EVENT, 20)
    screen = get_screen(700,600)
    while screen:
        event = pygame.event.wait()
        if event.type == pygame.QUIT:
            screen = None
        elif event.type == pygame.VIDEORESIZE:
            screen = get_screen(event.w, event.h)
        elif event.type == SCROLL_EVENT:
            screen.fill((0, 0, 0))
            screen = {True: screen, False: None}[scroller.render(screen)]
            pygame.display.flip()
    pygame.quit()

main()


Was This Post Helpful? 0
  • +
  • -

#13 DK3250   User is online

  • Pythonian
  • member icon

Reputation: 560
  • View blog
  • Posts: 1,765
  • Joined: 27-December 13

Re: Trying to make the text to my pygame program scroll up

Posted 22 December 2016 - 11:37 AM

Yes, - I understood your target: avoiding the 'running'; the solution here (line 66) is a bit nontraditional, - but ok!

And a poem in Icelandic !! How did you stumble over that? Bjrk?
I am Danish - but can read/understand Icelandic to some extend...

Now, let's hope we didn't loose the OP completely in all this; albert003, just catch up where you find is best!
Was This Post Helpful? 0
  • +
  • -

#14 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7492
  • View blog
  • Posts: 15,527
  • Joined: 16-October 07

Re: Trying to make the text to my pygame program scroll up

Posted 22 December 2016 - 12:07 PM

View PostDK3250, on 22 December 2016 - 01:37 PM, said:

And a poem in Icelandic !! How did you stumble over that? Bjrk?
I am Danish - but can read/understand Icelandic to some extend...


Heh, I just got back from Iceland. It's a wicked language, but fun to listen to.

I was very amused by the Yule Cat ( Jlaktturinn ) and the rest of the local Yule mythology. Grla and Krampus would be a great team. There was an xmas card at the national museum with part of that Jhannes r Ktlum poem on it that I sent to a friend.

I just found out that Bjrk did a version when I was hunting for the text.
Was This Post Helpful? 0
  • +
  • -

#15 albert003   User is online

  • D.I.C Addict

Reputation: 37
  • View blog
  • Posts: 779
  • Joined: 15-December 14

Re: Trying to make the text to my pygame program scroll up

Posted 22 December 2016 - 12:45 PM

I was lost in the modifications you guys did, but my plan is to slow down and read each suggestion piece by piece. My idea I came up with last time was similar to what baavgai had. I was trying to do this in python:

word="T'was the night before maintenance\n\
twhen all through the data centre\n\
not a server was amber which was\n\
all for the better."


But using pygame. Apparently using \n in a text in pygame doesn't do the same thing as it does it python.

When you suggested i update the list 'text' with rendered versions of the individual lines.
Then you don't need to render over and over again in each pass of the loop. You were meaning for me to put in pygame.display.update()?.







I appreciate your thumbs up and I will continue to work on the program. I will continue to show my progress here so you guys on the forum can give me advice.

This post has been edited by albert003: 22 December 2016 - 01:47 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2