A Cool Parallax Starfield Simulation using Python

In one of my previous tutorials, I have demonstrated how to create a simple starfield simulation using Python and Pygame. Today, we will make a few modifications in the code from that tutorial to make a pretty cool parallax starfield. The video below shows the parallax starfield in action.

The Idea

The idea of the parallax effect is to make distant objects appear to be moving slower than closer objects. As you can see in the video, distant stars are smaller and move at a slower speed, in contrast to closer stars that are faster and bigger. To make this even more interesting, I made closer stars brighter than distant stars.

The Code

If you compare this code with the code from the simple starfield tutorial, you will see I have made very few modifications. I have basically added a speed attribute to the stars, so they are now represented as a list with the format [X,Y,Speed]. The speed attribute can be 1,2 or 3, and it indicates the speed of the stars, but is also used to determine their color and size.

import pygame
from random import randrange, choice

MAX_STARS  = 250
STAR_SPEED = 2

def init_stars(screen):
  """ Create the starfield """
  global stars
  stars = []
  for i in range(MAX_STARS):
    # A star is represented as a list with this format: [X,Y,speed]
    star = [randrange(0,screen.get_width() - 1),
            randrange(0,screen.get_height() - 1),
            choice([1,2,3])]
    stars.append(star)

def move_and_draw_stars(screen):
  """ Move and draw the stars in the given screen """
  global stars
  for star in stars:
    star[1] += star[2]
    # If the star hit the bottom border then we reposition
    # it in the top of the screen with a random X coordinate.
    if star[1] >= screen.get_height():
      star[1] = 0
      star[0] = randrange(0,639)
      star[2] = choice([1,2,3])

    # Adjust the star color acording to the speed.
    # The slower the star, the darker should be its color.
    if star[2] == 1:
      color = (100,100,100)
    elif star[2] == 2:
      color = (190,190,190)
    elif star[2] == 3:
      color = (255,255,255)

    # Draw the star as a rectangle.
    # The star size is proportional to its speed.
    screen.fill(color,(star[0],star[1],star[2],star[2]))

def main():
  # Pygame stuff
  pygame.init()
  screen = pygame.display.set_mode((640,480))
  pygame.display.set_caption("Parallax Starfield Simulation")
  clock = pygame.time.Clock()

  init_stars(screen)

  while True:
    # Lock the framerate at 50 FPS
    clock.tick(50)

    # Handle events
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        return

    screen.fill((0,0,0))
    move_and_draw_stars(screen)
    pygame.display.flip()

if __name__ == "__main__":
  main()

Click here to download the source code.

Exercise

In this tutorial we made a vertical parallax starfield. Try to modify the code to make an horizontal starfield.

Conclusion

That’s everything for now. In the next tutorial I will show you how to make a 3D starfield simulation.

What do you think about this? Please comment, share or subscribe.

  1. Fantastico

  2. I came up with a modified version of this code that makes the star speeds floating-point (so there’s not just 3 visible layers of stars) and uses an image for the stars, among other minor tweaks:

    http://people.g33xnexus.com/whitelynx/blog/2011/may/19/full-parallax-starfield-pygame/

    Since the original code here wasn’t explicitly placed under any license, I’ve tentatively licensed my modified version under the MIT license. (if I should change this, please let me know!)

    • Hello David. Thank you for sharing your code with us. I have tried your code and it looks great.

      I have no concern about the use of the MIT license. Indeed, I am considering using the MIT license as the standard for my blog.

  3. Hey, thanks for the code! I’m using it to build a simple space shooter.

    I turned it into a class if anyone is interested: http://dl.dropbox.com/u/41670/stars.py

    • Hello Nick!
      I am glad to hear that.

      I would be glad to play your space shooter as soon as you finish it.

      Please, let us know of your advances.

      Thank you.

  4. Cool and simple demo!
    It took me maybe an hour to port it to Delphi XE2 and FireMonkey for iOS.
    http://blogs.embarcadero.com/pawelglowacki/2012/06/11/39651
    cheers!

  5. Hello, just wanted to say, I liked this blog post. It was helpful. Keep on posting!

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.