In this tutorial we will create a simple but cool starfield simulation with Python and Pygame. The tutorial will be very brief and accompanied by a self-explanatory small amount of code. See below a video of the simulation in action.
The Idea
To simulate the effect, we start by creating a list of stars positioned randomly across the screen. Then, in the main loop, we continuously move and draw the stars. When a star crosses the bottom screen border, we create a new star at the top of the screen.
The Code
The code is small and clear, and therefore bears a small amount of explanation. The init() function creates a list of stars positioned randomly across the screen. The move_and_draw_stars() function moves and draws the stars. When moving a star, move_and_draw_stars() checks if the star has crossed the bottom border. If so, it creates a new star at the top of the screen.
import pygame from random import randrange 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] star = [randrange(0,screen.get_width() - 1), randrange(0,screen.get_height() - 1)] 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_SPEED # 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) screen.set_at(star,(255,255,255)) def main(): # Pygame stuff pygame.init() screen = pygame.display.set_mode((640,480)) pygame.display.set_caption("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.
Conclusion
That’s everything for now. In the next tutorial I will show you how to make a parallax starfield.
To stay updated, make sure you subscribe to this blog, follow us on twitter, or follow us on facebook.
what do you do with the updated python