# How to make a Infinite Verticle Scrolling Background in Pygame

Is there anyone who knows how to create an infinite verticle scrolling background in pygame?

The idea behind infinitely scrolling backgrounds is pretty simple. You simply draw the background enough many times to fill the screen, and once a piece of the background moves off screen, you loop the rendering and start back from the beginning.

So, the basic functionality would go as follows: (pseudo code, should be easily adaptable to PyGame)

piece = yourBackgroundImage;
pieceHeight = piece.h;

scrollY = 0;

for (pieceY = (scrollY % pieceHeight) - pieceHeight; pieceY < screenHeight; pieceY += pieceHeight)
{
render(piece, 0, pieceY);
}


First, you take your background image you want to loop. You need to know it's height, as that's what we used to calculate how often we need to render it. The scrollY variable in the code above is the value you would modify in your main loop to create the scrolling effect.

Now, the loop is slightly more complicated, but not much. We start by calculating how much vertical movement there is along a single piece (scrollY % pieceHeight). We need to decrease that value by a single piece height, to make sure that the whole screen gets filled (you can try it without the decrement, and see that there will be a small piece of the background missing at the top of the screen). We will iterate as long as there is screen space to fill, and increment each step by the background image's height.

That should do it, and the algorithm is of course easily translatable to horizontal movement too.

• When i tried to implement your code, I got a syntax error saying that the equal sign after "backgroundY" in "for (backgroundY = (scrollY % backgroundHeight) - backgroundHeight, backgroundY < screenHeight; backgroundY += backgroundHeight):" is a syntax error. This is my code: background = pygame.image.load(path.join(img_dir, "Backgrounds/1.jpg")).convert() backgroundHeight = background.h scrollY = 0 for (backgroundY = (scrollY % backgroundHeight) - backgroundHeight, backgroundY < screenHeight, backgroundY += backgroundHeight): render(background, 0, backgroundHeight) – Tahmid RAhman Jul 17 '16 at 11:40
• As I said, it's pseudo code. You obviously need to convert the for loop (among the rest of the code) to the Python syntax. – Tyyppi_77 Jul 17 '16 at 11:41